1use std::collections::HashMap;
25use std::sync::{Mutex, OnceLock};
26use std::time::{Duration, Instant};
27
28use serde_json::{json, Value};
29
30use crate::server::browser_actions::{How, Kind};
31use crate::server::browser_powers::{self, Power};
32use crate::server::AppState;
33
34pub(crate) const BYPASS_META_KEY: &str = "browser:bypass";
36
37pub(crate) const CHOICES_MINUTES: [u64; 3] = [15, 60, 240];
39pub(crate) const DEFAULT_MINUTES: u64 = 60;
40
41pub(crate) const REQUEST_COOLDOWN: Duration = Duration::from_secs(10 * 60);
44
45pub(crate) const IDLE_LIMIT: Duration = Duration::from_secs(15 * 60);
50pub(crate) const IDLE_REASON: &str = "no activity for 15 minutes";
51const TIME_UP_REASON: &str = "its time ran out";
52
53#[derive(Debug, Clone)]
54pub(crate) struct Grant {
55 pub id: String,
58 pub agent: String,
59 pub origins: Vec<String>,
61 pub powers: Vec<Power>,
63 pub minutes: u64,
64 pub expires: Instant,
65 pub expires_at_ms: i64,
67 last_active: Instant,
69 pub paused_at: Option<Instant>,
73 pub standing: Option<String>,
76}
77
78impl Grant {
79 fn live(&self) -> bool {
80 self.paused_at.is_some() || Instant::now() < self.expires
81 }
82
83 fn left(&self, now: Instant) -> Duration {
85 self.expires.saturating_duration_since(self.paused_at.unwrap_or(now))
86 }
87
88 pub(crate) fn minutes_left(&self) -> u64 {
89 self.left(Instant::now()).as_secs().div_ceil(60)
90 }
91
92 fn hold(&mut self, hold: bool, now: Instant) -> bool {
96 match (hold, self.paused_at) {
97 (true, None) if now < self.expires => self.paused_at = Some(now),
98 (false, Some(at)) => {
99 (self.expires, self.expires_at_ms) =
100 crate::server::browser_actions::resumed_clock(self.expires, self.expires_at_ms, at, now);
101 self.last_active += now.saturating_duration_since(at);
102 self.paused_at = None;
103 }
104 _ => return false,
105 }
106 true
107 }
108
109 fn shorten(&mut self, minutes: u64, now: Instant) -> Option<u64> {
112 let dur = Duration::from_secs(minutes * 60);
113 if self.standing.is_some() || self.left(now) <= dur {
114 return None;
115 }
116 let was = self.minutes_left();
117 self.expires = self.paused_at.unwrap_or(now) + dur;
118 let paused_for = self.paused_at.map_or(Duration::ZERO, |at| now.saturating_duration_since(at));
120 self.expires_at_ms = chrono::Utc::now().timestamp_millis() - paused_for.as_millis() as i64 + dur.as_millis() as i64;
121 self.minutes = minutes;
122 Some(was)
123 }
124
125 pub(crate) fn allows(&self, power: Power) -> bool {
126 self.powers.contains(&power)
127 }
128
129 pub(crate) fn satisfies(&self, power: Power) -> bool {
133 match power {
134 Power::TerminalAsk => self.allows_terminal(),
135 p => self.allows(p),
136 }
137 }
138
139 pub(crate) fn allows_terminal(&self) -> bool {
141 self.allows(Power::Terminal) || self.allows(Power::TerminalAsk)
142 }
143
144 pub(crate) fn asks_each_line(&self) -> bool {
147 self.allows(Power::TerminalAsk)
148 }
149
150 pub(crate) fn covers(&self, url: &str) -> bool {
153 agentmux_common::allowed_origins::target_origin(url).is_some()
154 && agentmux_common::allowed_origins::allows(&self.origins, url)
155 }
156}
157
158struct Live {
161 grant: Grant,
162 state: Option<AppState>,
163}
164
165#[derive(Default)]
166struct Table {
167 grants: HashMap<String, Live>,
168 declined: HashMap<String, Instant>,
169}
170
171fn table() -> std::sync::MutexGuard<'static, Table> {
172 static T: OnceLock<Mutex<Table>> = OnceLock::new();
173 T.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
174}
175
176pub(crate) fn clamp_minutes(asked: Option<u64>) -> u64 {
179 let Some(asked) = asked else { return DEFAULT_MINUTES };
180 CHOICES_MINUTES
181 .iter()
182 .rev()
183 .find(|m| **m <= asked)
184 .copied()
185 .unwrap_or(CHOICES_MINUTES[0])
186}
187
188pub(crate) fn shorten(state: &AppState, pane: &str, agent: &str, minutes: u64) -> Option<(Grant, u64)> {
192 let (g, was) = {
193 let mut t = table();
194 let live = t.grants.get_mut(pane)?;
195 if !live.grant.live() || !live.grant.agent.eq_ignore_ascii_case(agent) {
196 return None;
197 }
198 let was = live.grant.shorten(minutes, Instant::now())?;
199 (live.grant.clone(), was)
200 };
201 publish(state, pane, strip_value(&g));
202 let detail = format!("cut from {was} to {minutes} min, as the agent asked");
203 crate::server::browser_actions::note(pane, agent, Kind::AutoApproveOn).detail(&detail).how(How::Allowed).record(state);
204 tokio::spawn(watch(state.clone(), pane.to_string(), g.id.clone(), IDLE_LIMIT));
206 Some((g, was))
207}
208
209pub(crate) fn active_for(pane: &str, agent: &str) -> Option<Grant> {
212 let mut t = table();
213 let g = t.grants.get(pane)?.grant.clone();
214 if !g.live() {
215 t.grants.remove(pane);
216 return None;
217 }
218 g.agent.eq_ignore_ascii_case(agent).then_some(g)
219}
220
221pub(crate) fn active_for_any(pane: &str) -> bool {
223 table().grants.get(pane).is_some_and(|l| l.grant.live())
224}
225
226pub(crate) fn is_standing(pane: &str) -> bool {
228 table().grants.get(pane).is_some_and(|l| l.grant.standing.is_some() && l.grant.live())
229}
230
231pub(crate) fn cooling_down(pane: &str) -> Option<Duration> {
233 let mut t = table();
234 let at = *t.declined.get(pane)?;
235 let left = REQUEST_COOLDOWN.checked_sub(at.elapsed());
236 if left.is_none() {
237 t.declined.remove(pane);
238 }
239 left
240}
241
242pub(crate) fn note_declined(pane: &str) {
243 table().declined.insert(pane.to_string(), Instant::now());
244}
245
246pub(crate) fn grant(
251 state: &AppState,
252 pane: &str,
253 agent: &str,
254 origins: Vec<String>,
255 powers: Vec<Power>,
256 minutes: u64,
257 how: How,
258) -> Grant {
259 grant_watched(state, pane, agent, origins, powers, minutes, how, IDLE_LIMIT)
260}
261
262pub(crate) fn grant_standing(
269 state: &AppState,
270 pane: &str,
271 agent: &str,
272 origins: Vec<String>,
273 powers: Vec<Power>,
274 row_id: &str,
275) -> Grant {
276 grant_made(state, pane, agent, origins, powers, Some(row_id.to_string()), 0, How::Allowed, IDLE_LIMIT)
277}
278
279fn grant_watched(
280 state: &AppState,
281 pane: &str,
282 agent: &str,
283 origins: Vec<String>,
284 powers: Vec<Power>,
285 minutes: u64,
286 how: How,
287 idle: Duration,
288) -> Grant {
289 grant_made(state, pane, agent, origins, powers, None, clamp_minutes(Some(minutes)), how, idle)
290}
291
292const NO_LIMIT: Duration = Duration::from_secs(10 * 365 * 24 * 3600);
295
296fn grant_made(
297 state: &AppState,
298 pane: &str,
299 agent: &str,
300 origins: Vec<String>,
301 powers: Vec<Power>,
302 standing: Option<String>,
303 minutes: u64,
304 how: How,
305 idle: Duration,
306) -> Grant {
307 let dur = if standing.is_some() { NO_LIMIT } else { Duration::from_secs(minutes * 60) };
308 let now = Instant::now();
309 let g = Grant {
310 id: uuid::Uuid::new_v4().to_string(),
311 agent: agent.to_string(),
312 origins,
313 powers,
314 minutes,
315 expires: now + dur,
316 expires_at_ms: chrono::Utc::now().timestamp_millis() + dur.as_millis() as i64,
317 last_active: now,
318 paused_at: crate::server::browser_actions::is_paused(pane).then_some(now),
320 standing,
321 };
322 {
323 let mut t = table();
324 t.declined.remove(pane);
325 t.grants.insert(pane.to_string(), Live { grant: g.clone(), state: Some(state.clone()) });
326 }
327 tracing::info!(
328 pane = %pane, agent = %agent, origins = ?g.origins, minutes,
329 "[browser-bypass] granted: the agent acts without asking"
330 );
331 publish(state, pane, strip_value(&g));
332 let how_long = if g.standing.is_some() { "always".to_string() } else { format!("{minutes} min") };
333 let detail = format!("{how_long} on {} ({})", g.origins.join(", "), browser_powers::names(&g.powers).join(", "));
334 crate::server::browser_actions::note(pane, agent, Kind::AutoApproveOn).detail(&detail).how(how).record(state);
335 tokio::spawn(watch(state.clone(), pane.to_string(), g.id.clone(), idle));
336 g
337}
338
339pub(crate) fn hold_clock(state: &AppState, pane: &str, hold: bool) {
343 let g = {
344 let mut t = table();
345 let Some(l) = t.grants.get_mut(pane) else { return };
346 if !l.grant.hold(hold, Instant::now()) {
347 return;
348 }
349 l.grant.clone()
350 };
351 publish(state, pane, strip_value(&g));
352}
353
354pub(crate) fn hold_all(state: &AppState) {
357 let panes: Vec<String> = table().grants.keys().cloned().collect();
358 for pane in panes {
359 hold_clock(state, &pane, crate::server::browser_actions::is_paused(&pane));
360 }
361}
362
363pub(crate) fn touch(target: &str, agent: &str) {
368 let pane = crate::server::ui_handlers::banner_for(target).0;
369 if let Some(l) = table().grants.get_mut(&pane).filter(|l| l.grant.agent.eq_ignore_ascii_case(agent)) {
370 l.grant.last_active = Instant::now();
371 }
372}
373
374#[derive(Debug, PartialEq)]
376enum Due {
377 Gone,
379 End(&'static str),
380 At(Instant),
382}
383
384fn due(pane: &str, id: &str, idle: Duration, now: Instant, busy: bool) -> Due {
388 let mut t = table();
389 let Some(g) = t.grants.get_mut(pane).map(|l| &mut l.grant).filter(|g| g.id == id) else {
390 return Due::Gone;
391 };
392 if let Some(at) = g.paused_at {
393 let left = g.left(now).min((g.last_active + idle).saturating_duration_since(at));
396 return Due::At(now + left.max(Duration::from_secs(1)));
397 }
398 if now >= g.expires {
399 return Due::End(TIME_UP_REASON);
400 }
401 if busy {
402 g.last_active = now;
403 }
404 let idle_at = g.last_active + idle;
405 if now >= idle_at {
406 return Due::End(IDLE_REASON);
407 }
408 Due::At(idle_at.min(g.expires))
409}
410
411async fn watch(state: AppState, pane: String, id: String, idle: Duration) {
415 loop {
416 let busy = crate::server::browser_attention::waiting_on_user(&pane).is_some();
417 match due(&pane, &id, idle, Instant::now(), busy) {
418 Due::Gone => return,
419 Due::End(reason) => {
420 end_if(&state, &pane, Some(&id), reason, true, How::TimedOut);
421 return;
422 }
423 Due::At(at) => tokio::time::sleep_until(tokio::time::Instant::from_std(at)).await,
424 }
425 }
426}
427
428pub(crate) fn end(state: &AppState, pane: &str, reason: &str, say_why: bool, how: How) -> bool {
433 end_if(state, pane, None, reason, say_why, how)
434}
435
436pub(crate) fn end_standing(state: &AppState, row_id: &str, reason: &str) -> usize {
440 let panes: Vec<String> = table()
441 .grants
442 .iter()
443 .filter(|(_, l)| l.grant.standing.as_deref() == Some(row_id))
444 .map(|(p, _)| p.clone())
445 .collect();
446 panes.iter().filter(|p| end(state, p, reason, true, How::ByUser)).count()
447}
448
449pub(crate) fn forget(pane: &str, reason: &str) {
453 let Some(live) = table().grants.remove(pane) else { return };
454 tracing::info!(pane = %pane, reason = %reason, "[browser-bypass] ended");
455 if let Some(state) = live.state {
456 publish(&state, pane, Value::Null);
457 }
458}
459
460fn end_if(state: &AppState, pane: &str, id: Option<&str>, reason: &str, say_why: bool, how: How) -> bool {
461 let removed = {
462 let mut t = table();
463 match t.grants.get(pane) {
464 Some(l) if id.is_none_or(|id| l.grant.id == id) => t.grants.remove(pane).map(|l| l.grant),
465 _ => None,
466 }
467 };
468 let Some(g) = removed else { return false };
469 tracing::info!(pane = %pane, reason = %reason, "[browser-bypass] ended");
470 publish(state, pane, if say_why { json!({ "agent": g.agent, "ended": reason }) } else { Value::Null });
473 crate::server::browser_actions::note(pane, &g.agent, Kind::AutoApproveOff).detail(reason).how(how).record(state);
474 true
475}
476
477fn strip_value(g: &Grant) -> Value {
479 let mut v = json!({
480 "agent": g.agent, "origins": g.origins, "powers": browser_powers::names(&g.powers),
481 "minutes": g.minutes, "expires_at": g.expires_at_ms,
482 });
483 if g.standing.is_some() {
484 v["always"] = json!(true);
485 }
486 if g.paused_at.is_some() {
488 v["paused_left"] = json!(g.left(Instant::now()).as_millis() as u64);
489 }
490 v
491}
492
493fn publish(state: &AppState, pane: &str, value: Value) {
495 let mut meta = crate::backend::obj::MetaMapType::new();
496 meta.insert(BYPASS_META_KEY.to_string(), value);
497 if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, pane, &meta) {
498 tracing::debug!(pane = %pane, error = %e, "[browser-bypass] header strip not updated");
499 }
500}
501
502pub(crate) fn reset_strips(state: &AppState) {
506 let live: Vec<String> = table().grants.keys().cloned().collect();
507 let blocks = match state.mstore.get_all::<crate::backend::obj::Block>() {
508 Ok(b) => b,
509 Err(e) => {
510 tracing::warn!(error = %e, "[browser-bypass] couldn't list panes to clear stale bypass strips");
511 return;
512 }
513 };
514 for b in blocks
515 .into_iter()
516 .filter(|b| !live.contains(&b.oid) && b.meta.get(BYPASS_META_KEY).is_some_and(|v| !v.is_null()))
517 {
518 publish(state, &b.oid, Value::Null);
519 }
520}
521
522pub(crate) fn is_payment(what: &str) -> bool {
527 let w = what.to_ascii_lowercase();
528 let words: Vec<&str> = w.split(|c: char| !c.is_ascii_alphanumeric()).filter(|s| !s.is_empty()).collect();
529 const STEMS: [&str; 11] =
532 ["pay", "purchas", "checkout", "transfer", "donat", "subscri", "withdraw", "remit", "deposit", "refund", "billing"];
533 const NOT: [&str; 2] = ["payload", "payloads"];
535 const WHOLE: [&str; 8] = ["buy", "buys", "order", "orders", "paid", "wire", "bid", "tip"];
536 const PAIRS: [[&str; 2]; 6] =
537 [["check", "out"], ["place", "order"], ["send", "money"], ["send", "funds"], ["add", "funds"], ["add", "money"]];
538 words.iter().any(|x| !NOT.contains(x) && (STEMS.iter().any(|s| x.starts_with(s)) || WHOLE.contains(x)))
539 || words.windows(2).any(|p| PAIRS.iter().any(|q| p == q))
540}
541
542const COMMANDS: [&str; 6] = ["pay", "buy", "confirm", "complete", "place", "make"];
544
545const BRANDS: [&str; 14] = [
549 "apple pay", "google pay", "samsung pay", "amazon pay", "kakao pay", "naver pay", "toss pay", "cash app pay",
550 "shop pay", "meta pay", "microsoft pay", "venmo pay", "link pay", "alipay",
551];
552
553pub(crate) fn is_brand_pay(name: &str) -> bool {
555 let name = name.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_lowercase();
556 BRANDS.contains(&name.trim_end_matches(['.', '!']))
557}
558
559fn without_plans(name: &str) -> String {
563 let lower = name.to_ascii_lowercase();
564 let (bytes, mut out, mut i) = (lower.as_bytes(), String::new(), 0);
565 let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
566 while i < name.len() {
567 let at_word_start = i == 0 || !word(bytes[i - 1]);
568 if at_word_start && (lower[i..].starts_with("pay-as-") || lower[i..].starts_with("pay-per-")) {
569 let skip = lower[i..].bytes().take_while(|&b| word(b) || b == b'-').count();
570 out.push(' ');
571 i += skip;
572 } else {
573 let ch = name[i..].chars().next().unwrap_or(' ');
574 out.push(ch);
575 i += ch.len_utf8();
576 }
577 }
578 out
579}
580
581fn quoted(what: &str) -> &str {
583 match (what.find('"'), what.rfind('"')) {
584 (Some(a), Some(b)) if b > a => &what[a + 1..b],
585 _ => what,
586 }
587}
588
589pub(crate) fn click_is_payment(what: &str, description: &str, submits: bool) -> bool {
594 if submits {
596 return is_payment(what) || is_payment(description);
597 }
598 let name = without_plans(quoted(what)).split_whitespace().collect::<Vec<_>>().join(" ");
601 if name.is_empty() || is_brand_pay(&name) {
602 let first = description.split(|c: char| !c.is_ascii_alphanumeric()).find(|w| !w.is_empty()).unwrap_or("");
603 return (COMMANDS.contains(&first.to_ascii_lowercase().as_str()) && is_payment(description))
604 || outside_of(what).as_deref().is_some_and(is_payment);
605 }
606 is_payment(&name) || is_payment(description) || outside_of(what).as_deref().is_some_and(is_payment)
608}
609
610fn outside_of(what: &str) -> Option<String> {
612 let (a, b) = (what.find('"')?, what.rfind('"')?);
613 (b > a).then(|| format!("{} {}", &what[..a], &what[b + 1..]))
614}
615
616pub(crate) fn origins_for(pane: &str, url: &str) -> Result<Vec<String>, String> {
619 let origin = agentmux_common::allowed_origins::target_origin(url)
620 .ok_or_else(|| "the pane isn't showing a web page; open the site first".to_string())?;
621 let mut out = vec![origin];
622 for o in crate::server::browser_allowlist::list_for(pane).unwrap_or_default() {
623 if !out.contains(&o) {
624 out.push(o);
625 }
626 }
627 Ok(out)
628}
629
630#[cfg(test)]
633pub(crate) fn tests_put(pane: &str, agent: &str) {
634 tests::put(pane, agent, &["https://github.com"], 60);
635}
636
637#[cfg(test)]
640pub(crate) fn tests_grant_idle(state: &AppState, pane: &str, agent: &str, idle: Duration) -> Grant {
641 grant_watched(state, pane, agent, vec!["https://github.com".to_string()], vec![Power::Clicks], 15, How::ByUser, idle)
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 pub(super) fn put(pane: &str, agent: &str, origins: &[&str], secs: u64) {
649 let grant = Grant {
650 id: format!("{pane}-id"),
651 agent: agent.to_string(),
652 origins: origins.iter().map(|s| s.to_string()).collect(),
653 powers: vec![Power::Clicks],
654 minutes: 1,
655 expires: Instant::now() + Duration::from_secs(secs),
656 expires_at_ms: 0,
657 last_active: Instant::now(),
658 paused_at: None,
659 standing: None,
660 };
661 table().grants.insert(pane.to_string(), Live { grant, state: None });
662 }
663
664 #[test]
665 fn a_pause_stops_both_clocks_and_resume_restarts_them() {
666 let idle = IDLE_LIMIT;
667 let t0 = Instant::now();
668 put("bp-held", "naki", &["https://github.com"], 60);
670 {
671 let mut t = table();
672 let g = &mut t.grants.get_mut("bp-held").unwrap().grant;
673 g.last_active = t0;
674 g.paused_at = Some(t0);
675 g.expires = t0 + Duration::from_secs(30 * 60);
676 }
677 let later = t0 + idle + Duration::from_secs(120);
679 assert!(matches!(due("bp-held", "bp-held-id", idle, later, false), Due::At(_)), "paused, so not due");
680 assert!(active_for("bp-held", "naki").is_some(), "a paused grant stays");
681 assert!(table().grants.get_mut("bp-held").unwrap().grant.hold(false, later));
684 let g = active_for("bp-held", "naki").unwrap();
685 assert_eq!(g.paused_at, None);
686 assert_eq!(g.expires, later + Duration::from_secs(30 * 60));
687 assert_eq!(due("bp-held", "bp-held-id", idle, later, false), Due::At(later + idle));
688 assert!(matches!(due("bp-held", "bp-held-id", idle, later + idle - Duration::from_secs(1), false), Due::At(_)));
689 assert_eq!(due("bp-held", "bp-held-id", idle, later + idle, false), Due::End(IDLE_REASON));
690 forget("bp-held", "test");
691 }
692
693 #[test]
694 fn a_paused_grant_does_not_run_out() {
695 put("bp-held-time", "naki", &["https://github.com"], 0);
696 let now = Instant::now();
697 table().grants.get_mut("bp-held-time").unwrap().grant.paused_at = Some(now);
698 assert!(active_for("bp-held-time", "naki").is_some(), "a paused grant stays, though its time is past");
699 let Due::At(at) = due("bp-held-time", "bp-held-time-id", IDLE_LIMIT, now, false) else { panic!("not ended") };
700 assert_eq!(at, now + Duration::from_secs(1), "the watcher looks again rather than ending it");
701 table().grants.get_mut("bp-held-time").unwrap().grant.paused_at = None;
702 assert!(active_for("bp-held-time", "naki").is_none());
703 }
704
705 fn quiet_for(pane: &str, d: Duration) {
706 table().grants.get_mut(pane).unwrap().grant.last_active = Instant::now() - d;
707 }
708
709 #[test]
710 fn a_grant_ends_after_its_agent_goes_quiet() {
711 let idle = Duration::from_secs(15 * 60);
712 put("bp-idle", "naki", &["https://github.com"], 3600);
713 let id = "bp-idle-id";
714 let Due::At(at) = due("bp-idle", id, idle, Instant::now(), false) else { panic!("not due yet") };
716 assert!(at > Instant::now() + Duration::from_secs(14 * 60));
717 quiet_for("bp-idle", idle + Duration::from_secs(1));
718 assert_eq!(due("bp-idle", id, idle, Instant::now(), false), Due::End(IDLE_REASON));
719 assert_eq!(due("bp-idle", "an-older-grant", idle, Instant::now(), false), Due::Gone);
721 assert_eq!(due("bp-none", id, idle, Instant::now(), false), Due::Gone);
722 forget("bp-idle", "test");
723 }
724
725 #[test]
726 fn a_browser_call_from_its_agent_keeps_a_grant_alive() {
727 let idle = Duration::from_secs(15 * 60);
728 put("bp-touch", "naki", &["https://github.com"], 3600);
729 quiet_for("bp-touch", idle + Duration::from_secs(1));
730 touch("bp-touch", "korp");
732 assert_eq!(due("bp-touch", "bp-touch-id", idle, Instant::now(), false), Due::End(IDLE_REASON));
733 touch("bp-touch", "Naki");
734 assert!(matches!(due("bp-touch", "bp-touch-id", idle, Instant::now(), false), Due::At(_)));
735 forget("bp-touch", "test");
736 }
737
738 #[test]
739 fn waiting_on_the_person_is_not_going_quiet() {
740 let idle = Duration::from_secs(15 * 60);
741 put("bp-busy", "naki", &["https://github.com"], 3600);
742 quiet_for("bp-busy", idle + Duration::from_secs(60));
743 assert!(matches!(due("bp-busy", "bp-busy-id", idle, Instant::now(), true), Due::At(_)));
745 assert!(matches!(due("bp-busy", "bp-busy-id", idle, Instant::now(), false), Due::At(_)));
747 forget("bp-busy", "test");
748 }
749
750 #[test]
751 fn the_time_limit_ends_a_grant_however_busy() {
752 put("bp-time", "naki", &["https://github.com"], 0);
753 assert_eq!(due("bp-time", "bp-time-id", Duration::from_secs(900), Instant::now(), true), Due::End(TIME_UP_REASON));
754 forget("bp-time", "test");
755 }
756
757 #[test]
758 fn asking_about_each_line_is_the_stricter_terminal_and_a_free_one_covers_a_request_for_it() {
759 put("bp-ask", "naki", &["https://github.com"], 60);
760 let power = |p: Power| table().grants.get_mut("bp-ask").unwrap().grant.powers.push(p);
761 let g = || active_for("bp-ask", "naki").unwrap();
762 assert!(!g().allows_terminal() && !g().asks_each_line());
763 power(Power::Terminal);
764 assert!(g().allows_terminal() && !g().asks_each_line(), "a free terminal runs without asking");
765 assert!(g().satisfies(Power::TerminalAsk), "a request to use it with questions needs nothing more");
766 power(Power::TerminalAsk);
767 assert!(g().asks_each_line(), "both: the stricter wins");
768 table().grants.get_mut("bp-ask").unwrap().grant.powers.retain(|p| *p != Power::Terminal);
769 assert!(g().allows_terminal() && g().asks_each_line());
770 assert!(!g().satisfies(Power::Terminal), "asking each line does not give the free terminal");
771 forget("bp-ask", "test");
772 }
773
774 #[test]
775 fn a_grant_allows_only_the_powers_it_names() {
776 put("bp-powers", "naki", &["https://github.com"], 60);
777 let g = active_for("bp-powers", "naki").unwrap();
778 assert!(g.allows(Power::Clicks));
779 assert!(!g.allows(Power::Terminal), "a grant made for clicks does not carry the terminal");
780 table().grants.get_mut("bp-powers").unwrap().grant.powers.push(Power::Terminal);
781 assert!(active_for("bp-powers", "naki").unwrap().allows(Power::Terminal));
782 forget("bp-powers", "test");
783 }
784
785 #[test]
786 fn enter_and_space_need_their_own_power_and_a_covered_page() {
787 put("bp-keys", "naki", &["https://github.com"], 60);
788 let g = active_for("bp-keys", "naki").unwrap();
789 assert!(!g.allows(Power::EnterSpace), "clicks alone don't press keys");
790 table().grants.get_mut("bp-keys").unwrap().grant.powers.push(Power::EnterSpace);
791 let g = active_for("bp-keys", "naki").unwrap();
792 assert!(g.allows(Power::EnterSpace) && g.satisfies(Power::EnterSpace));
793 assert!(!g.allows_terminal(), "the keys are not the terminal");
794 assert!(g.covers("https://github.com/x") && !g.covers("https://evil.example/"));
795 forget("bp-keys", "test");
796 }
797
798 #[test]
799 fn a_held_file_chooser_needs_the_uploads_power_and_a_covered_page() {
800 put("bp-up", "naki", &["https://github.com"], 60);
801 assert!(!active_for("bp-up", "naki").unwrap().allows(Power::Uploads), "clicks alone don't fill a chooser");
802 table().grants.get_mut("bp-up").unwrap().grant.powers.push(Power::Uploads);
803 let g = active_for("bp-up", "naki").unwrap();
804 assert!(g.allows(Power::Uploads) && !g.allows(Power::EnterSpace));
805 assert!(g.covers("https://github.com/upload") && !g.covers("https://evil.example/"));
806 forget("bp-up", "test");
807 }
808
809 #[test]
810 fn a_grant_is_for_its_agent_only() {
811 put("bp-agent", "naki", &["https://github.com"], 60);
812 assert!(active_for("bp-agent", "Naki").is_some());
813 assert!(active_for("bp-agent", "korp").is_none());
814 forget("bp-agent", "test");
815 assert!(active_for("bp-agent", "naki").is_none());
816 }
817
818 #[test]
819 fn an_expired_grant_is_gone_without_its_timer() {
820 put("bp-expired", "naki", &["https://github.com"], 0);
821 assert!(active_for("bp-expired", "naki").is_none());
822 assert!(!table().grants.contains_key("bp-expired"), "dropped when found expired");
823 }
824
825 #[test]
826 fn a_grant_covers_only_its_sites() {
827 put("bp-sites", "naki", &["https://github.com", "https://*.example.com"], 60);
828 let g = active_for("bp-sites", "naki").unwrap();
829 assert!(g.covers("https://github.com/example/repo/issues/1"));
830 assert!(g.covers("https://docs.example.com/x"));
831 assert!(!g.covers("https://accounts.google.com/o/oauth2"));
832 assert!(!g.covers("http://github.com/"), "another scheme is another site");
833 assert!(!g.covers("about:blank"), "a page with no origin is never covered");
834 assert!(!g.covers("data:text/html,hi"));
835 forget("bp-sites", "test");
836 }
837
838 #[test]
839 fn durations_round_down_to_a_choice_and_cap() {
840 assert_eq!(clamp_minutes(None), 60);
841 assert_eq!(clamp_minutes(Some(15)), 15);
842 assert_eq!(clamp_minutes(Some(30)), 15);
843 assert_eq!(clamp_minutes(Some(60)), 60);
844 assert_eq!(clamp_minutes(Some(90)), 60);
845 assert_eq!(clamp_minutes(Some(10_000)), 240);
846 assert_eq!(clamp_minutes(Some(1)), 15);
847 }
848
849 fn bare_grant(minutes: u64, standing: Option<String>) -> Grant {
850 let now = Instant::now();
851 let dur = if standing.is_some() { NO_LIMIT } else { Duration::from_secs(minutes * 60) };
852 Grant {
853 id: "g".into(),
854 agent: "a".into(),
855 origins: vec![],
856 powers: vec![Power::Clicks],
857 minutes,
858 expires: now + dur,
859 expires_at_ms: 0,
860 last_active: now,
861 paused_at: None,
862 standing,
863 }
864 }
865
866 #[test]
867 fn an_ask_for_less_cuts_a_longer_grant_and_an_ask_for_more_does_not_stretch_it() {
868 let now = Instant::now();
869 let mut g = bare_grant(60, None);
870 assert_eq!(g.shorten(15, now), Some(60), "a 60 minute grant asked for 15 is cut to 15");
871 assert_eq!(g.minutes, 15);
872 assert!((14..=15).contains(&g.minutes_left()), "{}", g.minutes_left());
873 assert_eq!(g.shorten(60, now), None, "asking for more never stretches it");
874 assert_eq!(g.shorten(15, now), None, "nor does asking for what is left");
875 let mut always = bare_grant(0, Some("row".into()));
876 assert_eq!(always.shorten(15, now), None, "a standing grant has no clock to cut");
877 let mut paused = bare_grant(60, None);
878 let ten_minutes_ago = now.checked_sub(Duration::from_secs(600)).unwrap_or(now);
879 paused.paused_at = Some(ten_minutes_ago);
880 paused.expires = ten_minutes_ago + Duration::from_secs(3600);
882 assert_eq!(paused.shorten(15, now), Some(60));
883 assert!((14..=15).contains(&paused.minutes_left()));
884 let end_in_ms = paused.expires_at_ms - chrono::Utc::now().timestamp_millis();
886 let expected = 15 * 60_000 - now.saturating_duration_since(ten_minutes_ago).as_millis() as i64;
887 assert!((end_in_ms - expected).abs() < 5_000, "{end_in_ms} vs {expected}");
888 }
889
890 #[test]
891 fn payments_are_recognised() {
892 for what in [
893 "Click \"Pay now\"",
894 "Click \"Buy\"",
895 "Click \"Place order\"",
896 "Click \"Check out\"",
897 "Click \"Checkout\"",
898 "Click \"Transfer funds\"",
899 "Click \"Confirm payment\"",
900 "Click \"Make a payment\"",
901 "Click \"Submit payment\"",
902 "Click \"Send money\"",
903 "Click \"Withdraw\"",
904 "Click \"Wire funds\"",
905 "Click \"Purchase subscription\"",
906 "Click \"Donate\"",
907 ] {
908 assert!(is_payment(what), "{what}");
909 }
910 for what in [
911 "Click \"Delete draft\"",
912 "Click \"Submit\"",
913 "Click \"Send\"",
914 "Click \"Send message\"",
915 "Click \"Reorder list\"",
916 "Click \"Payload settings\"",
917 "Click \"Delete revision\"",
918 "Click \"Confirm\"",
919 ] {
920 assert!(!is_payment(what), "{what}");
921 }
922 }
923
924 #[test]
925 fn a_brand_with_pay_in_its_name_is_not_a_payment_but_a_command_is() {
926 for what in [
927 "Click \"Kakao Pay\"",
928 "Click \"Cash App Pay\"",
929 "Click \"Apple Pay\"",
930 "Click \"Google Pay\"",
931 "Click \"Pay-as-you-go\"",
932 ] {
933 assert!(!click_is_payment(what, "", false), "{what}");
934 assert!(!click_is_payment(what, "Accept payments from customers in Korea", false), "{what} with a description");
935 assert!(click_is_payment(what, "", true), "{what} as a submit control");
936 }
937 for (what, description) in [
938 ("Click \"Pay\"", ""),
939 ("Click \"Pay now\"", ""),
940 ("Click \"Pay $5.46\"", ""),
941 ("Click \"Place order\"", ""),
942 ("Click \"Confirm and Pay\"", ""),
943 ("Click \"Click to Pay\"", ""),
944 ("Click \"Pay with Apple Pay\"", ""),
945 ("Click \"Kakao Pay\" (in a frame from https://pay.example.com)", ""),
946 ("Click \"Confirm\" (in a frame from https://checkout.example.com)", ""),
947 ("Click \"Unsubscribe Apple Pay\"", ""),
948 ("Click \"Post Kakao Pay\"", ""),
949 ("Click \"Publish Kakao Pay\"", ""),
950 ("Click \"Kakao Pay $20\"", ""),
951 ("Click \"Quick Pay\"", ""),
952 ("Click \"Approve Kakao Pay\"", ""),
953 ("Click \"Charge Apple Pay\"", ""),
954 ("Click \"Bill Pay\"", ""),
955 ("Click \"Pay-as-you-go:Pay now\"", ""),
956 ("Click \"Pay-as-you-go: Pay now\"", ""),
957 ("Click \"Pay-per-use - Pay $20\"", ""),
958 ("Click \"Pay-as-you-go\"", "Pay now"),
959 ("Click \"Confirm And Pay\"", ""),
960 ("Click \"Proceed To Pay\"", ""),
961 ("Click \"CLICK TO PAY\"", ""),
962 ("Click \"Confirm Apple Pay\"", ""),
963 ("Click \"Place Order And Pay\"", ""),
964 ("Click \"Apple Pay\"", "Pay $20.00 now"),
965 ("Click \"Continue\"", "Pay now"),
966 ] {
967 assert!(click_is_payment(what, description, false), "{what} / {description}");
968 }
969 }
970
971 #[test]
972 fn a_payment_under_a_grant_says_so_in_its_banner() {
973 use crate::server::browser_bypass_routes::payment_exception;
974 put("bp-pay-note", "korp", &["https://github.com"], 60);
975 let ask = |what: &str| json!({ "what": what, "page": "https://github.com/a/b", "why": "its name says \"Pay\"" });
976 let note = Some("auto-approve is on for this site, but a payment always asks");
977 assert_eq!(payment_exception("bp-pay-note", "korp", &ask("Click \"Pay now\"")), note);
978 assert_eq!(payment_exception("bp-pay-note", "korp", &ask("Click \"Kakao Pay\"")), None);
979 let submit = json!({ "what": "Click \"Apple Pay\"", "page": "https://github.com/a/b", "action": "https://github.com/pay", "why": "it submits a form" });
980 assert_eq!(payment_exception("bp-pay-note", "korp", &submit), note, "a checkout's submit control named Apple Pay pays");
981 assert_eq!(payment_exception("bp-pay-note", "other", &ask("Click \"Pay now\"")), None, "another agent holds no grant");
982 assert_eq!(payment_exception("bp-no-grant", "korp", &ask("Click \"Pay now\"")), None);
983 let elsewhere = json!({ "what": "Click \"Pay now\"", "page": "https://example.org/x" });
984 assert_eq!(payment_exception("bp-pay-note", "korp", &elsewhere), None, "off the granted sites auto-approve says nothing");
985 }
986
987 #[test]
988 fn a_no_cools_down() {
989 assert!(cooling_down("bp-cool").is_none());
990 note_declined("bp-cool");
991 assert!(cooling_down("bp-cool").is_some());
992 table().declined.insert("bp-cool".into(), Instant::now() - REQUEST_COOLDOWN - Duration::from_secs(1));
993 assert!(cooling_down("bp-cool").is_none());
994 }
995}