Skip to main content

agentmux_srv/server/
browser_bypass.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bypass: the person lets the agent driving a browser pane act without
5//! asking first, on the site(s) the pane is on, for a time they choose
6//! (docs/specs/SPEC_BROWSER_PANE_BYPASS_2026_10_16.md).
7//!
8//! A grant lives only here, in memory: srv restarting ends every grant, and
9//! the pane's `browser:bypass` meta key (srv-only, like `browser:attention`)
10//! only mirrors it for the header strip. Only the person grants one: through
11//! the host (`/api/v1/host/browser_bypass`, the Bypass button) or by answering
12//! an agent's `request_bypass` banner, which also arrives only through the
13//! host. An agent may end its own grant, never start one.
14//!
15//! A grant is for one pane (and the popup windows its page opens; a popup
16//! pane has its own header and its own grant), one agent (the owner
17//! when it was granted), the sites the person was shown, and a time limit.
18//! Take over, closing the pane, a change of owner and the time limit end it,
19//! and so do [`IDLE_LIMIT`] minutes without a `Browser` call from its agent
20//! on the pane: a hung or stopped agent doesn't keep one alive. While the
21//! person has paused the pane (`browser_actions`), both clocks stand still:
22//! the agent can't call then, so it isn't going quiet.
23
24use 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
34/// Block meta key the browser pane's header reads.
35pub(crate) const BYPASS_META_KEY: &str = "browser:bypass";
36
37/// The durations the person can pick, in minutes. 60 is the default.
38pub(crate) const CHOICES_MINUTES: [u64; 3] = [15, 60, 240];
39pub(crate) const DEFAULT_MINUTES: u64 = 60;
40
41/// After the person says No to an agent's request, the agent may not ask
42/// again on that pane for this long.
43pub(crate) const REQUEST_COOLDOWN: Duration = Duration::from_secs(10 * 60);
44
45/// A grant ends after this long without a `Browser` call from its agent on
46/// the pane ([`touch`]), with [`IDLE_REASON`]. Time the pane spends waiting
47/// on the person (a hand-off, a question) doesn't count: the agent is waiting
48/// for them then, not stuck.
49pub(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    /// Distinguishes this grant from a later one on the same pane, so an old
56    /// expiry timer can't end a new grant.
57    pub id: String,
58    pub agent: String,
59    /// The bound sites, in `allowed_origins` normal form.
60    pub origins: Vec<String>,
61    /// What the person allowed: committing clicks always, and any more they were shown.
62    pub powers: Vec<Power>,
63    pub minutes: u64,
64    pub expires: Instant,
65    /// For the header's countdown: milliseconds since the Unix epoch.
66    pub expires_at_ms: i64,
67    /// The agent's last `Browser` call on the pane, or the grant itself.
68    last_active: Instant,
69    /// Since when the person has paused the pane: the time limit and the
70    /// idle limit stand still until they resume, then both move later by
71    /// the paused time.
72    pub paused_at: Option<Instant>,
73    /// The standing row this grant was made from (`browser_standing`), for a
74    /// grant that has no time limit: revoking the row ends it.
75    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    /// Time left on the clock, which stands still while the pane is paused.
84    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    /// Stop (`hold`) or restart the grant's clocks at `now`. Resuming moves
93    /// its end and its idle deadline later by the paused time. Returns
94    /// whether anything changed.
95    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    /// Cut the time left to `minutes` when it is longer: a grant lasts what an agent asked for, or less. A
110    /// grant with no time limit (a standing row) is never cut. Returns the minutes it had left, when cut.
111    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        // The clock stands at the pause; resuming moves the end later by the time paused so far.
119        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    /// Does this grant already give what a request for `power` asks? A grant
130    /// that lets the terminal run freely covers a request to use it with a
131    /// question per line (the laxer one holds the stricter).
132    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    /// May the agent type in a web terminal at all, whether or not each line asks?
140    pub(crate) fn allows_terminal(&self) -> bool {
141        self.allows(Power::Terminal) || self.allows(Power::TerminalAsk)
142    }
143
144    /// Does each line need the person's Run it? The stricter power wins when a
145    /// grant carries both.
146    pub(crate) fn asks_each_line(&self) -> bool {
147        self.allows(Power::TerminalAsk)
148    }
149
150    /// Is `url` on the sites this grant is bound to? A page with no web
151    /// origin (`about:blank`, `data:`) never is.
152    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
158/// A grant, and the srv state it was made with: [`forget`]'s callers have
159/// none of their own, and it still takes the header strip down through it.
160struct 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
176/// Round `asked` to one of [`CHOICES_MINUTES`]: the nearest one not longer
177/// than asked, and never past the longest. None gives the default.
178pub(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
188/// An agent asked for `minutes` while `pane` already holds its live grant: cut the grant to that when it has
189/// longer left, so it lasts what was asked or less. Returns the grant as it is now and the minutes it had
190/// left, when it was cut.
191pub(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    // The watcher sleeps until the old end: a new one wakes at the new end (the old one finds the grant gone).
205    tokio::spawn(watch(state.clone(), pane.to_string(), g.id.clone(), IDLE_LIMIT));
206    Some((g, was))
207}
208
209/// The live grant on `pane` for `agent`, if any. An expired one is dropped
210/// here, without waiting for its timer.
211pub(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
221/// Does `pane` hold a live grant, whoever's?
222pub(crate) fn active_for_any(pane: &str) -> bool {
223    table().grants.get(pane).is_some_and(|l| l.grant.live())
224}
225
226/// Is the live grant on `pane` one made from a standing row?
227pub(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
231/// Did the person decline a request on `pane` too recently for another?
232pub(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
246/// Record a grant on `pane` for `agent` over `origins`, show it in the
247/// pane's header, log it (`how`: the person's header button, or their answer
248/// to the agent's request), and end it when its time is up or its agent goes
249/// quiet. Replaces any grant the pane had.
250pub(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
262/// A grant with no time limit, made from the person's standing row `row_id`
263/// when `agent` works on a pane showing a site the row names. It ends like
264/// any other (Stop, Take over, the pane closing, going idle), and when the row
265/// is revoked or changed. After going idle or a changed row the next call makes
266/// it again; after the person's Stop it doesn't, until they turn it on again
267/// (`browser_standing::stop_by_person`).
268pub(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
292/// Stands in for "no limit" on a standing grant's clock: far enough that no
293/// pane outlives it, so the time-limit code needs no second case.
294const 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        // Granted on a paused pane: its clocks start on resume.
319        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
339/// Stop (`hold`) or restart `pane`'s grant clocks: the person paused or
340/// resumed the pane. The watcher needs no word: it finds the new deadlines
341/// when it next wakes, which is never later than they are.
342pub(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
354/// "Pause all agent browsing" was turned on or off: hold every grant's clock
355/// whose pane is paused now, and restart the rest.
356pub(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
363/// A `Browser` call from `agent` on `target` (a pane, or a popup window,
364/// whose grant is its opener's): it keeps that agent's grant there alive.
365/// Every agent browser call resolves its pane through
366/// `ui_handlers::target_block_id`, which calls this.
367pub(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/// What the watcher of grant `id` on `pane` does next.
375#[derive(Debug, PartialEq)]
376enum Due {
377    /// The grant has ended or been replaced: stop watching.
378    Gone,
379    End(&'static str),
380    /// Nothing yet: look again then.
381    At(Instant),
382}
383
384/// Grant `id` on `pane` at `now`: past its time, or `idle` since its agent's
385/// last `Browser` call there. `busy`: the pane waits on the person, which
386/// counts as activity. A paused grant is never due.
387fn 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        // Resuming moves both deadlines by the paused time, so neither can
394        // come sooner than this much after now: look again then.
395        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
411/// One task per grant ends it on time or when its agent goes quiet. A
412/// [`touch`] only moves the deadline: the task wakes at the old one, finds
413/// the grant still in use, and sleeps until the new one.
414async 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
428/// End `pane`'s grant, if it has one, and take the header strip down; with
429/// `say_why`, the strip says why it ended instead (the person who ended it
430/// themselves needs no note). Returns whether there was one. `how` is for
431/// the action log: the agent's own stop is `Allowed`, the person's `ByUser`.
432pub(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
436/// End every live grant made from standing row `row_id` (the row was revoked
437/// or changed): each pane's strip comes down, and the agent's next call makes
438/// a new grant from what the row says now, if it still says anything.
439pub(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
449/// End `pane`'s grant for callers that have no [`AppState`]: Take over,
450/// closing the pane, a new owner. The strip is cleared through the state the
451/// grant was made with, so it can't go on showing a grant that has ended.
452pub(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    // The note has no `expires_at`, so the header never takes it for a
471    // grant; the next grant, or the host registering, replaces it.
472    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
477/// The header strip's copy of a live grant.
478fn 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    // Paused: the header shows the time left, which isn't running down.
487    if g.paused_at.is_some() {
488        v["paused_left"] = json!(g.left(Instant::now()).as_millis() as u64);
489    }
490    v
491}
492
493/// Write `value` as the header strip's `browser:bypass`.
494fn 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
502/// Clear every pane's strip. Called when the host registers: a grant never
503/// survives srv restarting, and the strip, saved with the pane, must not
504/// keep claiming one.
505pub(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
522/// Does the committing click `what` (the approval's "Click \"…\"") spend
523/// or move money? Those still ask under bypass (spec §11.2): the cost of a
524/// mistake is money, and bulk jobs rarely pay. Matched by word stem
525/// ("pay" covers payment, payments, paying), so it errs towards asking.
526pub(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    // A word starting with one of these: pay, payment, purchase, checkout,
530    // transfer, donation, subscription, withdrawal, remittance, deposit, refund.
531    const STEMS: [&str; 11] =
532        ["pay", "purchas", "checkout", "transfer", "donat", "subscri", "withdraw", "remit", "deposit", "refund", "billing"];
533    // Words a stem would get wrong ("payload"), or that only count whole.
534    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
542/// A description that opens with one of these tells the person to pay.
543const COMMANDS: [&str; 6] = ["pay", "buy", "confirm", "complete", "place", "make"];
544
545/// The wallets and pay apps whose name ends in "Pay". A page of payment methods lists a row, tab or link for
546/// each, and opening one pays nothing. Only these: any other name with "Pay" in it (an unknown brand, "Quick
547/// Pay", "Approve Kakao Pay") asks, as it always did. Keep in step with `BRANDS` in `click_label.js`.
548const 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
553/// Is `name`, whole, one of the [`BRANDS`]?
554pub(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
559/// `name` without its plan names ("Pay-as-you-go", "Pay-per-use"): a `pay-as-` or `pay-per-` at the start
560/// of a word and the letters, digits, `_` and `-` after it. Done as `click_label.js` does it, so both judge
561/// the same text.
562fn 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
581/// The name in a click's `what` (`Click "Kakao Pay"`): what is between the first and the last quote.
582fn 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
589/// Does the committing click `what` (with the element's `description` under its name) spend or move
590/// money? [`is_payment`] on both, except that a brand's name ("Kakao Pay") is not one: a payment-methods
591/// page lists dozens, and a click on one opens its settings. Its description still counts when it opens
592/// with a command ("Pay $20.00 now").
593pub(crate) fn click_is_payment(what: &str, description: &str, submits: bool) -> bool {
594    // A control that submits a form is judged on its name as it is: a checkout's "Apple Pay" submit pays.
595    if submits {
596        return is_payment(what) || is_payment(description);
597    }
598    // A plan's name ("Pay-as-you-go", "Pay-per-use") is taken out as the page's script takes it out, and
599    // what is left is judged: "Pay-as-you-go: Pay now" is still a command to pay.
600    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    // What `what` says outside the name (a frame from a payment site) is judged as it always was.
607    is_payment(&name) || is_payment(description) || outside_of(what).as_deref().is_some_and(is_payment)
608}
609
610/// What `what` says around the quoted name: ` (in a frame from https://pay.example.com)`.
611fn 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
616/// The sites a grant on `pane` binds to: the origin of the page it shows
617/// (`url`, as the host reports it), and its site list if it has one.
618pub(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/// A live grant on `pane` for `agent` over github.com, for other modules'
631/// tests (no `AppState` needed).
632#[cfg(test)]
633pub(crate) fn tests_put(pane: &str, agent: &str) {
634    tests::put(pane, agent, &["https://github.com"], 60);
635}
636
637/// A real grant (strip and watcher) that ends after `idle` without a
638/// `Browser` call, for other modules' tests.
639#[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        // Paused right after the agent's last call, with 30 minutes left.
669        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        // Paused for longer than the idle limit: still not due.
678        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        // Resume: the idle deadline is a whole quiet IDLE_LIMIT away again,
682        // and the end the 30 minutes it had left.
683        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        // Fresh: look again when the idle limit would be reached.
715        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        // Another grant's watcher, or one for a replaced grant, stops.
720        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        // Another agent's call doesn't count.
731        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        // A hand-off is up: the agent waits for the person, it isn't stuck.
744        assert!(matches!(due("bp-busy", "bp-busy-id", idle, Instant::now(), true), Due::At(_)));
745        // And the wait counts as activity once it's over.
746        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 ten minutes ago with sixty minutes then left: its clock stands at the pause.
881        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        // The header's end is 15 minutes after the pause, which resuming moves later by the time paused.
885        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}