Skip to main content

agentmux_srv_core/backend/vault/
card_target.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The card a whole-card fill is for, resolved by name before anything is asked
5//! (docs/specs/SPEC_VAULT_CARD_ENTRIES_FULL_CARD_DATA_AND_AUTOFILL_2026_11_08.md §6).
6//!
7//! `Browser` `fill` with `vault: "<card id>"` names the card; `vault: "card"` means the
8//! person's default one. `vault: "<id>.<part>"` is the older one-field fill and is not
9//! resolved here. What is returned is what the person is shown in the approval (the
10//! brand, the last four and the expiry) and nothing the agent could use.
11
12use super::{card, kinds, seal, vaults, FillTarget};
13use crate::backend::storage::store::Store;
14
15/// A card named for a whole-card fill.
16pub struct CardTarget {
17    /// The entry, for the use record and the approval; its `part` is the number.
18    pub fill: FillTarget,
19    pub brand: &'static str,
20    pub last_four: String,
21    /// The expiry month and year, when the card has one.
22    pub expiry: Option<(u32, i32)>,
23    /// Past its month: asks every time, and no "Always" covers it.
24    pub expired: bool,
25    /// The person's default card.
26    pub default: bool,
27    /// The card's sealed bytes as the approval described them: a card changed while the person
28    /// decides is not the card they said yes to.
29    pub sealed: Vec<u8>,
30}
31
32impl CardTarget {
33    /// This card as one line of the person's picker.
34    pub fn choice(&self) -> super::uses::UseChoice {
35        super::uses::UseChoice { id: self.fill.id.clone(), label: self.fill.label.clone(), detail: self.describe(), expired: self.expired, default: self.default }
36    }
37
38    /// What the person reads the card as: "Visa •••• 4242, expires 03/27".
39    pub fn describe(&self) -> String {
40        let brand = card_brand_name(self.brand);
41        let tail = if self.last_four.is_empty() { String::new() } else { format!(" •••• {}", self.last_four) };
42        let when = match self.expiry {
43            Some((m, y)) if self.expired => format!(", expired {}/{y:04}", card::month_text(m)),
44            Some((m, y)) => format!(", expires {}/{:02}", card::month_text(m), y % 100),
45            None => String::new(),
46        };
47        format!("{}{tail}{when}", if brand.is_empty() { "card" } else { brand })
48    }
49}
50
51fn card_brand_name(brand: &str) -> &'static str {
52    match brand {
53        "visa" => "Visa",
54        "mastercard" => "Mastercard",
55        "amex" => "American Express",
56        "discover" => "Discover",
57        "diners" => "Diners Club",
58        "jcb" => "JCB",
59        "unionpay" => "UnionPay",
60        _ => "",
61    }
62}
63
64/// What `vault` names for a whole-card fill.
65pub enum Asked {
66    /// Not a whole card (a part, another kind of entry): the old fill takes it.
67    NotACard,
68    /// A card: the one the agent named, or the person's default.
69    One(Box<CardTarget>),
70    /// `card` with no default: the person picks.
71    Pick,
72}
73
74/// Whether `vault` names a whole card: a card's id with no part, or `card` for the default.
75pub fn card_asked(store: &Store, vault: &str, agent: Option<&str>) -> Result<Asked, String> {
76    let (id, part) = super::slots::split(vault);
77    if part.is_some() {
78        return Ok(Asked::NotACard);
79    }
80    let row = match store.vault_get(id).map_err(|e| e.to_string())? {
81        Some(row) if row.kind != card::KIND => return Ok(Asked::NotACard),
82        Some(row) => row,
83        None if id == card::KIND => match default_card(store, agent)? {
84            Some(row) => row,
85            None if usable_cards(store, agent)?.is_empty() => return Err("you have no card saved: ask the person to add one in the Vault, or to type it (Vault request_value)".to_string()),
86            None => return Ok(Asked::Pick),
87        },
88        None => return Ok(Asked::NotACard),
89    };
90    if !vaults::entry_row_usable(store, &row.vault_id, agent)? {
91        return Err(format!("no Vault entry {id:?}: Vault's list action shows the entries"));
92    }
93    open_row(row).map(|c| Asked::One(Box::new(c)))
94}
95
96/// A card named by its id, among the Vaults the agent may use: what the person picked.
97pub fn card_by_id(store: &Store, id: &str, agent: Option<&str>) -> Result<CardTarget, String> {
98    let row = store.vault_get(id).map_err(|e| e.to_string())?.filter(|r| r.kind == card::KIND);
99    let row = row.ok_or_else(|| format!("no card {id:?}"))?;
100    if !vaults::entry_row_usable(store, &row.vault_id, agent)? {
101        return Err(format!("no card {id:?}"));
102    }
103    open_row(row)
104}
105
106/// Every card among the Vaults the agent may use, for the person's picker: the default first, then the
107/// most recently saved. A card that can't be opened (changed, or sealed with another Vault key) is left out
108/// of the list: it can't be filled, and it must not stop a fill of another card.
109pub fn card_choices(store: &Store, agent: Option<&str>) -> Result<Vec<CardTarget>, String> {
110    let mut rows = usable_cards(store, agent)?;
111    rows.sort_by(|a, b| is_default(b).cmp(&is_default(a)).then(b.updated_at.cmp(&a.updated_at)));
112    Ok(rows.into_iter().filter_map(|row| open_row(row).ok()).collect())
113}
114
115fn usable_cards(store: &Store, agent: Option<&str>) -> Result<Vec<super::VaultRow>, String> {
116    let mut out = Vec::new();
117    for row in store.vault_list().map_err(|e| e.to_string())? {
118        if row.kind == card::KIND && vaults::entry_row_usable(store, &row.vault_id, agent)? {
119            out.push(row);
120        }
121    }
122    Ok(out)
123}
124
125fn is_default(row: &super::VaultRow) -> bool {
126    let fields: std::collections::BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
127    fields.get(card::DEFAULT).map(String::as_str) == Some("yes")
128}
129
130/// A card row opened for what the approval says of it: brand, last four, expiry. The number itself leaves here only as
131/// those and as the sealed bytes the approval was shown for.
132fn open_row(row: super::VaultRow) -> Result<CardTarget, String> {
133    let kind = kinds::kind(card::KIND).ok_or("the card kind is missing")?;
134    let key = seal::key(false)?;
135    let parts = seal::open(&key, &row.id, &row.sealed)?;
136    let number = parts.get("number").and_then(card::normalize_number).unwrap_or_default();
137    let last_four: String = number.chars().rev().take(4).collect::<Vec<_>>().into_iter().rev().collect();
138    let expiry = card::expiry_of(&parts);
139    let expired = expiry.is_some_and(|(m, y)| card::expired(m, y, super::expiry::today()));
140    let default = is_default(&row);
141    let sealed = row.sealed.clone();
142    Ok(CardTarget {
143        brand: card::brand(&number),
144        last_four,
145        expiry,
146        expired,
147        default,
148        sealed,
149        fill: FillTarget {
150            id: row.id,
151            kind: kind.name,
152            typed: false,
153            kind_info: kind,
154            label: row.label,
155            part: "number",
156            slot: None,
157            what: "card".to_string(),
158            created_at: row.created_at,
159            version: None,
160        },
161    })
162}
163
164/// The person's default card among the Vaults the agent may use: the most recently saved if two
165/// say they are (one Vault keeps only one, but two Vaults each can).
166fn default_card(store: &Store, agent: Option<&str>) -> Result<Option<super::VaultRow>, String> {
167    let mut found: Option<super::VaultRow> = None;
168    for row in usable_cards(store, agent)? {
169        if is_default(&row) && found.as_ref().is_none_or(|f| row.updated_at > f.updated_at) {
170            found = Some(row);
171        }
172    }
173    Ok(found)
174}
175
176/// The card's parts for the host to type, opened only once the person has said yes; never
177/// returned to an agent. Refused if the entry was replaced, or its card changed, while they decided.
178pub fn parts_for_fill(store: &Store, id: &str, created_at: i64, sealed: &[u8]) -> Result<seal::Parts, String> {
179    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
180    if row.created_at != created_at {
181        return Err(format!("{} was replaced while the person was deciding: nothing was typed", row.label));
182    }
183    if row.sealed != sealed {
184        return Err(format!("{} was changed while the person was deciding, so it isn't the card they approved: nothing was typed", row.label));
185    }
186    let key = seal::key(false)?;
187    seal::open(&key, &row.id, &row.sealed)
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn target(brand: &'static str, last_four: &str, expiry: Option<(u32, i32)>, expired: bool) -> CardTarget {
195        let kind = kinds::kind(card::KIND).expect("card kind");
196        CardTarget {
197            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 },
198            brand,
199            last_four: last_four.into(),
200            expiry,
201            expired,
202            default: false,
203            sealed: Vec::new(),
204        }
205    }
206
207    #[tokio::test]
208    async fn a_card_changed_while_the_person_decides_is_not_filled() {
209        use super::super::{create, update, EntryChange, NewEntry};
210        seal::use_test_key();
211        let store = crate::test_support::core_parts().mstore;
212        let parts = |n: &str| seal::Parts([("number".to_string(), n.to_string()), ("exp_month".to_string(), "03".to_string()), ("exp_year".to_string(), "2099".to_string())].into());
213        let id = create(&store, NewEntry { kind: "card".into(), label: "Probe".into(), fields: Default::default(), tags: vec![], parts: parts("4111111111111111") }).unwrap();
214        let Asked::One(asked) = card_asked(&store, &id, None).unwrap() else { panic!("a card") };
215        assert_eq!(asked.last_four, "1111");
216        // Unchanged: the fill goes ahead with the card that was shown.
217        assert!(parts_for_fill(&store, &id, asked.fill.created_at, &asked.sealed).is_ok());
218        // The person changes the number while the prompt is open: what was approved is not what is there.
219        update(&store, EntryChange { id: id.clone(), label: "Probe".into(), fields: Default::default(), tags: vec![], parts: parts("5555555555554444"), clear: vec![] }).unwrap();
220        let why = parts_for_fill(&store, &id, asked.fill.created_at, &asked.sealed).err().expect("refused");
221        assert!(why.contains("changed while the person was deciding"), "{why}");
222        assert!(!why.contains("5555") && !why.contains("4111"), "{why}");
223    }
224
225    #[test]
226    fn a_card_is_described_by_its_brand_last_four_and_expiry() {
227        assert_eq!(target("visa", "4242", Some((3, 2027)), false).describe(), "Visa •••• 4242, expires 03/27");
228        assert_eq!(target("amex", "0005", Some((12, 2030)), false).describe(), "American Express •••• 0005, expires 12/30");
229        assert_eq!(target("visa", "4242", Some((3, 2026)), true).describe(), "Visa •••• 4242, expired 03/2026");
230        assert_eq!(target("", "", None, false).describe(), "card");
231    }
232
233    #[tokio::test]
234    async fn card_names_the_default_or_asks_the_person_to_pick_and_lists_the_default_first() {
235        use super::super::{create, NewEntry};
236        seal::use_test_key();
237        let store = crate::test_support::core_parts().mstore;
238        assert!(matches!(card_asked(&store, "card", None), Err(e) if e.contains("no card saved")));
239        let make = |label: &str, number: &str, default: bool| {
240            let fields = if default { [("default".to_string(), "yes".to_string())].into() } else { Default::default() };
241            let parts = seal::Parts([("number", number), ("exp_month", "03"), ("exp_year", "2099")].into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect());
242            create(&store, NewEntry { kind: "card".into(), label: label.into(), fields, tags: vec![], parts }).unwrap()
243        };
244        let plain = make("Plain", "4111111111111111", false);
245        // Cards but no default: the person picks.
246        assert!(matches!(card_asked(&store, "card", None), Ok(Asked::Pick)));
247        let default = make("Default", "5555555555554444", true);
248        let Ok(Asked::One(named)) = card_asked(&store, "card", None) else { panic!("the default") };
249        assert_eq!(named.fill.id, default);
250        let all = card_choices(&store, None).unwrap();
251        assert_eq!(all.iter().map(|c| c.fill.id.as_str()).collect::<Vec<_>>(), [default.as_str(), plain.as_str()], "the default first");
252        assert!(all[0].choice().default && !all[1].choice().default);
253        assert_eq!(all[1].choice().detail, "Visa •••• 1111, expires 03/99");
254        assert!(card_by_id(&store, &plain, None).is_ok());
255        assert!(card_by_id(&store, "nope", None).is_err());
256    }
257
258    #[tokio::test]
259    async fn a_card_that_does_not_open_is_left_out_of_the_choices_and_stops_nothing() {
260        use super::super::{create, NewEntry};
261        seal::use_test_key();
262        let store = crate::test_support::core_parts().mstore;
263        let make = |label: &str, number: &str| {
264            let parts = seal::Parts([("number", number), ("exp_month", "03"), ("exp_year", "2099")].into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect());
265            create(&store, NewEntry { kind: "card".into(), label: label.into(), fields: Default::default(), tags: vec![], parts }).unwrap()
266        };
267        let good = make("Good", "4111111111111111");
268        let bad = make("Bad", "5555555555554444");
269        // Sealed with something else, as a card changed under another Vault key would be.
270        let mut row = store.vault_get(&bad).unwrap().expect("the card");
271        row.sealed = vec![0u8; row.sealed.len().max(32)];
272        assert!(store.vault_update(&row).unwrap());
273        let all = card_choices(&store, None).expect("one card that does not open does not fail the list");
274        assert_eq!(all.iter().map(|c| c.fill.id.as_str()).collect::<Vec<_>>(), [good.as_str()]);
275        assert!(card_by_id(&store, &bad, None).is_err());
276    }
277}