Skip to main content

agentmux_srv/server/browser_vault_fill/
card.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `fill` with `vault: "<card id>"` (or `"card"`, the default card): one question
5//! for the person, then every card field the form has is filled
6//! (docs/specs/SPEC_VAULT_CARD_ENTRIES_FULL_CARD_DATA_AND_AUTOFILL_2026_11_08.md ยง6).
7//!
8//! The host says which fields of the form look like parts of a card and how each takes its
9//! text (`card_form`); the person is asked once, naming the card and the parts; then each field
10//! is filled through the same `vault_fill` as a single field, which checks it again. The answer
11//! lists the parts filled and the parts the form wanted that were left, by name; a value is in
12//! no answer, error or record. A card that has expired is asked about every time: no "Always"
13//! is offered for it and none already given counts.
14
15use serde_json::{json, Value};
16use zeroize::Zeroizing;
17
18use super::*;
19use crate::backend::vault::card_fill::{self, FormField, Shaped};
20use crate::backend::vault::card_target::{self, Asked, CardTarget};
21use crate::backend::vault::seal::Parts;
22use crate::server::caller::Caller;
23
24/// A field of the form the host matched to a part of a card.
25struct CardField {
26    ref_: String,
27    fingerprint: String,
28    shape: FormField,
29}
30
31/// The slots that make a form a card form: a ZIP or a name alone is a single-field fill's.
32const MAIN_SLOTS: [&str; 5] = ["card-number", "card-expiry", "card-exp-month", "card-exp-year", "card-cvc"];
33
34fn parse_fields(form: &Value) -> Vec<CardField> {
35    let text = |f: &Value, k: &str| f.get(k).and_then(Value::as_str).unwrap_or("").to_string();
36    let mut out: Vec<CardField> = Vec::new();
37    for f in form.get("fields").and_then(Value::as_array).into_iter().flatten() {
38        let slot = text(f, "slot");
39        if card_fill::part_of_slot(&slot).is_none() || out.iter().any(|o| o.shape.slot == slot) {
40            continue;
41        }
42        let shape = FormField {
43            slot,
44            select: f.get("select").and_then(Value::as_bool).unwrap_or(false),
45            input_type: text(f, "input_type"),
46            max_length: f.get("max_length").and_then(Value::as_u64).map(|m| m as usize),
47            placeholder: text(f, "placeholder"),
48            pattern: text(f, "pattern"),
49        };
50        out.push(CardField { ref_: text(f, "ref"), fingerprint: text(f, "fingerprint"), shape });
51    }
52    out
53}
54
55/// The parts the form asks for, by name, once each ("number, expiry, security code").
56fn part_names(fields: &[CardField]) -> Vec<&'static str> {
57    let mut names: Vec<&'static str> = Vec::new();
58    for f in fields {
59        let n = card_fill::part_name(&f.shape.slot);
60        if !names.contains(&n) {
61            names.push(n);
62        }
63    }
64    names
65}
66
67/// Takes the call when `vault` names a whole card, `None` for any other fill.
68pub(super) async fn whole_card(state: &AppState, caller: Option<&Caller>, req: &VaultFillRequest, block_id: &str, agent: &str, reason: &str) -> Option<Response> {
69    if req.vault.is_none() && req.request_kind.as_deref().map(str::trim) == Some("card") {
70        return Some(typed::typed_card(state, caller, req, block_id, agent).await);
71    }
72    let wanted = req.vault.clone()?;
73    let (store, who) = (state.identity_store.clone(), agent.to_string());
74    let found = tokio::task::spawn_blocking(move || {
75        let asked = card_target::card_asked(&store, &wanted, Some(&who))?;
76        let cards = if matches!(asked, Asked::NotACard) { Vec::new() } else { card_target::card_choices(&store, Some(&who))? };
77        Ok::<_, String>((asked, cards))
78    })
79    .await;
80    match found {
81        Ok(Ok((Asked::NotACard, _))) => None,
82        Ok(Ok((Asked::One(card), cards))) => Some(fill_card(state, caller, req, block_id, agent, reason, Some(*card), cards).await),
83        // The cards the person might pick from can be none: all deleted, or none that opens, since `card_asked` looked.
84        Ok(Ok((Asked::Pick, cards))) if cards.is_empty() => Some(err_response(StatusCode::BAD_REQUEST, "you have no card saved that can be filled: ask the person to add one in the Vault, or to type it (Vault request_value)".to_string())),
85        Ok(Ok((Asked::Pick, cards))) => Some(fill_card(state, caller, req, block_id, agent, reason, None, cards).await),
86        Ok(Err(e)) => Some(err_response(StatusCode::BAD_REQUEST, e)),
87        Err(e) => Some(err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
88    }
89}
90
91/// What the person is asked: the card named (or none), and the cards they may pick from when they may.
92struct Question<'a> {
93    card: Option<&'a CardTarget>,
94    picker: &'a [CardTarget],
95    origin: &'a str,
96    /// The page's origin when the fields are in another site's frame, else empty.
97    page: &'a str,
98    names: &'a [&'a str],
99    offer_always: bool,
100    why: &'a str,
101}
102
103fn card_question(agent: &str, pane: String, q: &Question, agent_reason: &str) -> UseRequest {
104    UseRequest {
105        id: uuid::Uuid::new_v4().to_string(),
106        agent: agent.to_string(),
107        block_id: pane,
108        entry_id: q.card.map(|c| c.fill.id.clone()).unwrap_or_default(),
109        entry_label: q.card.map(|c| c.fill.label.clone()).unwrap_or_else(|| "a card".to_string()),
110        what: q.card.map(CardTarget::describe).unwrap_or_else(|| "card".to_string()),
111        origin: q.origin.to_string(),
112        page: q.page.to_string(),
113        field: format!("the card fields: {}", q.names.join(", ")),
114        offer_always: q.offer_always,
115        reason: q.why.to_string(),
116        agent_reason: agent_reason.to_string(),
117        kind: "card".to_string(),
118        requested_ms: agentmux_common::time::now_ms_u64(),
119        choices: (!q.picker.is_empty()).then(|| q.picker.iter().map(CardTarget::choice).collect()),
120        ..Default::default()
121    }
122}
123
124/// What fills one field: the host is told the text, or the month or year to choose, and the field it was approved for.
125async fn fill_field(state: &AppState, block_id: &str, origin: &str, field: &CardField, text: &str, choose: Option<&str>) -> Result<Value, (StatusCode, String)> {
126    let body = json!({
127        "block_id": block_id,
128        "ref": field.ref_,
129        "text": text,
130        "expect_origin": origin,
131        "expect_fingerprint": field.fingerprint,
132        "choose": choose,
133    });
134    proxy_value(state, "vault_fill", body, HOST_WAIT).await
135}
136
137/// An error with no part of the card in it: a page's or a parser's message can quote what it was given.
138fn without_card(e: &str, parts: &Parts) -> String {
139    let mut out = e.to_string();
140    for v in parts.0.values().filter(|v| v.chars().count() >= 3) {
141        out = out.replace(v.as_str(), "[hidden]");
142    }
143    out
144}
145
146/// What the fill did, by part name: never a value.
147#[derive(Default)]
148struct Outcome {
149    filled: Vec<&'static str>,
150    left: Vec<Value>,
151    failed: Vec<Value>,
152    flagged: bool,
153    reformatted: bool,
154}
155
156async fn fill_all(state: &AppState, block_id: &str, origin: &str, fields: &[CardField], parts: &Parts) -> Outcome {
157    let mut done = Outcome::default();
158    for f in fields {
159        let part = card_fill::part_name(&f.shape.slot);
160        let (text, choose): (Zeroizing<String>, Option<&str>) = match card_fill::shape(&f.shape, parts) {
161            Shaped::Left(why) => {
162                done.left.push(json!({ "part": part, "why": why }));
163                continue;
164            }
165            Shaped::Text(t) => (t, None),
166            Shaped::Choose(t) => (t, Some(if f.shape.slot == "card-exp-month" { "month" } else { "year" })),
167        };
168        match fill_field(state, block_id, origin, f, &text, choose).await {
169            Ok(data) => {
170                if !done.filled.contains(&part) {
171                    done.filled.push(part);
172                }
173                // The page's own message can echo the value: the agent is told only that there is one.
174                done.flagged |= data.get("validation").and_then(Value::as_str).is_some_and(|v| !v.is_empty());
175                done.reformatted |= data.get("changed_by_page").and_then(Value::as_bool) == Some(true);
176            }
177            Err((_, e)) => done.failed.push(json!({ "part": part, "why": without_card(&e, parts) })),
178        }
179    }
180    done
181}
182
183fn answer(entry: &str, origin: &str, page: &str, done: &Outcome, went_ahead: bool) -> Value {
184    let mut out = json!({
185        // The entry's id and part names only: the brand, last four and expiry are the person's to see.
186        "filled_from_vault": entry,
187        "parts_filled": done.filled,
188        "value": "[secret: hidden]",
189        "site": origin,
190    });
191    if let Some(o) = out.as_object_mut() {
192        if !page.is_empty() {
193            o.insert("in_a_frame_on".into(), json!(page));
194        }
195        if !done.left.is_empty() {
196            o.insert("parts_left".into(), json!(done.left));
197        }
198        if !done.failed.is_empty() {
199            o.insert("parts_failed".into(), json!(done.failed));
200        }
201        if went_ahead {
202            o.insert("approval".into(), json!(uses::WENT_AHEAD));
203        }
204        if done.flagged {
205            o.insert("validation".into(), json!("the page flagged a value as invalid (its message isn't shown, since a page can put the value in it)"));
206        }
207        if done.reformatted {
208            o.insert("note".into(), json!("the page shortened or reformatted a value"));
209        }
210    }
211    out
212}
213
214/// Whether the person may pick the card: none was named, or they have more than one.
215fn picks(card: &Option<CardTarget>, picker: &[CardTarget]) -> bool {
216    card.is_none() || picker.len() > 1
217}
218
219/// The card the fill is for once the person has answered, and how they answered.
220struct Settled {
221    card: CardTarget,
222    always: bool,
223    went_ahead: bool,
224}
225
226/// What a use record names when no card was chosen (a refusal, a no, no answer): never a card of the person's.
227fn stand_in(card: &Option<CardTarget>, picker: &[CardTarget]) -> crate::backend::vault::FillTarget {
228    match (card, picker.first()) {
229        (Some(c), _) => c.fill.clone(),
230        (None, Some(first)) => {
231            let mut fill = first.fill.clone();
232            fill.id = String::new();
233            fill.label = "a card".to_string();
234            fill
235        }
236        (None, None) => unreachable!("a whole-card fill has a card or a list of cards"),
237    }
238}
239
240/// Asks the person, unless this card is granted on this site and current: the card they chose (the named one when
241/// they chose none), or the response that ends the call.
242async fn settle(state: &AppState, caller: Option<&Caller>, req: &VaultFillRequest, call: (&str, &str, &str), place: (&str, &str, &[&str]), (card, picker): (Option<CardTarget>, Vec<CardTarget>)) -> Result<Settled, Response> {
243    let ((block_id, agent, reason), (origin, page, names)) = (call, place);
244    // A payment frame is asked about, and granted, with the page it is on.
245    let grant_key = grant_site(origin, page);
246    let site = format!("{grant_key} (card form)");
247    let (store, grant_origin) = (state.identity_store.clone(), grant_key);
248    let granted_id = card.as_ref().filter(|c| !c.expired).map(|c| c.fill.id.clone());
249    let granted = match granted_id {
250        Some(entry) => tokio::task::spawn_blocking(move || store.vault_grant_check(&entry, &grant_origin).unwrap_or(false)).await.unwrap_or(false),
251        None => false,
252    };
253    let pick = picks(&card, &picker);
254    let planned = plan(!origin.is_empty(), false, true, granted, true);
255    if let Plan::Refuse(why) = planned {
256        record(state, block_id, &stand_in(&card, &picker), agent, &site, "refused", reason);
257        return Err(err_response(StatusCode::BAD_REQUEST, why.to_string()));
258    }
259    if matches!(planned, Plan::Go) && card.as_ref().is_some_and(|c| !c.expired) {
260        return Ok(Settled { card: card.expect("a card was named"), always: false, went_ahead: false });
261    }
262    let expired = card.as_ref().is_some_and(|c| c.expired);
263    let (offer_always, why) = match planned {
264        // The person may pick a current card, so "Always" is offered and enforced per card (vault_handlers.rs).
265        _ if pick => (true, if card.is_none() { "no card was named, and there is no default card" } else { "you may want a different card" }),
266        Plan::Ask { offer_always, reason } if !expired => (offer_always, reason),
267        _ => (false, "the card has expired"),
268    };
269    let asked = Question { card: card.as_ref(), picker: if pick { &picker } else { &[] }, origin, page, names, offer_always, why };
270    let question = card_question(agent, super::super::vault_ask::agent_pane(state, caller, &req.auth), &asked, reason);
271    let what = card.as_ref().map(CardTarget::describe).unwrap_or_else(|| "card".to_string());
272    let headline = if page.is_empty() { format!("{agent} wants to fill your {what} on {origin}") } else { format!("{agent} wants to fill your {what} in a card field from {origin} on {page}") };
273    let (ended, answer) = super::super::vault_ask::ask(state, block_id, question, ANSWER_WAIT, &headline).await;
274    if !ended.allowed() {
275        record(state, block_id, &stand_in(&card, &picker), agent, &site, ended.outcome(), reason);
276        let code = if ended == Ended::NoAnswer { StatusCode::REQUEST_TIMEOUT } else { StatusCode::FORBIDDEN };
277        return Err(err_response(code, ended.refusal("nothing was typed")));
278    }
279    // The card they picked is one of those opened for this question, so a card changed since is caught when it is opened.
280    let picked = answer.and_then(|a| a.choice);
281    let stand = stand_in(&card, &picker);
282    let chosen = match (picked, card) {
283        (Some(id), Some(c)) if c.fill.id == id => Some(c),
284        (Some(id), _) => picker.into_iter().find(|c| c.fill.id == id),
285        (None, c) => c,
286    };
287    let Some(card) = chosen else {
288        record(state, block_id, &stand, agent, &site, "failed", reason);
289        return Err(err_response(StatusCode::BAD_REQUEST, "no card was chosen: nothing was typed".to_string()));
290    };
291    Ok(Settled { always: ended == Ended::Always && !card.expired, went_ahead: ended == Ended::WentAhead, card })
292}
293
294/// What the host found of a card form: where it is, and the fields it matched to a card's parts.
295struct CardForm {
296    origin: String,
297    /// The page's origin when the fields are in another site's frame, else empty: the question and the grant carry both.
298    page: String,
299    grant_key: String,
300    fields: Vec<CardField>,
301    names: Vec<&'static str>,
302}
303
304/// Asks the host for the card form the field `ref_` is in, or says why there is none.
305async fn read_form(state: &AppState, block_id: &str, ref_: &str, instead: &str) -> Result<CardForm, Response> {
306    let form = match proxy_value(state, "card_form", json!({ "block_id": block_id, "ref": ref_ }), HOST_WAIT).await {
307        Ok(v) => v,
308        Err((code, e)) => return Err(err_response(code, e)),
309    };
310    let origin = form.get("origin").and_then(Value::as_str).unwrap_or("").to_string();
311    let page = framed_in(&origin, form.get("page_origin").and_then(Value::as_str).unwrap_or(""));
312    let grant_key = grant_site(&origin, &page);
313    let fields = parse_fields(&form);
314    if !fields.iter().any(|f| MAIN_SLOTS.contains(&f.shape.slot.as_str())) {
315        return Err(err_response(StatusCode::BAD_REQUEST, format!("no card number, expiry or security code field was found with that one: {instead}, or take a new snapshot")));
316    }
317    let names = part_names(&fields);
318    Ok(CardForm { origin, page, grant_key, fields, names })
319}
320
321/// Why nothing was filled, by part name: never a value.
322fn why_nothing(done: &Outcome) -> String {
323    done.failed.iter().chain(&done.left).map(|v| format!("{}: {}", v["part"].as_str().unwrap_or("?"), v["why"].as_str().unwrap_or("?"))).collect::<Vec<_>>().join("; ")
324}
325
326async fn fill_card(state: &AppState, caller: Option<&Caller>, req: &VaultFillRequest, block_id: &str, agent: &str, reason: &str, card: Option<CardTarget>, picker: Vec<CardTarget>) -> Response {
327    tracing::info!(agent = %agent, block_id = %block_id, entry = %card.as_ref().map(|c| c.fill.id.as_str()).unwrap_or("(the person picks)"), "[vault] a whole-card web form fill was asked for");
328    let named = card.as_ref().map(|c| c.fill.id.as_str()).unwrap_or("<id>");
329    let instead = format!("fill a single field with {named}.<part> (number, exp_month, exp_year, cvc, name, zip)");
330    let CardForm { origin, page, grant_key, fields, names } = match read_form(state, block_id, &req.ref_, &instead).await {
331        Ok(f) => f,
332        Err(response) => return response,
333    };
334    let site = format!("{grant_key} (card form)");
335    let Settled { mut card, always, went_ahead } = match settle(state, caller, req, (block_id, agent, reason), (&origin, &page, &names), (card, picker)).await {
336        Ok(s) => s,
337        Err(response) => return response,
338    };
339    if always {
340        let (store, entry, grant_origin, created) = (state.identity_store.clone(), card.fill.id.clone(), grant_key.clone(), card.fill.created_at);
341        let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&entry, &grant_origin, agentmux_common::time::now_ms(), created)).await;
342    }
343
344    // The card leaves the sealed row only now.
345    let store = state.identity_store.clone();
346    let (entry, created, sealed) = (card.fill.id.clone(), card.fill.created_at, card.sealed.clone());
347    let parts = match tokio::task::spawn_blocking(move || card_target::parts_for_fill(&store, &entry, created, &sealed)).await {
348        Ok(Ok(p)) => p,
349        Ok(Err(e)) => {
350            record(state, block_id, &card.fill, agent, &site, "failed", reason);
351            return err_response(StatusCode::BAD_REQUEST, e);
352        }
353        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
354    };
355    let done = fill_all(state, block_id, &origin, &fields, &parts).await;
356    drop(parts);
357
358    card.fill.what = format!("card ({})", if done.filled.is_empty() { "nothing".to_string() } else { done.filled.join(", ") });
359    if done.filled.is_empty() {
360        record(state, block_id, &card.fill, agent, &site, "failed", reason);
361        let why = why_nothing(&done);
362        return err_response(StatusCode::BAD_REQUEST, format!("nothing was filled: {why}"));
363    }
364    record(state, block_id, &card.fill, agent, &site, "done", reason);
365    let (store, entry) = (state.identity_store.clone(), card.fill.id.clone());
366    let _ = tokio::task::spawn_blocking(move || store.vault_touch(&entry, agentmux_common::time::now_ms())).await;
367    (StatusCode::OK, Json(json!({ "ok": true, "data": answer(&card.fill.id, &origin, &page, &done, went_ahead) }))).into_response()
368}
369
370mod typed;
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use crate::backend::vault::{kinds, FillTarget};
376
377    fn a_card() -> CardTarget {
378        let kind = kinds::kind("card").expect("the card kind");
379        let fill = FillTarget { id: "card-a".into(), kind: kind.name, typed: false, kind_info: kind, label: "A".into(), part: "number", slot: None, what: "card".into(), created_at: 1, version: None };
380        CardTarget { fill, brand: "visa", last_four: "4242".into(), expiry: Some((3, 2027)), expired: false, default: false, sealed: vec![] }
381    }
382
383    #[test]
384    fn a_frame_and_the_page_it_is_on_are_one_site_for_the_grant_and_the_question() {
385        assert_eq!(grant_site("https://shop.example", ""), "https://shop.example", "a field of the page: its origin");
386        assert_eq!(grant_site("https://shop.example", "https://shop.example"), "https://shop.example", "a frame of the page's own site is the page's");
387        assert_eq!(grant_site("https://js.stripe.com", "https://shop.example"), "https://js.stripe.com on https://shop.example");
388        assert_ne!(grant_site("https://js.stripe.com", "https://shop.example"), grant_site("https://js.stripe.com", "https://other.example"), "the provider's frame on another page is another grant");
389        assert_eq!(framed_in("https://js.stripe.com", "https://shop.example"), "https://shop.example");
390        assert_eq!(framed_in("https://shop.example", "https://shop.example"), "");
391        assert_eq!(framed_in("", "https://shop.example"), "");
392        let framed = card_question("a", String::new(), &Question { card: Some(&a_card()), picker: &[], origin: "https://js.stripe.com", page: "https://shop.example", names: &["number"], offer_always: true, why: "x" }, "");
393        assert_eq!((framed.origin.as_str(), framed.page.as_str()), ("https://js.stripe.com", "https://shop.example"));
394    }
395
396    #[test]
397    fn a_card_never_goes_ahead_on_silence_so_the_answer_carries_no_approval_note_unless_one_did() {
398        let done = Outcome { filled: vec!["number"], ..Default::default() };
399        assert!(answer("card-a", "https://shop.example", "", &done, false).get("approval").is_none());
400        assert_eq!(answer("card-a", "https://shop.example", "", &done, true)["approval"], uses::WENT_AHEAD);
401        assert!(!uses::goes_ahead(&card_question("a", String::new(), &Question { card: Some(&a_card()), picker: &[], origin: "https://shop.example", page: "", names: &["number"], offer_always: false, why: "x" }, "")), "silence denies a card");
402    }
403}