1use 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);
46pub(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 #[serde(default)]
60 pub(super) card: Option<BTreeMap<String, String>>,
61 #[serde(rename = "as", default)]
63 pub(super) into: Option<CaptureAs>,
64 #[serde(default)]
66 pub(super) entry: Option<String>,
67 #[serde(default)]
69 pub(super) download: bool,
70 #[serde(default)]
72 pub(super) timeout_ms: Option<u64>,
73 #[serde(default)]
75 pub(super) reason: Option<String>,
76 #[serde(default)]
78 pub(super) near: Option<String>,
79 #[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 #[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
105fn origin_field(kind: &str) -> Option<&'static str> {
107 match kind {
108 "api-key" => Some("service"),
109 "login" => Some("site"),
110 _ => None,
111 }
112}
113
114fn 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 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
129pub(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
142struct Taken {
145 value: Zeroizing<String>,
146 origin: String,
147 file: Option<String>,
148 ref_: String,
149}
150
151async 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 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 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 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 let mut marked = false;
234 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 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
262const 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
265const 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
268pub(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
278pub(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
306pub(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;