Skip to main content

agentmux_srv/server/
browser_capture.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `capture`: a secret a web page shows once goes straight into the Vault
5//! (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §15.1).
6//!
7//! The host reads the element a reference names and marks it as holding a Vault
8//! value; srv stores what it read as a new entry, or as the new value of one the
9//! agent names, and answers with the entry's id. The value never reaches the agent.
10//! The entry keeps the page's origin, which the host takes from its own frame map,
11//! as its `service` or `site`, and the Activity says "captured from <origin>".
12//!
13//! With `download`, the reference is the button or link that downloads a file (a
14//! GitHub App's private key): the host clicks it and takes the file off the network
15//! before it becomes a download, so it is never written to disk, and srv stores its
16//! text (a `note` by default). A click that commits something (a form's submit)
17//! waits for the person's approval in the pane, as an `act` click does.
18//!
19//! A new entry asks nobody: saving a value takes nothing out of the Vault, and the
20//! page already showed it. Replacing an existing entry's value asks the person each
21//! time, as a capture from a command does (§4.2).
22
23use std::collections::BTreeMap;
24use std::time::Duration;
25
26use axum::extract::State;
27use axum::http::StatusCode;
28use axum::response::{IntoResponse, Response};
29use axum::Json;
30use serde::Deserialize;
31use serde_json::{json, Value};
32use zeroize::Zeroizing;
33
34use agentmux_common::api_types::{CaptureFrom, CaptureInto, CaptureRule, UiAutomationAuth};
35
36use crate::backend::vault::capture::{self, Found, Target};
37use crate::backend::vault::pace::{admit, refund, Act};
38
39use super::browser_actions::{note, How, Kind};
40use super::browser_capture_read::{begin, check_shape, read_page, what_to_read};
41use agentmux_common::capture_shape::CaptureShape;
42use super::ui_handlers::{err_response, proxy_value, target_block_id};
43use super::AppState;
44
45pub(super) const HOST_WAIT: Duration = Duration::from_secs(30);
46/// The longest the host waits for a download after its click (2 minutes), and
47/// time for the click and the reply.
48pub(super) const DOWNLOAD_WAIT: Duration = Duration::from_secs(150);
49
50#[derive(Debug, Deserialize)]
51pub(crate) struct CaptureRequest {
52    pub(super) auth: UiAutomationAuth,
53    #[serde(default)]
54    pub(super) pane: Option<String>,
55    #[serde(rename = "ref", default)]
56    pub(super) ref_: Option<String>,
57    /// A card shown on the page: each part's key (`number`, `exp`, `exp_month`, `exp_year`, `cvc`, `name`, `zip`) and the
58    /// ref of the element that shows it. Saved whole as a new card (`as`), instead of `ref`.
59    #[serde(default)]
60    pub(super) card: Option<BTreeMap<String, String>>,
61    /// A new entry: its kind (`api-key` by default), label, and plain fields.
62    #[serde(rename = "as", default)]
63    pub(super) into: Option<CaptureAs>,
64    /// Or an existing entry, whose value this replaces.
65    #[serde(default)]
66    pub(super) entry: Option<String>,
67    /// The file the element downloads, instead of the element's text.
68    #[serde(default)]
69    pub(super) download: bool,
70    /// How long to wait for the download after the click (at most 2 minutes).
71    #[serde(default)]
72    pub(super) timeout_ms: Option<u64>,
73    /// Why the agent keeps what the page shows: one line of 8 to 300 characters, required.
74    #[serde(default)]
75    pub(super) reason: Option<String>,
76    /// Text with no reference of its own: the value shown beside this label. Instead of `ref`.
77    #[serde(default)]
78    pub(super) near: Option<String>,
79    /// What the value must be, or nothing is saved: a short prefix, one of the named shapes, a length range.
80    #[serde(default)]
81    pub(super) prefix: Option<String>,
82    #[serde(default)]
83    pub(super) shape: Option<String>,
84    #[serde(default)]
85    pub(super) min_length: Option<u32>,
86    #[serde(default)]
87    pub(super) max_length: Option<u32>,
88    /// The reference is the page's own copy button: its value is taken from the page's copy, never the clipboard.
89    #[serde(default)]
90    pub(super) copy: bool,
91}
92
93#[derive(Debug, Default, Deserialize)]
94pub(crate) struct CaptureAs {
95    #[serde(default)]
96    pub(super) kind: Option<String>,
97    #[serde(default)]
98    pub(super) label: String,
99    #[serde(default)]
100    pub(super) fields: BTreeMap<String, String>,
101    #[serde(default)]
102    pub(super) expires: Option<String>,
103}
104
105/// The plain field a kind keeps a page's origin in.
106fn origin_field(kind: &str) -> Option<&'static str> {
107    match kind {
108        "api-key" => Some("service"),
109        "login" => Some("site"),
110        _ => None,
111    }
112}
113
114/// The capture rule the request describes, checked like a command's.
115fn rule_of(req: &CaptureRequest) -> Result<CaptureRule, String> {
116    let into = match (&req.entry, &req.into) {
117        (Some(_), Some(_)) => return Err("name an existing entry (entry) or a new one (as), not both".into()),
118        (Some(id), None) => CaptureInto { id: Some(id.clone()), ..Default::default() },
119        (None, Some(a)) => {
120            // A file is kept as a note's text; a value as an API key's.
121            let kind = a.kind.clone().unwrap_or_else(|| if req.download { "note" } else { "api-key" }.into());
122            CaptureInto { kind: Some(kind), label: Some(a.label.clone()), ..Default::default() }
123        }
124        (None, None) => return Err("say where it goes: as {kind, label} for a new entry, or entry for an existing one".into()),
125    };
126    Ok(CaptureRule { into, from: CaptureFrom::Stdout("all".into()) })
127}
128
129/// `POST /api/v1/ui/browser/capture`.
130/// `POST /api/v1/ui/browser/capture`: a card the page shows is saved whole, anything else is one value.
131pub(crate) async fn handle_capture(
132    State(state): State<AppState>,
133    caller: Option<axum::Extension<crate::server::caller::Caller>>,
134    Json(req): Json<CaptureRequest>,
135) -> Response {
136    if req.card.is_some() {
137        return super::browser_capture_card::capture_card(state, caller, req).await;
138    }
139    handle_browser_capture(State(state), caller, Json(req)).await
140}
141
142/// What a capture read from the page: the value, the page's origin, the file's name when a file was taken, and the element's
143/// reference (text found beside a label has one now, which marks it once it is saved).
144struct Taken {
145    value: Zeroizing<String>,
146    origin: String,
147    file: Option<String>,
148    ref_: String,
149}
150
151/// Reads the element and checks what came back, or the answer for the agent when it can't be saved.
152async fn read_for_capture(state: &AppState, req: &CaptureRequest, block_id: &str, agent: &str, ref_: &str, shape: Option<&CaptureShape>) -> Result<(Taken, Option<super::browser_attention::Waiting>), Response> {
153    let (read, approved_click) = match read_page(state, req, block_id, agent, (ref_, shape)).await {
154        Ok(r) => r,
155        Err(refused) => return Err(super::browser_capture_read::counted(refused, shape, agent)),
156    };
157    let file = read.get("name").and_then(Value::as_str).map(|n| n.chars().take(200).collect::<String>());
158    let ref_ = read.get("ref").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| ref_.to_string());
159    let (value, origin) = take_read(read).map_err(|e| err_response(StatusCode::BAD_GATEWAY, e))?;
160    check_shape(shape, &value, agent).map_err(|e| err_response(StatusCode::UNPROCESSABLE_ENTITY, e))?;
161    if origin.is_empty() {
162        return Err(err_response(StatusCode::BAD_REQUEST, "AgentMux can't tell which site this page is, so nothing was saved".into()));
163    }
164    Ok((Taken { value, origin, file, ref_ }, approved_click))
165}
166
167async fn handle_browser_capture(
168    State(state): State<AppState>,
169    caller: Option<axum::Extension<crate::server::caller::Caller>>,
170    Json(req): Json<CaptureRequest>,
171) -> Response {
172    let (ref_, shape) = match what_to_read(&req) {
173        Ok(r) => r,
174        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
175    };
176    let reason = match crate::backend::vault::history::require_reason(req.reason.as_deref()) {
177        Ok(r) => r,
178        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
179    };
180    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
181        Ok(b) => b,
182        Err((code, e)) => return err_response(code, e),
183    };
184    let agent: String = req.auth.agent_id.chars().take(64).collect();
185    if let Err(e) = begin(shape.as_ref(), &agent) {
186        return err_response(StatusCode::TOO_MANY_REQUESTS, e);
187    }
188    let rule = match rule_of(&req) {
189        Ok(r) => r,
190        Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
191    };
192    let (store, a) = (state.identity_store.clone(), agent.clone());
193    let mut plan = match tokio::task::spawn_blocking(move || capture::plan(&store, &[rule], &a, "")).await {
194        Ok(Ok(p)) => p,
195        Ok(Err(e)) => return err_response(StatusCode::BAD_REQUEST, e),
196        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
197    };
198
199    plan.reason = reason.clone();
200    // Nobody is asked to allow the write, replacing a value included: the history line is the record, the old value is kept
201    // 7 days, and the agent's pace bounds how much it does in an hour.
202    let act = match &plan.rules[0].into {
203        Target::Existing { id, .. } => Act::Replace(id.clone()),
204        Target::New { .. } => Act::New,
205    };
206    let spent = [act];
207    if let Err(e) = admit(&agent, &spent) {
208        if let (Target::Existing { id, label, .. }, true) = (&plan.rules[0].into, crate::backend::vault::pace::may_note_refusal(&agent)) {
209            let line = crate::backend::vault::Line { entry_id: id, label, actor: &agent, action: capture::CAPTURED, target: "from a page", outcome: "refused: pace", reason: &reason };
210            crate::backend::vault::record_line(&state.identity_store, line);
211        }
212        return err_response(StatusCode::TOO_MANY_REQUESTS, e);
213    }
214
215    // Held until the approved click is made, if one waits for the person.
216    let (taken, _approved_click) = match read_for_capture(&state, &req, &block_id, &agent, &ref_, shape.as_ref()).await {
217        Ok(r) => r,
218        Err(refused) => {
219            // Nothing was stored: a capture that failed does not use up the agent's pace.
220            refund(&agent, &spent);
221            return refused;
222        }
223    };
224    let Taken { value, origin, file, ref_ } = taken;
225    let (store, given, from) = (state.identity_store.clone(), req.into, origin.clone());
226    let stored = tokio::task::spawn_blocking(move || store_captured(&store, plan, value, &from, given.as_ref())).await;
227    if !matches!(stored, Ok(Ok(_))) {
228        refund(&agent, &spent);
229    }
230    super::vault_handlers::publish(&state);
231    // Only now that it is stored is the element marked: a refused capture leaves no
232    // mark (one that would keep eval refused on the tab for nothing).
233    let mut marked = false;
234    // A downloaded file, and what a copy button copied, are on no element to mark.
235    if matches!(stored, Ok(Ok(_))) && !req.download && !req.copy {
236        match proxy_value(&state, "capture_mark", json!({ "block_id": block_id, "ref": ref_ }), HOST_WAIT).await {
237            Ok(_) => marked = true,
238            Err((_, e)) => tracing::warn!(error = %e, "[vault] a captured element couldn't be marked"),
239        }
240    }
241    // The pane's own Log: what was captured, from where, never the value.
242    let log = note(&block_id, &agent, Kind::Capture).target(&ref_);
243    match &stored {
244        Ok(Ok((_, label))) => {
245            let what = file.as_deref().map(|f| format!("{label} (the file {f})")).unwrap_or_else(|| label.clone());
246            log.detail(&format!("{what}, captured from {origin}")).how(How::Allowed).record(&state)
247        }
248        Ok(Err(e)) => log.how(How::Refused(e.chars().take(160).collect())).record(&state),
249        Err(_) => {}
250    }
251    match stored {
252        Ok(Ok((id, label))) => {
253            let note = if file.is_some() { DOWNLOADED_NOTE } else if req.copy { COPIED_NOTE } else { captured_note(marked) };
254            let out = json!({ "ok": true, "id": id, "label": label, "captured_from": origin, "file": file, "marked": marked, "copied": req.copy, "note": note });
255            (StatusCode::OK, Json(out)).into_response()
256        }
257        Ok(Err(e)) => err_response(StatusCode::BAD_REQUEST, format!("nothing was saved: {e}")),
258        Err(e) => err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
259    }
260}
261
262/// What the agent is told once a downloaded file is saved.
263const DOWNLOADED_NOTE: &str = "Saved in the Vault; you never see the file. It was never written to disk: give it to a command with Terminal run's secret_files.";
264
265/// What the agent is told once a value taken from the page's copy button is saved.
266const COPIED_NOTE: &str = "Saved in the Vault; you never see the value. It was taken from the page's own copy action: the system clipboard was never written, and nothing was left on it.";
267
268/// What the agent is told about the page once the value is saved: what keeps
269/// hiding it there depends on whether the element could be marked.
270pub(super) fn captured_note(marked: bool) -> &'static str {
271    if marked {
272        "Saved in the Vault; you never see the value. While it is on the page, screenshots black it out and eval is refused on this tab; snapshots keep hiding it while it shows as a secret, and always in a field."
273    } else {
274        "Saved in the Vault; you never see the value. The page changed before the element could be marked, so only a value with a secret's shape stays hidden on it: don't read the element again, and navigate away when you're done."
275    }
276}
277
278/// Stores a captured value: a new entry starts with the page's origin as its
279/// `service` or `site` (unless the agent gave one), the fields and expiry date the
280/// agent gave; an existing one gets it as its new value, the old one kept 7 days.
281/// Returns the entry's id and label.
282pub(crate) fn store_captured(
283    store: &crate::backend::storage::store::Store,
284    mut plan: capture::Capture,
285    value: Zeroizing<String>,
286    origin: &str,
287    given: Option<&CaptureAs>,
288) -> Result<(String, String), String> {
289    plan.cmd = format!("from {origin}");
290    if let (Target::New { kind, fields, .. }, Some(given)) = (&mut plan.rules[0].into, given) {
291        fields.extend(given.fields.clone());
292        if let Some(date) = given.expires.as_ref().filter(|d| !d.trim().is_empty()) {
293            fields.insert("expires".into(), date.clone());
294        }
295        if let Some(f) = origin_field(kind) {
296            fields.entry(f.to_string()).or_insert_with(|| origin.to_string());
297        }
298    }
299    let ids = plan.store(store, &[Found { value, printed: None, also: Vec::new() }])?;
300    let label = match &plan.rules[0].into {
301        Target::New { label, .. } | Target::Existing { label, .. } => label.clone(),
302    };
303    Ok((ids.into_iter().next().unwrap_or_default(), label))
304}
305
306/// The value and origin from the host's answer, the value moved out of the JSON
307/// into memory that is wiped when dropped.
308pub(super) fn take_read(mut v: Value) -> Result<(Zeroizing<String>, String), String> {
309    let origin = v.get("origin").and_then(Value::as_str).unwrap_or("").to_string();
310    match v.get_mut("value").map(Value::take) {
311        Some(Value::String(s)) => Ok((Zeroizing::new(s), origin)),
312        _ => Err("the browser didn't send the element's value".into()),
313    }
314}
315
316#[cfg(test)]
317#[path = "browser_capture_tests.rs"]
318mod tests;