Skip to main content

agentmux_common/
pii_mask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Hides what looks like a payment card, an ID number or a one-time code in text an agent is about to
5//! read from a web page (the Browser tool's snapshot, find, wait, log and every other answer).
6//!
7//! The Browser tool already refuses to read a password, card or taxpayer-number *field* (the DOM
8//! facts: type, autocomplete, name, label). This is the second line: it works on the *text*, by
9//! shape, so a number a page echoes in plain copy, or one in a field the markup doesn't name, doesn't
10//! reach the agent, its transcript or the pane's Log either. It is a mistake guard, not a sandbox: a
11//! page can always write a number in a way no pattern knows (digits spelled out, split across
12//! elements). It errs toward hiding.
13//!
14//! What it hides:
15//! - a payment card number: 13–19 digits (single spaces or dashes between groups allowed) that pass
16//!   the Luhn check and start like a real card network;
17//! - a U.S. Social Security or taxpayer number written `123-45-6789` or `123 45 6789`;
18//! - an IBAN that passes its mod-97 check;
19//! - the digits after a label that says what they are: a card security code (`CVV: 123`), a
20//!   one-time or verification code, a bank account or routing number, an SSN or taxpayer ID;
21//! - with [`mask_short_text`], credential-prefixed tokens and private keys (`ghp_…`, `sk-…`,
22//!   `-----BEGIN … PRIVATE KEY-----`), through [`crate::redact`].
23//!
24//! Manual scanning, like `redact.rs`: nothing in this workspace depends on `regex`. [`mask_text`] is
25//! linear in the length of the text, so a page of digits can't make it slow.
26
27use crate::redact;
28
29pub const CARD: &str = "[card number hidden]";
30pub const ID_NUMBER: &str = "[ID number hidden]";
31pub const CODE: &str = "[code hidden]";
32pub const ACCOUNT: &str = "[account number hidden]";
33
34/// `text` with the numbers above hidden. Text with none of them comes back unchanged. Linear in the
35/// length of the text, so it is safe on a whole page.
36pub fn mask_text(text: &str) -> String {
37    if !text.bytes().any(|b| b.is_ascii_digit()) {
38        return text.to_string();
39    }
40    let out = mask_labelled(text);
41    let out = mask_iban(&out);
42    mask_runs(&out)
43}
44
45/// [`mask_text`], and credential-prefixed tokens and private keys too. Linear in the length of the
46/// text.
47pub fn mask_short_text(text: &str) -> String {
48    mask_text(&redact::redact_token_shapes(text))
49}
50
51/// The first `max_chars` characters of `text` with everything above hidden, for a caller that shows
52/// only the start of a long string. The whole text is masked first and cut after, so no number or
53/// token that straddles the cut can show its first characters.
54pub fn mask_bounded(text: &str, max_chars: usize) -> String {
55    mask_short_text(text).chars().take(max_chars).collect()
56}
57
58fn luhn(digits: &[u8]) -> bool {
59    let mut total = 0u32;
60    for (i, d) in digits.iter().rev().enumerate() {
61        let mut n = u32::from(*d);
62        if i % 2 == 1 {
63            n *= 2;
64            if n > 9 {
65                n -= 9;
66            }
67        }
68        total += n;
69    }
70    total.is_multiple_of(10)
71}
72
73/// Does a run of digits start like a card network's numbers (Visa, Mastercard, American Express,
74/// Discover, JCB, Diners Club, UnionPay)? Keeps a 13-digit timestamp or an order number that
75/// happens to pass Luhn from being hidden.
76fn card_network(d: &[u8]) -> bool {
77    let n = d.len();
78    let p2 = u32::from(d[0]) * 10 + u32::from(d[1]);
79    let p3 = p2 * 10 + u32::from(d[2]);
80    let p4 = p3 * 10 + u32::from(d.get(3).copied().unwrap_or(0));
81    match n {
82        13 => d[0] == 4,
83        14 => matches!(p2, 36 | 38) || (300..=305).contains(&p3),
84        15 => matches!(p2, 34 | 37) || p4 == 2131 || p4 == 1800,
85        16 => d[0] == 4 || (51..=55).contains(&p2) || (2221..=2720).contains(&p4) || p4 == 6011 || p2 == 65 || (3528..=3589).contains(&p4) || p2 == 62,
86        17..=19 => d[0] == 4 || p2 == 62 || p4 == 6011 || p2 == 65,
87        _ => false,
88    }
89}
90
91/// The run of digits that starts at `start`, as the byte ranges of its groups (`4111`, `1111`, …). A
92/// single space or dash joins two groups, and only when a digit follows it. Also the run's end.
93fn digit_groups(bytes: &[u8], start: usize) -> (usize, Vec<(usize, usize)>) {
94    let mut groups: Vec<(usize, usize)> = Vec::new();
95    let mut end = start;
96    let mut i = start;
97    let mut group_start = start;
98    while i < bytes.len() {
99        let b = bytes[i];
100        if b.is_ascii_digit() {
101            end = i + 1;
102            i += 1;
103        } else if (b == b' ' || b == b'-') && end == i && bytes.get(i + 1).is_some_and(u8::is_ascii_digit) {
104            groups.push((group_start, end));
105            i += 1;
106            group_start = i;
107        } else {
108            break;
109        }
110    }
111    groups.push((group_start, end));
112    (end, groups)
113}
114
115/// Hides card numbers and SSNs wherever they stand in the text. Every window of digit groups is
116/// tried, so a card number is found inside a longer run (`4111 1111 1111 1111 123`, or after another
117/// number), and windows that overlap are merged before anything is replaced, so the whole span
118/// goes: `Order 40008 4111 1111 1111 1111` hides the order number with the card rather than leave
119/// the last eight digits of the card showing.
120fn mask_runs(text: &str) -> String {
121    let bytes = text.as_bytes();
122    // (start, end, what it says) of each window to hide.
123    let mut spans: Vec<(usize, usize, &str)> = Vec::new();
124    let mut i = 0;
125    while i < bytes.len() {
126        // A run starts at a digit that isn't the tail of a longer number.
127        if !bytes[i].is_ascii_digit() || (i > 0 && bytes[i - 1].is_ascii_digit()) {
128            i += 1;
129            continue;
130        }
131        let (run_end, groups) = digit_groups(bytes, i);
132        let mut digits: Vec<u8> = Vec::with_capacity(20);
133        for g in 0..groups.len() {
134            digits.clear();
135            for k in g..groups.len() {
136                digits.extend(bytes[groups[k].0..groups[k].1].iter().map(|b| b - b'0'));
137                if digits.len() > 19 {
138                    break;
139                }
140                // The cheap prefix test first: Luhn only runs on what starts like a card.
141                if digits.len() >= 13 && card_network(&digits) && luhn(&digits) && digits.iter().any(|d| *d != digits[0]) {
142                    spans.push((groups[g].0, groups[k].1, CARD));
143                } else if k == g + 2 && is_ssn_shape(&groups[g..=k]) {
144                    spans.push((groups[g].0, groups[k].1, ID_NUMBER));
145                }
146            }
147        }
148        i = run_end.max(i + 1);
149    }
150    if spans.is_empty() {
151        return text.to_string();
152    }
153    spans.sort_by_key(|s| (s.0, std::cmp::Reverse(s.1)));
154    // Merge the overlapping ones: a card number in the span makes it a card.
155    let mut merged: Vec<(usize, usize, &str)> = Vec::new();
156    for (start, end, label) in spans {
157        match merged.last_mut() {
158            Some(last) if start < last.1 => {
159                last.1 = last.1.max(end);
160                if label == CARD {
161                    last.2 = CARD;
162                }
163            }
164            _ => merged.push((start, end, label)),
165        }
166    }
167    let mut out = String::with_capacity(text.len());
168    let mut copied = 0;
169    for (start, end, label) in merged {
170        out.push_str(&text[copied..start]);
171        out.push_str(label);
172        copied = end;
173    }
174    out.push_str(&text[copied..]);
175    out
176}
177
178/// Three groups of 3, 2 and 4 digits: `123-45-6789`.
179fn is_ssn_shape(groups: &[(usize, usize)]) -> bool {
180    groups.len() == 3 && groups[0].1 - groups[0].0 == 3 && groups[1].1 - groups[1].0 == 2 && groups[2].1 - groups[2].0 == 4
181}
182
183/// Labels that say the digits after them are a secret, with the digits they take: (label words,
184/// fewest digits, most digits, what the hidden text says).
185const LABELS: &[(&[&str], usize, usize, &str)] = &[
186    (&["cvv2", "cvv", "cvc2", "cvc", "csc", "cid", "security code", "card verification", "card code"], 3, 4, CODE),
187    (
188        &[
189            "one-time code",
190            "one time code",
191            "one-time password",
192            "one time password",
193            "verification code",
194            "security code",
195            "passcode",
196            "otp",
197            "2fa code",
198            "auth code",
199            "authentication code",
200            "login code",
201            "sms code",
202        ],
203        4,
204        8,
205        CODE,
206    ),
207    (&["account number", "account no", "acct number", "acct no", "account #", "acct #", "routing number", "routing no", "routing #", "aba number", "aba"], 6, 17, ACCOUNT),
208    (&["social security number", "social security no", "social security", "ssn", "taxpayer id", "taxpayer identification number", "tin", "itin"], 9, 9, ID_NUMBER),
209];
210
211/// Hides the digits that follow a word saying what they are: `CVV: 123`, `your verification code is
212/// 482913`, `Routing number 021000021`.
213fn mask_labelled(text: &str) -> String {
214    let lower = text.to_ascii_lowercase();
215    let bytes = text.as_bytes();
216    // (start, end, replacement) of the digits to hide.
217    let mut hits: Vec<(usize, usize, &str)> = Vec::new();
218    for (labels, min, max, shown) in LABELS {
219        for label in *labels {
220            let mut from = 0;
221            while let Some(found) = lower[from..].find(label) {
222                let at = from + found;
223                let after = at + label.len();
224                from = after;
225                // A whole word: not the middle of `ravioli` or `Tinder`.
226                let word_before = at > 0 && bytes[at - 1].is_ascii_alphanumeric();
227                let word_after = after < bytes.len() && bytes[after].is_ascii_alphanumeric();
228                if word_before || word_after {
229                    continue;
230                }
231                // Skip `:`, `=`, `#`, quotes and spaces, and a short `is`, `was` or `no.` between the label and the digits.
232                let mut j = after;
233                loop {
234                    while j < bytes.len() && matches!(bytes[j], b' ' | b':' | b'=' | b'#' | b'"' | b'\'' | b'\t' | b'\n' | b'(' | b'*' | b'.') {
235                        j += 1;
236                    }
237                    let rest = &lower[j..];
238                    let word = ["is", "was", "number", "no.", "no", "code"].into_iter().find(|w| rest.starts_with(*w) && !rest.as_bytes().get(w.len()).is_some_and(u8::is_ascii_alphanumeric));
239                    match word {
240                        Some(w) => j += w.len(),
241                        None => break,
242                    }
243                }
244                if j >= bytes.len() || !bytes[j].is_ascii_digit() {
245                    continue;
246                }
247                // The longest start of the run, by whole groups, that has as many digits as the
248                // label takes: `CVV: 123 12/29` is the code `123`, not a run of five digits.
249                let (_, groups) = digit_groups(bytes, j);
250                let mut taken = 0;
251                let mut best: Option<usize> = None;
252                for (_, (s, e)) in groups.iter().enumerate() {
253                    taken += e - s;
254                    if taken > *max {
255                        break;
256                    }
257                    if taken >= *min {
258                        best = Some(*e);
259                    }
260                }
261                let Some(end) = best else { continue };
262                hits.push((j, end, shown));
263            }
264        }
265    }
266    if hits.is_empty() {
267        return text.to_string();
268    }
269    // The longest match first where several labels take the same start (`Security code` is a card's
270    // 3 or 4 digits and a one-time code's 4 to 8).
271    hits.sort_by_key(|h| (h.0, std::cmp::Reverse(h.1)));
272    let mut out = String::with_capacity(text.len());
273    let mut copied = 0;
274    for (start, end, shown) in hits {
275        if start < copied {
276            continue;
277        }
278        out.push_str(&text[copied..start]);
279        out.push_str(shown);
280        copied = end;
281    }
282    out.push_str(&text[copied..]);
283    out
284}
285
286/// Hides an IBAN: two letters, two check digits and up to 30 letters or digits (groups of four may
287/// be spaced), when its mod-97 check passes.
288fn mask_iban(text: &str) -> String {
289    let bytes = text.as_bytes();
290    if bytes.len() < 15 {
291        return text.to_string();
292    }
293    let mut out = String::with_capacity(text.len());
294    let mut copied = 0;
295    let mut i = 0;
296    while i + 4 <= bytes.len() {
297        let starts = bytes[i].is_ascii_uppercase()
298            && bytes[i + 1].is_ascii_uppercase()
299            && bytes[i + 2].is_ascii_digit()
300            && bytes[i + 3].is_ascii_digit()
301            && (i == 0 || !bytes[i - 1].is_ascii_alphanumeric());
302        if !starts {
303            i += 1;
304            continue;
305        }
306        // Letters and digits in words joined by single spaces, up to 34 characters of the number
307        // itself: the longest start of them that passes the check is the IBAN.
308        let mut compact: Vec<u8> = Vec::new();
309        // (end offset, compact length) after each whole word.
310        let mut stops: Vec<(usize, usize)> = Vec::new();
311        let mut k = i;
312        while k < bytes.len() && compact.len() < 34 {
313            if bytes[k].is_ascii_alphanumeric() {
314                compact.push(bytes[k].to_ascii_uppercase());
315                k += 1;
316                if k >= bytes.len() || !bytes[k].is_ascii_alphanumeric() {
317                    stops.push((k, compact.len()));
318                }
319            } else if bytes[k] == b' ' && bytes.get(k + 1).is_some_and(u8::is_ascii_alphanumeric) {
320                k += 1;
321            } else {
322                break;
323            }
324        }
325        let found = stops.iter().rev().find(|(_, n)| (15..=34).contains(n) && iban_ok(&compact[..*n]));
326        if let Some(&(end, _)) = found {
327            out.push_str(&text[copied..i]);
328            out.push_str(ACCOUNT);
329            copied = end;
330            i = end;
331        } else {
332            i += 1;
333        }
334    }
335    out.push_str(&text[copied..]);
336    out
337}
338
339/// ISO 7064 mod 97-10: move the first four characters to the end, letters become 10–35, and the
340/// number mod 97 is 1.
341fn iban_ok(compact: &[u8]) -> bool {
342    let mut rem: u32 = 0;
343    for &c in compact[4..].iter().chain(compact[..4].iter()) {
344        let v = if c.is_ascii_digit() { u32::from(c - b'0') } else { u32::from(c - b'A') + 10 };
345        rem = if v >= 10 { (rem * 100 + v) % 97 } else { (rem * 10 + v) % 97 };
346    }
347    rem == 1
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn card_numbers_are_hidden_however_they_are_spaced() {
356        for card in ["4111111111111111", "4111 1111 1111 1111", "4111-1111-1111-1111", "5555 5555 5555 4444", "3782 822463 10005", "6011111111111117", "4000056655665556"] {
357            let masked = mask_text(&format!("Card number {card} expires 12/29"));
358            assert!(masked.contains(CARD), "{card}: {masked}");
359            assert!(!masked.contains(&card[..4]), "{card}: {masked}");
360            assert!(masked.ends_with("expires 12/29"), "{masked}");
361        }
362    }
363
364    #[test]
365    fn a_card_number_followed_by_its_code_is_still_found() {
366        assert_eq!(mask_text("4111 1111 1111 1111 123"), format!("{CARD} 123"));
367        assert_eq!(mask_text("25 4111 1111 1111 1111"), format!("25 {CARD}"));
368    }
369
370    #[test]
371    fn a_card_after_another_number_is_hidden_whole() {
372        for text in ["Order 40008 4111 1111 1111 1111", "Ref 12345 4111-1111-1111-1111 done"] {
373            let masked = mask_text(text);
374            assert!(!masked.contains("1111"), "{masked}");
375            assert!(masked.contains(CARD), "{masked}");
376        }
377        assert_eq!(mask_text("Paid 4111 1111 1111 1111 and 5555 5555 5555 4444."), format!("Paid {CARD} and {CARD}."));
378    }
379
380    #[test]
381    fn digits_that_are_not_a_card_are_left_alone() {
382        for text in [
383            "Order 1792806660525 shipped",
384            "Call 555-123-4567 or (555) 123 4567",
385            "Total $1,234.56 on 2026-10-23",
386            "Tracking 1234567890123456",
387            "Invoice 12345678",
388            "Version 1.2.3.4",
389            "No digits here at all",
390            "",
391        ] {
392            assert_eq!(mask_text(text), text);
393        }
394        // Passes Luhn but starts like no card network.
395        assert_eq!(mask_text("id 1000000000000008"), "id 1000000000000008");
396    }
397
398    #[test]
399    fn a_social_security_number_is_hidden_with_dashes_or_spaces() {
400        assert_eq!(mask_text("SSN on file: 123-45-6789."), format!("SSN on file: {ID_NUMBER}."));
401        assert_eq!(mask_text("123 45 6789"), ID_NUMBER);
402        // A longer chain of groups, or a date, is something else.
403        assert_eq!(mask_text("12-34-56-78-90"), "12-34-56-78-90");
404        assert_eq!(mask_text("2026-10-23"), "2026-10-23");
405    }
406
407    #[test]
408    fn a_label_hides_the_digits_after_it() {
409        assert_eq!(mask_text("CVV: 123"), format!("CVV: {CODE}"));
410        assert_eq!(mask_text("Security code 4321 on the back"), format!("Security code {CODE} on the back"));
411        assert_eq!(mask_text("Your verification code is 482913. Don't share it."), format!("Your verification code is {CODE}. Don't share it."));
412        assert_eq!(mask_text("OTP=998877"), format!("OTP={CODE}"));
413        assert_eq!(mask_text("Routing number 021000021"), format!("Routing number {ACCOUNT}"));
414        assert_eq!(mask_text("Account no. 000123456789"), format!("Account no. {ACCOUNT}"));
415        assert_eq!(mask_text("Social Security Number: 123456789"), format!("Social Security Number: {ID_NUMBER}"));
416        assert_eq!(mask_text("TIN 12-3456789"), format!("TIN {ID_NUMBER}"));
417        // A label with no number after it, or the wrong count of digits, hides nothing.
418        assert_eq!(mask_text("Enter your CVV"), "Enter your CVV");
419        assert_eq!(mask_text("cvv 12"), "cvv 12");
420        // Part of another word is not the label.
421        assert_eq!(mask_text("spinach 12345"), "spinach 12345");
422        assert_eq!(mask_text("Tinder 123456789"), "Tinder 123456789");
423    }
424
425    #[test]
426    fn an_iban_is_hidden_and_a_look_alike_is_not() {
427        assert_eq!(mask_text("Pay to GB82 WEST 1234 5698 7654 32 today"), format!("Pay to {ACCOUNT} today"));
428        assert_eq!(mask_text("DE89370400440532013000"), ACCOUNT);
429        assert_eq!(mask_text("GB82 WEST 1234 5698 7654 33"), "GB82 WEST 1234 5698 7654 33", "a wrong check digit");
430        assert_eq!(mask_text("AB12 is a code"), "AB12 is a code");
431    }
432
433    #[test]
434    fn short_text_also_loses_tokens_and_private_keys() {
435        let masked = mask_short_text(concat!("token ghp", "_abcdefghijklmnopqrstuvwxyz0123456789 end"));
436        assert!(!masked.contains("ghp_abcdef"), "{masked}");
437        // Built in pieces, so the file doesn't hold a key block that a secret scanner would flag.
438        let dashes = "-----";
439        let key = format!("{dashes}BEGIN RSA PRIVATE KEY{dashes}\nMIIEow\n{dashes}END RSA PRIVATE KEY{dashes}");
440        assert!(!mask_short_text(&key).contains("MIIEow"));
441        // mask_text alone leaves them: it is for whole pages.
442        assert_eq!(mask_text("ghp_abcdefghijklmnopqrstuvwxyz"), "ghp_abcdefghijklmnopqrstuvwxyz");
443        // A prefix in the middle of a word is not a token: ordinary page text comes back whole.
444        for text in ["disk-usage-report-weekly", "https://example.test/risk-assessment-for-the-quarter", "tasks-and-asks-for-next-year-planning", concat!("AKI", "AIOSFODNN7EXAMPLE is shown")] {
445            if text.starts_with("AKIA") {
446                continue;
447            }
448            assert_eq!(mask_short_text(text), text);
449        }
450        assert!(!mask_short_text(concat!("key=AKI", "AIOSFODNN7EXAMPLE")).contains("AKIAIOSFODNN7"));
451        assert!(!mask_short_text("see https://x.test/ghp_abcdefghijklmnopqrstuvwxyz0123").contains("ghp_abcdef"));
452    }
453
454    #[test]
455    fn a_number_across_the_cut_is_hidden_even_after_a_token_shrinks_the_text() {
456        // A token before the cut shrinks when redacted, which moves a later number across the cut.
457        let text = format!("ghp_{} {} 4111111111111111", "a".repeat(300), "x".repeat(90));
458        let shown = mask_bounded(&text, 400);
459        assert!(!shown.contains("4111"), "{shown}");
460        assert!(shown.contains(CARD) || shown.chars().count() <= 400, "{shown}");
461        // Short text is returned in full.
462        assert_eq!(mask_bounded("plain words", 400), "plain words");
463    }
464
465    #[test]
466    fn a_labelled_secret_followed_by_other_numbers_is_still_hidden() {
467        assert_eq!(mask_text("CVV: 123 12/29"), format!("CVV: {CODE} 12/29"));
468        assert_eq!(mask_text("Your verification code is 482913 2026-10-24"), format!("Your verification code is {CODE} 2026-10-24"));
469        assert_eq!(mask_text("SSN 123-45-6789 4 dependants"), format!("SSN {ID_NUMBER} 4 dependants"));
470        assert_eq!(mask_text("Routing number 021000021 account number 12345678"), format!("Routing number {ACCOUNT} account number {ACCOUNT}"));
471    }
472
473    #[test]
474    fn where_two_labels_match_the_longer_secret_wins() {
475        assert_eq!(mask_text("Security code: 123 456"), format!("Security code: {CODE}"));
476        assert_eq!(mask_text("Security code: 123"), format!("Security code: {CODE}"));
477        assert_eq!(mask_text("Security code 4321 on the back"), format!("Security code {CODE} on the back"));
478    }
479
480    #[test]
481    fn a_token_that_crosses_the_cut_never_shows_its_prefix() {
482        let text = format!("ghp_{} ghp_abcdefghijklmnopqrstuv", "a".repeat(1980));
483        let shown = mask_bounded(&text, 2000);
484        assert!(!shown.contains("ghp_"), "{shown}");
485        assert_eq!(mask_bounded(&format!("{} sk-abcdefghijklmnopqrstuvwxyz", "word ".repeat(10)), 60).contains("sk-"), false);
486    }
487
488    #[test]
489    fn masking_is_idempotent_and_keeps_other_text_and_unicode() {
490        let text = "Café — total 4111 1111 1111 1111 — ñ ✓ CVV 123";
491        let once = mask_text(text);
492        assert_eq!(mask_text(&once), once);
493        assert!(once.starts_with("Café — total ") && once.contains("ñ ✓"), "{once}");
494    }
495
496    #[test]
497    fn a_page_of_digits_is_scanned_in_linear_time() {
498        let digits = "1234567890".repeat(200_000);
499        let spaced = "1 2 3 4 5 6 7 8 9 0 ".repeat(100_000);
500        let started = std::time::Instant::now();
501        let _ = mask_text(&digits);
502        let _ = mask_text(&spaced);
503        assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
504    }
505}