Skip to main content

agentmux_srv_core/backend/vault/
card.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a card entry knows about itself: its brand, whether its number passes
5//! the Luhn check, how its number is grouped, how long its security code is,
6//! and its expiry month and year. Pure functions, no store, no seal.
7//! docs/specs/SPEC_VAULT_CARD_ENTRIES_FULL_CARD_DATA_AND_AUTOFILL_2026_11_08.md ยง4.
8//!
9//! A card's number, expiry month and year, code, name and ZIP are sealed
10//! parts. What the pane and the reminders can read without the key is the
11//! plain `brand` and `default` fields and the `expires` date (the last day of
12//! the expiry month), which [`settle`] keeps in step with the parts on every save.
13
14use std::collections::BTreeMap;
15
16use chrono::{Datelike, NaiveDate};
17use zeroize::Zeroize;
18
19use super::seal::Parts;
20
21/// The kind these functions are for.
22pub const KIND: &str = "card";
23
24/// The plain field that holds the brand (`visa`, `mastercard`, ...), worked out from the number.
25pub const BRAND: &str = "brand";
26/// The plain field that marks the person's default card (`yes`, or absent).
27pub const DEFAULT: &str = "default";
28/// A pre-split expiry, "MM/YY" or "MM/YYYY". Still read; a save writes `exp_month` and `exp_year` instead.
29pub const LEGACY_EXPIRY: &str = "expiry";
30
31/// The brand a number belongs to by its first digits, or an empty string.
32pub fn brand(number: &str) -> &'static str {
33    let digits: String = number.chars().filter(char::is_ascii_digit).collect();
34    let prefix = |n: usize| -> u32 { digits.get(..n).and_then(|p| p.parse().ok()).unwrap_or(0) };
35    let has = |n: usize| digits.len() >= n;
36    if has(4) && (3528..=3589).contains(&prefix(4)) {
37        "jcb"
38    } else if has(2) && matches!(prefix(2), 34 | 37) {
39        "amex"
40    } else if (has(4) && prefix(4) == 6011) || (has(3) && (644..=649).contains(&prefix(3))) || (has(2) && prefix(2) == 65) {
41        "discover"
42    } else if (has(2) && (51..=55).contains(&prefix(2))) || (has(4) && (2221..=2720).contains(&prefix(4))) {
43        "mastercard"
44    } else if (has(3) && (300..=305).contains(&prefix(3))) || (has(2) && matches!(prefix(2), 36 | 38)) {
45        "diners"
46    } else if has(2) && prefix(2) == 62 {
47        "unionpay"
48    } else if digits.starts_with('4') {
49        "visa"
50    } else {
51        ""
52    }
53}
54
55/// A number's digits when it is only digits, spaces and dashes; None for anything else.
56pub fn normalize_number(text: &str) -> Option<String> {
57    let digits: String = text.chars().filter(|c| !matches!(c, ' ' | '-')).collect();
58    (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit())).then_some(digits)
59}
60
61/// Whether the digits of `number` pass the Luhn check.
62pub fn luhn(number: &str) -> bool {
63    let digits: Vec<u32> = number.chars().filter_map(|c| c.to_digit(10)).collect();
64    if digits.len() < 2 {
65        return false;
66    }
67    let sum: u32 = digits
68        .iter()
69        .rev()
70        .enumerate()
71        .map(|(i, d)| if i % 2 == 1 { let x = d * 2; if x > 9 { x - 9 } else { x } } else { *d })
72        .sum();
73    sum % 10 == 0
74}
75
76/// A number grouped for reading: 4-6-5 for American Express, fours for the rest.
77pub fn group(number: &str) -> String {
78    let digits: String = number.chars().filter(char::is_ascii_digit).collect();
79    let sizes: &[usize] = if brand(&digits) == "amex" { &[4, 6, 5] } else { &[4, 4, 4, 4, 4] };
80    let mut out = String::new();
81    let mut rest = digits.as_str();
82    for size in sizes {
83        if rest.is_empty() {
84            break;
85        }
86        let (head, tail) = rest.split_at(rest.len().min(*size));
87        if !out.is_empty() {
88            out.push(' ');
89        }
90        out.push_str(head);
91        rest = tail;
92    }
93    if !rest.is_empty() {
94        out.push(' ');
95        out.push_str(rest);
96    }
97    out
98}
99
100/// How many digits the security code has: four for American Express, three otherwise.
101pub fn cvc_length(brand: &str) -> usize {
102    if brand == "amex" {
103        4
104    } else {
105        3
106    }
107}
108
109fn month_of(text: &str) -> Option<u32> {
110    let m: u32 = text.trim().parse().ok()?;
111    (1..=12).contains(&m).then_some(m)
112}
113
114fn year_of(text: &str) -> Option<i32> {
115    let text = text.trim();
116    let y: i32 = text.parse().ok()?;
117    match text.len() {
118        1 | 2 => Some(2000 + y),
119        4 => (2000..=2099).contains(&y).then_some(y),
120        _ => None,
121    }
122}
123
124/// A month and year from any of "3/27", "03/27", "03/2027", "0327", "032027",
125/// "03-2027" or "2027-03".
126pub fn normalize_expiry(text: &str) -> Option<(u32, i32)> {
127    let text: String = text.chars().filter(|c| !c.is_whitespace()).collect();
128    let (a, b) = match text.split_once(['/', '-', '.']) {
129        Some(pair) => pair,
130        None if matches!(text.len(), 4 | 6) && text.is_ascii() => text.split_at(2),
131        None => return None,
132    };
133    if !a.chars().all(|c| c.is_ascii_digit()) || !b.chars().all(|c| c.is_ascii_digit()) {
134        return None;
135    }
136    if a.len() == 4 {
137        return Some((month_of(b)?, year_of(a)?));
138    }
139    Some((month_of(a)?, year_of(b)?))
140}
141
142/// "03" for March.
143pub fn month_text(month: u32) -> String {
144    format!("{month:02}")
145}
146
147/// The last day of the expiry month: the card works through it.
148pub fn last_day(month: u32, year: i32) -> Option<NaiveDate> {
149    let first_of_next = if month == 12 { NaiveDate::from_ymd_opt(year + 1, 1, 1) } else { NaiveDate::from_ymd_opt(year, month + 1, 1) };
150    first_of_next.and_then(|d| d.pred_opt())
151}
152
153/// Whether a card is past its month: from the first day of the month after.
154pub fn expired(month: u32, year: i32, today: NaiveDate) -> bool {
155    (today.year(), today.month()) > (year, month)
156}
157
158/// The expiry a set of parts holds: its month and year, or the older single
159/// part read as one.
160pub fn expiry_of(parts: &Parts) -> Option<(u32, i32)> {
161    if let (Some(m), Some(y)) = (parts.get("exp_month").and_then(month_of), parts.get("exp_year").and_then(year_of)) {
162        return Some((m, y));
163    }
164    parts.get(LEGACY_EXPIRY).and_then(normalize_expiry)
165}
166
167/// A card part as a fill or a command asks for it. The older `expiry` is read
168/// from the month and year when the card has no such part, as "MM/YY".
169pub fn part_value(parts: &Parts, part: &str) -> Option<String> {
170    if let Some(v) = parts.get(part) {
171        return Some(v.to_string());
172    }
173    if part == LEGACY_EXPIRY {
174        let (m, y) = expiry_of(parts)?;
175        return Some(format!("{}/{:02}", month_text(m), y % 100));
176    }
177    None
178}
179
180fn put(parts: &mut Parts, name: &str, value: String) {
181    if let Some(mut old) = parts.0.insert(name.to_string(), value) {
182        old.zeroize();
183    }
184}
185
186/// Makes a card's parts and plain fields agree, on every save (by the person,
187/// an agent or an import): the number as digits, the expiry as `exp_month` and
188/// `exp_year` (the older `expiry` read into them and dropped), the brand worked
189/// out from the number, `expires` set to the last day of the expiry month for
190/// the reminders, and the default flag kept to `yes`. A month or year that is
191/// not one is refused; a number with anything but digits is left as typed (the
192/// pane warns, the Vault doesn't decide). Any other kind is left alone.
193pub fn settle(kind: &str, fields: &mut BTreeMap<String, String>, parts: &mut Parts) -> Result<(), String> {
194    if kind != KIND {
195        return Ok(());
196    }
197    if let Some(digits) = parts.get("number").and_then(normalize_number) {
198        if parts.get("number") != Some(digits.as_str()) {
199            put(parts, "number", digits);
200        }
201    }
202    let month = match parts.get("exp_month") {
203        Some(m) => Some(month_of(m).ok_or("the expiry month is 1 to 12")?),
204        None => None,
205    };
206    let year = match parts.get("exp_year") {
207        Some(y) => Some(year_of(y).ok_or("the expiry year is four digits, like 2030, or two")?),
208        None => None,
209    };
210    let older = if month.is_none() && year.is_none() { parts.get(LEGACY_EXPIRY).and_then(normalize_expiry) } else { None };
211    let (month, year) = (month.or(older.map(|o| o.0)), year.or(older.map(|o| o.1)));
212    if let Some(m) = month {
213        put(parts, "exp_month", month_text(m));
214    }
215    if let Some(y) = year {
216        put(parts, "exp_year", y.to_string());
217    }
218    fields.remove(super::expiry::FIELD);
219    if let (Some(m), Some(y)) = (month, year) {
220        if let Some(mut gone) = parts.0.remove(LEGACY_EXPIRY) {
221            gone.zeroize();
222        }
223        if let Some(date) = last_day(m, y) {
224            fields.insert(super::expiry::FIELD.to_string(), date.to_string());
225        }
226    }
227    if let Some(zip) = parts.get("zip").map(str::trim).filter(|z| Some(*z) != parts.get("zip")).map(str::to_string) {
228        put(parts, "zip", zip);
229    }
230    match parts.get("number").map(brand).filter(|b| !b.is_empty()) {
231        Some(b) => {
232            fields.insert(BRAND.to_string(), b.to_string());
233        }
234        None => {
235            fields.remove(BRAND);
236        }
237    }
238    if fields.get(DEFAULT).is_some_and(|v| v != "yes") {
239        fields.remove(DEFAULT);
240    }
241    Ok(())
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    fn parts(list: &[(&str, &str)]) -> Parts {
249        Parts(list.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())
250    }
251
252    #[test]
253    fn brands_follow_the_first_digits() {
254        for (number, want) in [
255            ("4111111111111111", "visa"),
256            ("5555555555554444", "mastercard"),
257            ("2221000000000009", "mastercard"),
258            ("2720999999999996", "mastercard"),
259            ("378282246310005", "amex"),
260            ("341111111111111", "amex"),
261            ("6011111111111117", "discover"),
262            ("6445644564456445", "discover"),
263            ("6500000000000002", "discover"),
264            ("30569309025904", "diners"),
265            ("36227206271667", "diners"),
266            ("38520000023237", "diners"),
267            ("3530111333300000", "jcb"),
268            ("3589000000000000", "jcb"),
269            ("6200000000000005", "unionpay"),
270            ("9999999999999999", ""),
271            ("", ""),
272            ("2", ""),
273        ] {
274            assert_eq!(brand(number), want, "{number}");
275        }
276        assert_eq!(brand("4111 1111 1111 1111"), "visa", "spaces are no matter");
277    }
278
279    #[test]
280    fn luhn_accepts_the_test_numbers_and_refuses_one_digit_off() {
281        for ok in ["4111111111111111", "5555555555554444", "378282246310005", "6011111111111117", "30569309025904", "3530111333300000"] {
282            assert!(luhn(ok), "{ok}");
283        }
284        for bad in ["4111111111111112", "5555555555554445", "378282246310006", "1234567890123456", "7", ""] {
285            assert!(!luhn(bad), "{bad}");
286        }
287        assert!(luhn("4111 1111 1111 1111"));
288    }
289
290    #[test]
291    fn numbers_group_by_brand() {
292        assert_eq!(group("4111111111111111"), "4111 1111 1111 1111");
293        assert_eq!(group("378282246310005"), "3782 822463 10005");
294        assert_eq!(group("4111"), "4111");
295        assert_eq!(group("41111"), "4111 1");
296        assert_eq!(group(""), "");
297        assert_eq!(group("4111-1111-1111-1111"), "4111 1111 1111 1111");
298    }
299
300    #[test]
301    fn a_number_is_digits_or_left_alone() {
302        assert_eq!(normalize_number("4111 1111-1111 1111").as_deref(), Some("4111111111111111"));
303        assert_eq!(normalize_number("4111x"), None);
304        assert_eq!(normalize_number("  "), None);
305    }
306
307    #[test]
308    fn the_code_is_four_digits_for_amex_only() {
309        assert_eq!(cvc_length("amex"), 4);
310        for b in ["visa", "mastercard", "discover", "diners", "jcb", "unionpay", ""] {
311            assert_eq!(cvc_length(b), 3, "{b}");
312        }
313    }
314
315    #[test]
316    fn an_expiry_is_read_in_every_spelling() {
317        for text in ["3/27", "03/27", "03/2027", "0327", "032027", "03-2027", "03 / 27", "3.27", "2027-03"] {
318            assert_eq!(normalize_expiry(text), Some((3, 2027)), "{text}");
319        }
320        for text in ["13/27", "00/27", "03/1999", "soon", "", "3", "03/", "0327x", "03/20277"] {
321            assert_eq!(normalize_expiry(text), None, "{text}");
322        }
323    }
324
325    #[test]
326    fn a_card_expires_after_the_last_day_of_its_month() {
327        let d = |y, m, day| NaiveDate::from_ymd_opt(y, m, day).unwrap();
328        assert_eq!(last_day(2, 2028), Some(d(2028, 2, 29)));
329        assert_eq!(last_day(12, 2027), Some(d(2027, 12, 31)));
330        assert!(!expired(3, 2027, d(2027, 3, 31)));
331        assert!(expired(3, 2027, d(2027, 4, 1)));
332        assert!(expired(12, 2026, d(2027, 1, 1)));
333        assert!(!expired(1, 2030, d(2026, 11, 10)));
334    }
335
336    #[test]
337    fn the_older_expiry_is_read_as_a_month_and_year() {
338        let old = parts(&[("number", "4111111111111111"), ("expiry", "03/2027")]);
339        assert_eq!(expiry_of(&old), Some((3, 2027)));
340        assert_eq!(part_value(&old, "expiry").as_deref(), Some("03/2027"));
341        let new = parts(&[("exp_month", "03"), ("exp_year", "2027")]);
342        assert_eq!(expiry_of(&new), Some((3, 2027)));
343        assert_eq!(part_value(&new, "expiry").as_deref(), Some("03/27"), "the older part is derived as MM/YY");
344        assert_eq!(part_value(&new, "cvc"), None);
345        assert_eq!(expiry_of(&parts(&[("number", "4")])), None);
346    }
347
348    #[test]
349    fn a_save_makes_the_parts_and_fields_agree() {
350        let mut fields = BTreeMap::from([("brand".to_string(), "amex".to_string()), ("expires".to_string(), "1999-01-01".to_string())]);
351        let mut p = parts(&[("number", "4111 1111 1111 1111"), ("exp_month", "3"), ("exp_year", "27"), ("zip", " 94107 ")]);
352        settle("card", &mut fields, &mut p).unwrap();
353        assert_eq!(p.get("number"), Some("4111111111111111"));
354        assert_eq!((p.get("exp_month"), p.get("exp_year")), (Some("03"), Some("2027")));
355        assert_eq!(p.get("zip"), Some("94107"));
356        assert_eq!(fields.get("brand").map(String::as_str), Some("visa"), "the brand follows the number, not what was sent");
357        assert_eq!(fields.get("expires").map(String::as_str), Some("2027-03-31"));
358    }
359
360    #[test]
361    fn a_save_reads_the_older_expiry_into_the_new_parts_and_drops_it() {
362        let mut fields = BTreeMap::new();
363        let mut p = parts(&[("number", "378282246310005"), ("expiry", "11/2029"), ("cvc", "1234")]);
364        settle("card", &mut fields, &mut p).unwrap();
365        assert_eq!((p.get("exp_month"), p.get("exp_year"), p.get("expiry")), (Some("11"), Some("2029"), None));
366        assert_eq!(fields.get("brand").map(String::as_str), Some("amex"));
367        assert_eq!(fields.get("expires").map(String::as_str), Some("2029-11-30"));
368        assert_eq!(p.get("cvc"), Some("1234"));
369    }
370
371    #[test]
372    fn an_expiry_nobody_can_read_stays_as_it_was() {
373        let mut fields = BTreeMap::from([("expires".to_string(), "2030-01-31".to_string())]);
374        let mut p = parts(&[("number", "4111111111111111"), ("expiry", "someday")]);
375        settle("card", &mut fields, &mut p).unwrap();
376        assert_eq!(p.get("expiry"), Some("someday"));
377        assert_eq!(p.get("exp_month"), None);
378        assert!(!fields.contains_key("expires"), "a date the parts don't give is not kept");
379    }
380
381    #[test]
382    fn a_bad_month_or_year_is_refused() {
383        for (m, y) in [("13", "2030"), ("0", "2030"), ("x", "2030"), ("3", "1999"), ("3", "20300")] {
384            let mut p = parts(&[("number", "4111111111111111"), ("exp_month", m), ("exp_year", y)]);
385            assert!(settle("card", &mut BTreeMap::new(), &mut p).is_err(), "{m}/{y}");
386        }
387    }
388
389    #[test]
390    fn a_number_that_is_not_digits_is_kept_and_has_no_brand() {
391        let mut fields = BTreeMap::from([("brand".to_string(), "visa".to_string())]);
392        let mut p = parts(&[("number", "GIFT-ABCD-1234")]);
393        settle("card", &mut fields, &mut p).unwrap();
394        assert_eq!(p.get("number"), Some("GIFT-ABCD-1234"));
395        assert!(!fields.contains_key("brand"));
396    }
397
398    #[test]
399    fn only_yes_marks_the_default_and_other_kinds_are_left_alone() {
400        let mut fields = BTreeMap::from([("default".to_string(), "true".to_string())]);
401        settle("card", &mut fields, &mut parts(&[("number", "4111111111111111")])).unwrap();
402        assert!(!fields.contains_key("default"));
403        let mut fields = BTreeMap::from([("default".to_string(), "yes".to_string())]);
404        settle("card", &mut fields, &mut parts(&[("number", "4111111111111111")])).unwrap();
405        assert_eq!(fields.get("default").map(String::as_str), Some("yes"));
406        let mut other = BTreeMap::from([("expires".to_string(), "2030-01-01".to_string())]);
407        settle("api-key", &mut other, &mut parts(&[("value", "k")])).unwrap();
408        assert_eq!(other.len(), 1);
409    }
410}