Skip to main content

agentmux_srv/server/
browser_bypass_routes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The routes of Bypass (docs/specs/SPEC_BROWSER_PANE_BYPASS_2026_10_16.md):
5//! an agent's `request_bypass` and `end_bypass`, the person's Bypass button
6//! and End bypass through the host, and the check that lets a committing
7//! click through without asking. The grants themselves are `browser_bypass`.
8
9use axum::extract::State;
10use axum::http::StatusCode;
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde_json::json;
14
15use crate::server::browser_actions::{note, How, Kind, Note};
16use crate::server::browser_bypass as bypass;
17use crate::server::browser_powers::{self, Power};
18use crate::server::ui_handlers::{
19    banner_for, err_response, from_host, get_host_ipc, owning_agent, proxy_to_host_timeout, proxy_value, target_block_id,
20};
21use crate::server::AppState;
22
23/// The pane a bypass for `target` is recorded on: the pane itself, or for
24/// a popup window (which has no AgentMux header of its own) its opener. A
25/// popup pane has its own header, so it has its own grant (bypass spec §4.2).
26fn bypass_pane(target: &str) -> String {
27    banner_for(target).0
28}
29
30/// Does the committing click `ask` describes pay? The element's text after its name is judged with the
31/// name, so a payment word on any line asks (roadblocks report R7). A control that submits a form (it has an `action`, or
32/// that is why it asks) is judged on its name as it is.
33fn ask_is_payment(ask: &serde_json::Value) -> bool {
34    let text = |k: &str| ask.get(k).and_then(|v| v.as_str()).unwrap_or("");
35    let submits = !text("action").is_empty() || text("why") == "it submits a form";
36    bypass::click_is_payment(text("what"), text("description"), submits)
37}
38
39/// The click `ask` asks although auto-approve is on for its site, because it pays: the words to add to the
40/// banner's "Asked because", so that it doesn't read as auto-approve being broken (#47625).
41pub(crate) fn payment_exception(block_id: &str, agent: &str, ask: &serde_json::Value) -> Option<&'static str> {
42    let g = bypass::active_for(&bypass_pane(block_id), agent)?;
43    let text = |k: &str| ask.get(k).and_then(|v| v.as_str()).unwrap_or("");
44    (g.covers(text("page")) && ask_is_payment(ask))
45        .then_some("auto-approve is on for this site, but a payment always asks")
46}
47
48/// The address `target` (a pane or popup window) shows, as the host reports
49/// it from the browser's own record of the page: never block meta, which a
50/// client can write. Not the agent's `eval`: that scans the whole page for
51/// secrets first, which on a large page outlasts the person's button.
52pub(crate) async fn page_url(state: &AppState, target: &str) -> Result<String, String> {
53    let host = get_host_ipc(state).await?;
54    let v = proxy_to_host_timeout(state, &host, "page_url", json!({ "block_id": target }), None).await?;
55    if v.get("ok").and_then(|o| o.as_bool()) == Some(false) {
56        return Err(v.get("error").and_then(|e| e.as_str()).unwrap_or("couldn't read the page's address").to_string());
57    }
58    v.pointer("/data/url")
59        .and_then(|r| r.as_str())
60        .map(str::to_string)
61        .ok_or_else(|| "couldn't read the page's address".to_string())
62}
63
64/// The click `ask` describes (a committing click's `needs_approval`), made
65/// without the person's approval if they granted `agent` a bypass on the
66/// site the page is on (bypass spec §4.1). `approved` is the act request to
67/// send for it. `page` is the address the host read from the page itself. A
68/// payment still asks (§11.2). None: ask as usual. `log` describes the click
69/// for the pane's action log. `route` is the host route that makes the click
70/// (`act`, or `press` for Enter and Space taken as one).
71pub(crate) async fn bypassed_click(
72    state: &AppState,
73    block_id: &str,
74    agent: &str,
75    ask: &serde_json::Value,
76    approved: serde_json::Value,
77    route: &str,
78    log: Note,
79) -> Option<Response> {
80    // A click or a drag in a canvas always asks: a grant for committing clicks does not cover it (spec §4.4).
81    if ask.get("canvas").and_then(|v| v.as_bool()) == Some(true) {
82        return None;
83    }
84    let pane = bypass_pane(block_id);
85    let g = match bypass::active_for(&pane, agent) {
86        Some(g) => g,
87        // No grant on this pane: the person's standing one for this agent on the page's site makes it.
88        None => {
89            let page = ask.get("page").and_then(|v| v.as_str()).unwrap_or("");
90            crate::server::browser_standing::activate_at(state, &pane, agent, page)?
91        }
92    };
93    // The person may have paused the pane after this act passed
94    // `target_block_id`: a paused grant is still live, so check again here.
95    if let Err((code, e)) = crate::server::browser_actions::not_paused(block_id) {
96        return Some(log.asked(ask).fail(state, code, e));
97    }
98    let what = ask.get("what").and_then(|v| v.as_str()).unwrap_or("");
99    let page = ask.get("page").and_then(|v| v.as_str()).unwrap_or("");
100    let origin = agentmux_common::allowed_origins::target_origin(page).unwrap_or_default();
101    if !g.covers(page) {
102        tracing::info!(agent_id = %agent, block_id = %block_id, origin = %origin, "[browser-bypass] paused: the page is off the granted sites, so the click asks");
103        return None;
104    }
105    if ask_is_payment(ask) {
106        tracing::info!(agent_id = %agent, block_id = %block_id, what = %what, "[browser-bypass] a payment still asks");
107        return None;
108    }
109    if form_leaves_the_site(ask, &origin) {
110        tracing::info!(agent_id = %agent, block_id = %block_id, origin = %origin, "[browser-bypass] the form sends to another site, so the click asks");
111        return None;
112    }
113    tracing::info!(
114        agent_id = %agent, block_id = %block_id, what = %what, origin = %origin, page = %page,
115        "[browser-bypass] committing click made without asking"
116    );
117    // The page may confirm it while the click is still running.
118    crate::server::browser_dialog::note_click(block_id, what, crate::server::browser_dialog::How::Auto);
119    let made = proxy_value(state, route, approved, std::time::Duration::from_secs(20)).await.map(|mut data| {
120        if let Some(o) = data.as_object_mut() {
121            o.insert("bypassed".to_string(), json!(true));
122            o.insert("bypass_minutes_left".to_string(), json!(g.minutes_left()));
123            o.insert("bypass_always".to_string(), json!(g.standing.is_some()));
124        }
125        data
126    });
127    Some(log.asked(ask).how(How::AutoApproved).outcome(state, made))
128}
129
130/// Does the form this click submits send its fields to a site other than the page's? The person's
131/// grant is for the site they gave, and a fake form on it can point `action` anywhere (now with a
132/// secret in its fields), so such a click always asks. A click with no form has no `action`.
133fn form_leaves_the_site(ask: &serde_json::Value, page_origin: &str) -> bool {
134    let Some(action) = ask.get("action").and_then(|v| v.as_str()).filter(|a| !a.is_empty()) else { return false };
135    agentmux_common::allowed_origins::target_origin(action).as_deref() != Some(page_origin)
136}
137
138/// A grant that was already there answers a request for it. It lasts what was asked or less: an ask for fewer
139/// minutes cuts it, and the answer says so.
140fn granted_asked_for(state: &AppState, pane: &str, agent: &str, asked: Option<u64>, g: bypass::Grant) -> Response {
141    match asked.and_then(|m| bypass::shorten(state, pane, agent, bypass::clamp_minutes(Some(m)))) {
142        Some((cut, was)) => granted_cut(&cut, Some(was)),
143        None => granted(&g),
144    }
145}
146
147/// The answer to a request that was granted.
148fn granted(g: &bypass::Grant) -> Response {
149    granted_cut(g, None)
150}
151
152/// A grant, and (when an earlier one was cut to what was asked) the minutes it had left before.
153fn granted_cut(g: &bypass::Grant, cut_from: Option<u64>) -> Response {
154    (
155        StatusCode::OK,
156        Json(json!({ "ok": true, "data": {
157            "answer": "granted", "origins": g.origins, "minutes": g.minutes, "powers": browser_powers::names(&g.powers),
158            "minutes_left": g.minutes_left(), "expires_at": g.expires_at_ms, "always": g.standing.is_some(),
159            "cut_from": cut_from,
160        } })),
161    )
162        .into_response()
163}
164
165/// Is `block_id` a browser pane?
166fn is_browser_pane(state: &AppState, block_id: &str) -> bool {
167    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten();
168    block.is_some_and(|b| b.meta.get("view").and_then(|v| v.as_str()) == Some("browser"))
169}
170
171/// `POST /api/v1/ui/browser/request_bypass` — backs Browser's `request_bypass`
172/// (SPEC_BROWSER_PANE_BYPASS_2026_10_16.md §6): a banner asks the person to
173/// let this agent act without asking first, on the site the pane shows, for a
174/// while; the call waits for their answer. Only their click in the pane,
175/// relayed by the host, grants it.
176pub(crate) async fn handle_ui_browser_request_bypass(
177    State(state): State<AppState>,
178    caller: Option<axum::Extension<crate::server::caller::Caller>>,
179    Json(req): Json<agentmux_common::api_types::UiBrowserRequestBypassRequest>,
180) -> impl IntoResponse {
181    let agent = req.auth.agent_id.clone();
182    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
183        Ok(b) => b,
184        Err((code, e)) => return err_response(code, e),
185    };
186    let pane = bypass_pane(&block_id);
187    let powers = match browser_powers::parse(req.powers.as_deref()) {
188        Ok(p) => p,
189        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
190    };
191    // A grant already there answers a request for what it carries. One that
192    // lacks a power the agent now asks for is not widened by asking: the
193    // person is shown the banner for the larger set.
194    if let Some(g) = bypass::active_for(&pane, &agent).filter(|g| powers.iter().all(|p| g.satisfies(*p))) {
195        return granted_asked_for(&state, &pane, &agent, req.minutes, g);
196    }
197    let (banner_at, in_window) = banner_for(&block_id);
198    if !is_browser_pane(&state, &banner_at) || crate::server::browser_owner::owner_of(&pane).is_none() {
199        return err_response(
200            StatusCode::BAD_REQUEST,
201            "Browser's request_auto_approve action needs a browser pane you opened: pass the `pane` its open action returned".to_string(),
202        );
203    }
204    let url = match page_url(&state, &block_id).await {
205        Ok(u) => u,
206        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
207    };
208    // The person's standing grant for this agent on this site answers at once,
209    // with no banner, and a No from before doesn't count against it.
210    if let Some(g) = crate::server::browser_standing::activate_at(&state, &pane, &agent, &url).filter(|g| powers.iter().all(|p| g.satisfies(*p))) {
211        return granted(&g);
212    }
213    if let Some(left) = bypass::cooling_down(&pane) {
214        return err_response(
215            StatusCode::TOO_MANY_REQUESTS,
216            format!(
217                "the user said No to auto-approve on this pane; don't ask again for {} more minutes. Carry on with \
218                 per-click approvals, or ask them in chat",
219                left.as_secs().div_ceil(60)
220            ),
221        );
222    }
223    let reason: String = req.reason.trim().chars().take(300).collect();
224    if reason.is_empty() {
225        return err_response(StatusCode::BAD_REQUEST, "say what you need it for (`reason`)".to_string());
226    }
227    if let Err(e) = crate::server::app_api::connections::host_to_ask_user(&state).await {
228        return err_response(StatusCode::SERVICE_UNAVAILABLE, e);
229    }
230    let origins = match bypass::origins_for(&pane, &url) {
231        Ok(o) => o,
232        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
233    };
234    let minutes = bypass::clamp_minutes(req.minutes);
235    let owner_before = crate::server::browser_owner::owner_of(&pane);
236    tracing::info!(agent_id = %agent, pane = %pane, origins = ?origins, minutes, "[browser-bypass] asking the user");
237    let (answer, _waiting) = match crate::server::browser_attention::ask(
238        &state,
239        &banner_at,
240        &agent,
241        crate::server::browser_attention::Kind::Bypass,
242        json!({
243            "reason": reason, "origins": origins, "minutes": minutes, "window": in_window,
244            "powers": browser_powers::names(&powers),
245        }),
246        std::time::Duration::from_secs(10 * 60),
247    )
248    .await
249    {
250        Ok(a) => a,
251        Err(e) => return err_response(e.status(), e.to_string()),
252    };
253    use crate::server::browser_attention::Answer;
254    let answer_was = answer;
255    let answer = match answer {
256        // A Take over while the banner was up wins over an Allow after it.
257        Answer::Yes | Answer::YesAlways | Answer::YesAsking if crate::server::browser_owner::owner_of(&pane) != owner_before => {
258            return err_response(StatusCode::FORBIDDEN, "the user took over this pane, so auto-approve wasn't turned on".to_string());
259        }
260        Answer::Yes => {
261            crate::server::browser_standing::resume(&pane);
262            return granted(&bypass::grant(&state, &pane, &agent, origins, powers, minutes, How::Approved));
263        }
264        // Allowed for the time, but each terminal line asks first.
265        Answer::YesAsking => {
266            crate::server::browser_standing::resume(&pane);
267            let powers = browser_powers::asking_each_line(&powers);
268            return granted(&bypass::grant(&state, &pane, &agent, origins, powers, minutes, How::Approved));
269        }
270        // "Always for this agent on this site": the sites the banner named
271        // become a standing row; the pane grant is made from it.
272        Answer::YesAlways => {
273            let names: Vec<String> = browser_powers::names(&powers).iter().map(|n| n.to_string()).collect();
274            let row = match crate::server::browser_standing::add_powers(&state, &agent, &origins, &names) {
275                Ok(r) => r,
276                Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
277            };
278            crate::server::browser_standing::resume(&pane);
279            let g = bypass::grant_standing(&state, &pane, &agent, row.origins.clone(), row.powers(), &row.id);
280            return granted(&g);
281        }
282        Answer::Cancelled => {
283            bypass::note_declined(&pane);
284            tracing::info!(agent_id = %agent, pane = %pane, "[browser-bypass] the user said No");
285            "declined"
286        }
287        Answer::TimedOut => "timed_out",
288    };
289    note(&pane, &agent, Kind::AutoApproveOn).detail(&reason).how(How::from_answer(answer_was)).record(&state);
290    (StatusCode::OK, Json(json!({ "ok": true, "data": { "answer": answer } }))).into_response()
291}
292
293/// `POST /api/v1/ui/browser/end_bypass` — backs Browser's `end_bypass`: an
294/// agent ends its own bypass when its job is done. An agent can end a grant,
295/// never start one.
296pub(crate) async fn handle_ui_browser_end_bypass(
297    State(state): State<AppState>,
298    caller: Option<axum::Extension<crate::server::caller::Caller>>,
299    Json(req): Json<agentmux_common::api_types::UiBrowserEndBypassRequest>,
300) -> impl IntoResponse {
301    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
302        Ok(b) => b,
303        Err((code, e)) => return err_response(code, e),
304    };
305    let pane = bypass_pane(&block_id);
306    let ended = bypass::active_for(&pane, &req.auth.agent_id).is_some() && bypass::end(&state, &pane, "the agent turned it off", true, How::Allowed);
307    (StatusCode::OK, Json(json!({ "ok": true, "data": { "ended": ended } }))).into_response()
308}
309
310/// `POST /api/v1/host/browser_bypass` — the person's Bypass button and End
311/// bypass, relayed by the CEF host (bypass spec §5). Only the host can call
312/// it: an agent holding the instance auth key gets 403, so no agent can grant
313/// itself a bypass. Body `{block_id, on, minutes?, agent, origins}`: `agent`
314/// and `origins` are what the confirmation showed; the grant is made only if
315/// they are still true.
316pub(crate) async fn handle_host_browser_bypass(
317    State(state): State<AppState>,
318    headers: axum::http::HeaderMap,
319    Json(body): Json<serde_json::Value>,
320) -> impl IntoResponse {
321    if !from_host(&state, &headers).await {
322        return err_response(StatusCode::FORBIDDEN, "only the AgentMux host can turn auto-approve on or off".to_string());
323    }
324    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
325    let block_id = s("block_id");
326    let pane = bypass_pane(&block_id);
327    if body.get("on").and_then(|v| v.as_bool()) != Some(true) {
328        // A standing grant would be made again by the agent's next call:
329        // Stop also holds that off until the person turns it on again.
330        let ended = bypass::active_for_any(&pane);
331        crate::server::browser_standing::stop_by_person(&state, &pane);
332        return (StatusCode::OK, Json(json!({ "ok": true, "data": { "ended": ended } }))).into_response();
333    }
334    let block = match state.mstore.get::<crate::backend::obj::Block>(&pane) {
335        Ok(Some(b)) => b,
336        _ => return err_response(StatusCode::NOT_FOUND, "the pane is gone".to_string()),
337    };
338    let Some(owner) = owning_agent(&block, &pane) else {
339        return err_response(StatusCode::CONFLICT, "no agent drives this pane any more".to_string());
340    };
341    if !owner.eq_ignore_ascii_case(&s("agent")) {
342        return err_response(StatusCode::CONFLICT, format!("{owner} drives this pane now, not who you were shown; look again"));
343    }
344    if crate::server::browser_attention::waiting_on_user(&pane).is_some() {
345        return err_response(StatusCode::CONFLICT, "the pane is waiting for your answer to its banner; answer that first".to_string());
346    }
347    let url = match page_url(&state, &pane).await {
348        Ok(u) => u,
349        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
350    };
351    let origins = match bypass::origins_for(&pane, &url) {
352        Ok(o) => o,
353        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
354    };
355    let shown: Vec<String> = body
356        .get("origins")
357        .and_then(|v| v.as_array())
358        .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
359        .unwrap_or_default();
360    let shown = agentmux_common::allowed_origins::parse_list(&shown).unwrap_or_default();
361    if shown != origins {
362        return err_response(
363            StatusCode::CONFLICT,
364            format!("the page is on {} now, not what you were shown; look again", origins.join(", ")),
365        );
366    }
367    let minutes = bypass::clamp_minutes(body.get("minutes").and_then(|v| v.as_u64()));
368    // The header's button turns on what Auto-approve always was: committing clicks.
369    crate::server::browser_standing::resume(&pane);
370    let g = bypass::grant(&state, &pane, &owner, origins, vec![Power::Clicks], minutes, How::ByUser);
371    (
372        StatusCode::OK,
373        Json(json!({ "ok": true, "data": { "origins": g.origins, "minutes": g.minutes, "expires_at": g.expires_at_ms } })),
374    )
375        .into_response()
376}
377
378#[cfg(test)]
379mod tests {
380    #[test]
381    fn a_pane_holds_its_own_grant() {
382        // A popup pane (or any pane) is its own: only a popup window, which
383        // has no header, is covered by its opener's grant.
384        assert_eq!(super::bypass_pane("a-pane-id"), "a-pane-id");
385    }
386
387    #[test]
388    fn a_form_sending_to_another_site_always_asks() {
389        let ask = |action: serde_json::Value| serde_json::json!({ "what": "Click \"Save\"", "action": action });
390        let page = "https://appstoreconnect.apple.com";
391        assert!(!super::form_leaves_the_site(&ask(serde_json::json!("https://appstoreconnect.apple.com/save")), page));
392        assert!(!super::form_leaves_the_site(&ask(serde_json::Value::Null), page));
393        assert!(super::form_leaves_the_site(&ask(serde_json::json!("https://evil.example/collect")), page));
394        assert!(super::form_leaves_the_site(&ask(serde_json::json!("javascript:send()")), page));
395    }
396}