Skip to main content

agentmux_srv_core/backend/vault/
card_fill.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a whole-card fill puts in each field of a form
5//! (docs/specs/SPEC_VAULT_CARD_ENTRIES_FULL_CARD_DATA_AND_AUTOFILL_2026_11_08.md §6).
6//!
7//! The host says what a field is (its slot) and how it takes text (a choice, a
8//! length, a placeholder, a pattern); this turns the card's parts into the text that
9//! field takes: an expiry as `MM/YY`, `MM/YYYY` or `MMYY`, a month and a year to
10//! choose or type, a number grouped or plain, a code that is left alone when the
11//! field is shorter than it. Pure functions: the values come in and go out as
12//! `Zeroizing` text, and no reason a part is left empty ever carries one.
13
14use zeroize::Zeroizing;
15
16use super::card;
17use super::seal::Parts;
18
19/// What the host reports about a field it matched to a card slot.
20#[derive(Debug, Clone, Default)]
21pub struct FormField {
22    pub slot: String,
23    /// A `<select>`: the host picks the option the text names.
24    pub select: bool,
25    /// An `<input>`'s `type`, lower-cased (`month` takes `YYYY-MM`).
26    pub input_type: String,
27    pub max_length: Option<usize>,
28    pub placeholder: String,
29    pub pattern: String,
30}
31
32/// What goes in a field.
33pub enum Shaped {
34    /// Typed (set) as it is.
35    Text(Zeroizing<String>),
36    /// A month (`03`) or a year (`2027`) for the host to find among a `<select>`'s options.
37    Choose(Zeroizing<String>),
38    /// Left empty, and why (never a value).
39    Left(String),
40}
41
42/// The card part a slot takes, in the card's own names.
43pub fn part_of_slot(slot: &str) -> Option<&'static str> {
44    Some(match slot {
45        "card-number" => "number",
46        "card-expiry" => "expiry",
47        "card-exp-month" => "exp_month",
48        "card-exp-year" => "exp_year",
49        "card-cvc" => "cvc",
50        "card-name" => "name",
51        "card-zip" => "zip",
52        _ => return None,
53    })
54}
55
56/// What the person reads for a slot's part in the answer and the approval: names only.
57pub fn part_name(slot: &str) -> &'static str {
58    match slot {
59        "card-number" => "number",
60        "card-expiry" | "card-exp-month" | "card-exp-year" => "expiry",
61        "card-cvc" => "security code",
62        "card-name" => "name",
63        "card-zip" => "ZIP",
64        _ => "card detail",
65    }
66}
67
68fn shaped(s: String) -> Shaped {
69    Shaped::Text(Zeroizing::new(s))
70}
71
72fn left(part: &str) -> Shaped {
73    Shaped::Left(format!("the card has no {part} saved"))
74}
75
76/// The text for one field, from the card's parts.
77pub fn shape(field: &FormField, parts: &Parts) -> Shaped {
78    match field.slot.as_str() {
79        "card-number" => number(field, parts),
80        "card-expiry" => expiry(field, parts),
81        "card-exp-month" => month(field, parts),
82        "card-exp-year" => year(field, parts),
83        "card-cvc" => code(field, parts),
84        "card-name" => plain(parts, "name", "holder name"),
85        "card-zip" => plain(parts, "zip", "billing ZIP"),
86        other => Shaped::Left(format!("{other} isn't a card field")),
87    }
88}
89
90fn plain(parts: &Parts, part: &str, what: &str) -> Shaped {
91    match parts.get(part).filter(|v| !v.trim().is_empty()) {
92        Some(v) => shaped(v.to_string()),
93        None => left(what),
94    }
95}
96
97fn number(field: &FormField, parts: &Parts) -> Shaped {
98    let Some(digits) = parts.get("number").and_then(card::normalize_number) else {
99        return left("number");
100    };
101    let grouped = card::group(&digits);
102    // A field that has room for the spaces and shows them in its placeholder (digit groups like
103    // "1234 5678 9012 3456", not words like "Card number") is given them, unless its pattern is digits only.
104    let groups = field.placeholder.split(' ').filter(|g| !g.is_empty() && g.chars().all(|c| c.is_ascii_digit() || matches!(c, '•' | '*' | 'x' | 'X' | '#'))).count();
105    let spaces_allowed = field.pattern.is_empty() || field.pattern.contains(' ') || field.pattern.contains("\\s");
106    let roomy = field.max_length.is_some_and(|m| m >= grouped.chars().count()) && groups >= 2 && spaces_allowed;
107    let text = if roomy { grouped } else { digits };
108    match field.max_length {
109        Some(m) if text.chars().count() > m => Shaped::Left(format!("this field takes {m} characters and the card's number has {}", text.chars().count())),
110        _ => shaped(text),
111    }
112}
113
114/// The year and separator a field's `pattern` asks for, as (long year, no separator), when nothing else says: `\d{2}/\d{4}` is `MM/YYYY`, a bare
115/// `\d{4}` is `MMYY` and a bare `\d{6}` is `MMYYYY`; anything else is the default `MM/YY`.
116fn by_pattern(pattern: &str) -> (bool, bool) {
117    let separated = pattern.contains('/') || pattern.contains("\\-") || pattern.contains(' ');
118    let four = pattern.contains("{4}") && !pattern.contains("{2}{4}") && !pattern.contains(")?");
119    match (four, pattern.contains("{6}"), separated) {
120        (true, _, true) => (true, false),
121        (true, _, false) => (false, true),
122        (false, true, false) => (true, true),
123        _ => (false, false),
124    }
125}
126
127/// How a one-field expiry is written, from what the field says about itself.
128fn expiry_text(field: &FormField, month: u32, year: i32) -> String {
129    // A native month input takes its own format, whatever its placeholder or length say.
130    if field.input_type == "month" {
131        return format!("{year:04}-{}", card::month_text(month));
132    }
133    let placeholder = field.placeholder.to_ascii_uppercase();
134    let pattern = field.pattern.as_str();
135    // What stands between the month and year tokens of a placeholder like "MM / YY"; a placeholder
136    // that is words ("Expiration date", "Exp. date") says nothing about the separator.
137    let between = placeholder.find("MM").zip(placeholder.find("YY")).filter(|(m, y)| m + 2 <= *y).map(|(m, y)| &placeholder[m + 2..y]);
138    let separator = between.and_then(|b| b.chars().find(|c| matches!(c, '/' | '-' | '.')).or_else(|| b.contains(' ').then_some(' ')));
139    // The field's own length decides first (4 is MMYY, 5 MM/YY, 6 MMYYYY, 7 MM/YYYY); without one the
140    // placeholder does ("MMYY" has no separator), and a pattern that asks for four digits.
141    let (long, compact) = match field.max_length {
142        Some(4) => (false, true),
143        Some(5) => (false, false),
144        Some(6) => (true, true),
145        Some(7) => (true, false),
146        _ if between.is_some() || placeholder.contains("YYYY") => (placeholder.contains("YYYY"), between.is_some() && separator.is_none()),
147        _ => by_pattern(pattern),
148    };
149    let y = if long { format!("{year:04}") } else { format!("{:02}", year % 100) };
150    let m = card::month_text(month);
151    if compact {
152        format!("{m}{y}")
153    } else {
154        format!("{m}{}{y}", separator.unwrap_or('/'))
155    }
156}
157
158fn expiry(field: &FormField, parts: &Parts) -> Shaped {
159    match card::expiry_of(parts) {
160        Some((m, y)) => shaped(expiry_text(field, m, y)),
161        None => left("expiry"),
162    }
163}
164
165fn month(field: &FormField, parts: &Parts) -> Shaped {
166    let Some((m, _)) = card::expiry_of(parts) else { return left("expiry") };
167    let text = Zeroizing::new(card::month_text(m));
168    if field.select {
169        Shaped::Choose(text)
170    } else {
171        Shaped::Text(text)
172    }
173}
174
175fn year(field: &FormField, parts: &Parts) -> Shaped {
176    let Some((_, y)) = card::expiry_of(parts) else { return left("expiry") };
177    if field.select {
178        return Shaped::Choose(Zeroizing::new(format!("{y:04}")));
179    }
180    let short = field.max_length == Some(2) || field.placeholder.to_ascii_uppercase() == "YY";
181    shaped(if short { format!("{:02}", y % 100) } else { format!("{y:04}") })
182}
183
184fn code(field: &FormField, parts: &Parts) -> Shaped {
185    let Some(code) = parts.get("cvc").filter(|c| !c.is_empty()) else { return left("security code") };
186    let length = code.chars().count();
187    match field.max_length {
188        Some(m) if m < length => Shaped::Left(format!("this field takes {m} digits and the card's code has {length}")),
189        _ => shaped(code.to_string()),
190    }
191}
192
193#[cfg(test)]
194mod tests;