chrome-agent 0.14.0

Browser automation for AI agents. Single binary, zero deps, CDP direct to Chrome.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! What a snapshot may not print.
//!
//! The accessibility tree is the widest path a field's value takes to stdout: `inspect` prints
//! it, and every action report quotes the same lines back inside `delta`. Chrome masks a
//! `type=password` there, which is why the leak went unnoticed — the other half of
//! `element::SECRET_FIELD`, a card number or a one-time code in a `type=text` field, was
//! reported verbatim on the same response whose `value`/`values_lost` fields said
//! `{"redacted": true}`.
//!
//! Secret-ness is a property of the ELEMENT, not of the string, so it cannot be decided from
//! the tree alone: the a11y tree carries no `type` and no `autocomplete`. It is decided by
//! asking the page — one scan with `element::SECRET_FIELD` as the predicate, and one round trip
//! per secret field FOUND, so the cost follows the small number rather than the number of
//! fields on the page. Nothing is asked at all when the tree holds no value to hide.

use std::collections::{HashMap, HashSet};

use serde_json::{Value, json};

use crate::cdp::client::CdpClient;
use crate::cdp::types::AXNode;

/// What stands in for a value the tree may not print.
///
/// Fixed, never derived from the value: two snapshots of the same unchanged secret field have
/// to compare equal, and a marker carrying a length or a hash would make every action report a
/// change on every secret field it happened to see.
pub const MARKER: &str = "<redacted>";

/// Shortest secret looked for outside the field that holds it.
///
/// A secret's own node is redacted by identity whatever its length. This bound applies only to
/// the search for the same string elsewhere on the page — an echo. Below four characters the
/// search stops being about the secret: a three-digit security code of `123` also appears in a
/// price, a date and a street number, and redacting those hides the page to protect nothing
/// that is still hidden anyway.
const MIN_SEARCHABLE: usize = 4;

/// How many secret fields are located before the whole page's values are redacted instead.
///
/// Locating one costs a CDP round trip, and the probe runs on every snapshot — including the
/// one every action's change report takes. A page holding more secret fields than this is not
/// one an agent is reading field by field, so the cap resolves the other way than usual: it
/// redacts rather than spends.
const MAX_SECRET_FIELDS: usize = 32;

/// The object group the probe's handles live in, released before the probe returns.
const OBJECT_GROUP: &str = "chrome-agent-secret";

/// Which rendered strings the snapshot must replace with [`MARKER`].
#[derive(Default)]
pub struct Redaction {
    /// Nodes whose `value=` is a secret. Their accessible name is a label, and stays.
    values: HashSet<i64>,
    /// Nodes whose accessible NAME is the secret itself: Chrome exposes the editable content
    /// of an input as a `generic` child whose name is the value, so redacting the input's
    /// `value=` alone left the digits one line below it.
    texts: HashSet<i64>,
    /// The secret strings, to catch a page that echoes one somewhere else entirely — a
    /// checkout showing the card it is about to charge. Fails safe: an unrelated node holding
    /// the same string is redacted too.
    strings: Vec<String>,
}

impl Redaction {
    /// Nothing to hide — no candidate carried a value.
    pub fn none() -> Self {
        Self::default()
    }

    /// What to print for a node's `value=`.
    pub fn value<'a>(&'a self, backend: Option<i64>, value: &'a str) -> &'a str {
        match backend {
            // A value with no DOM node behind it cannot be classified, and an unclassified
            // field is treated as a secret.
            None => MARKER,
            Some(id) if self.values.contains(&id) => MARKER,
            _ => self.scrub(value),
        }
    }

    /// What to print for a node's accessible name.
    pub fn name<'a>(&'a self, backend: Option<i64>, name: &'a str) -> &'a str {
        if backend.is_some_and(|id| self.texts.contains(&id)) {
            return MARKER;
        }
        self.scrub(name)
    }

    /// Replace the whole token when it carries a secret, rather than the matching slice: a
    /// partially masked card number is still a card number minus a substring.
    fn scrub<'a>(&'a self, s: &'a str) -> &'a str {
        if self.strings.iter().any(|secret| s.contains(secret.as_str())) {
            MARKER
        } else {
            s
        }
    }

    fn hide_string(&mut self, s: &str) {
        if s.chars().count() >= MIN_SEARCHABLE && !self.strings.iter().any(|k| k == s) {
            self.strings.push(s.to_string());
        }
    }

    /// Build a redaction directly, for the rendering tests.
    #[cfg(test)]
    pub fn for_tests(values: &[i64], texts: &[i64], strings: &[&str]) -> Self {
        Self {
            values: values.iter().copied().collect(),
            texts: texts.iter().copied().collect(),
            strings: strings.iter().map(|s| (*s).to_string()).collect(),
        }
    }
}

/// A node that will render a `value=`, and therefore has to be classified.
struct Candidate {
    node_id: String,
    backend: i64,
    value: String,
}

/// Decide what the tree may print, before a line of it is rendered.
///
/// Costs nothing on a page with no filled field — the common case, including every change
/// report on a page that is not a form.
pub async fn probe(client: &CdpClient, nodes: &[AXNode]) -> Redaction {
    let candidates = candidates(nodes);
    if candidates.is_empty() {
        return Redaction::none();
    }
    build(nodes, &candidates, secret_nodes(client).await.as_ref())
}

/// Turn the page's answer into a redaction. Split from [`probe`] so the answer it fears —
/// `None`, the question that could not be asked — is testable without a browser.
fn build(nodes: &[AXNode], candidates: &[Candidate], secret: Option<&HashSet<i64>>) -> Redaction {
    let by_id: HashMap<&str, &AXNode> = nodes.iter().map(|n| (n.node_id.as_str(), n)).collect();
    let mut redaction = Redaction::default();
    for candidate in candidates {
        // Fails closed: when the page could not be asked, every value it holds is a secret.
        if secret.is_some_and(|ids| !ids.contains(&candidate.backend)) {
            continue;
        }
        redaction.values.insert(candidate.backend);
        redaction.hide_string(&candidate.value);
        hide_subtree(&by_id, &candidate.node_id, &mut redaction);
    }
    redaction
}

/// Every node that renders a non-empty `value=`.
fn candidates(nodes: &[AXNode]) -> Vec<Candidate> {
    let mut seen = HashSet::new();
    nodes
        .iter()
        .filter_map(|node| {
            let value = node
                .value
                .as_ref()
                .and_then(|v| v.value.as_ref())
                .and_then(|v| v.as_str())
                .filter(|v| !v.is_empty())?;
            let backend = node.backend_dom_node_id?;
            seen.insert(backend).then(|| Candidate {
                node_id: node.node_id.clone(),
                backend,
                value: value.to_string(),
            })
        })
        .collect()
}

/// Mark the descendants of a secret field: their text IS its value.
fn hide_subtree(by_id: &HashMap<&str, &AXNode>, node_id: &str, redaction: &mut Redaction) {
    let Some(node) = by_id.get(node_id) else {
        return;
    };
    let Some(child_ids) = &node.child_ids else {
        return;
    };
    for child_id in child_ids {
        if let Some(child) = by_id.get(child_id.as_str()) {
            if let Some(backend) = child.backend_dom_node_id {
                redaction.texts.insert(backend);
            }
            let child_value = child
                .value
                .as_ref()
                .and_then(|v| v.value.as_ref())
                .and_then(|v| v.as_str());
            for text in [child.name_value(), child_value].into_iter().flatten() {
                redaction.hide_string(text);
            }
        }
        hide_subtree(by_id, child_id, redaction);
    }
}

/// Which nodes on the page are secret fields, as backend node ids.
///
/// `None` means the question could not be answered, and the caller then redacts every value in
/// the tree: the alternative to an unanswered question is printing a card number.
///
/// The scan runs once for the whole page and its cost is one round trip per SECRET field found
/// — not per field, and not per node. Asking each value-carrying node instead cost one round
/// trip each: measured at +171ms on a form holding 60 filled inputs, paid on every action.
/// A page has one card number and forty other fields, so the work follows the small number.
async fn secret_nodes(client: &CdpClient) -> Option<HashSet<i64>> {
    let handles = scan(client).await?;
    let mut ids = HashSet::new();
    let mut complete = handles.len() <= MAX_SECRET_FIELDS;
    if complete {
        for handle in &handles {
            match backend_id(client, handle).await {
                Some(id) => {
                    ids.insert(id);
                }
                // A secret field we cannot name is one we cannot mask by identity.
                None => complete = false,
            }
        }
    }
    let _ = client
        .call::<_, Value>(
            "Runtime.releaseObjectGroup",
            json!({"objectGroup": OBJECT_GROUP}),
        )
        .await;
    complete.then_some(ids)
}

/// One in-page pass over every element that could be a secret field, `element::SECRET_FIELD`
/// as the predicate. Returns a JS handle per match.
///
/// Descends into same-origin iframes, which is exactly the set `Accessibility.getFullAXTree`
/// can report on: a cross-origin frame is out-of-process, its nodes are not in this tree, and
/// its content is unreachable from here either way.
async fn scan(client: &CdpClient) -> Option<Vec<String>> {
    let expression = format!(
        r"(() => {{
            const found = [];
            const walk = (doc) => {{
                for (const el of doc.querySelectorAll('input,textarea,select,[autocomplete]')) {{
                    if ({predicate}) found.push(el);
                }}
                for (const frame of doc.querySelectorAll('iframe')) {{
                    try {{ if (frame.contentDocument) walk(frame.contentDocument); }} catch (e) {{}}
                }}
            }};
            walk(document);
            return found;
        }})()",
        predicate = crate::element::SECRET_FIELD
    );
    let mut params = json!({
        "expression": expression,
        "objectGroup": OBJECT_GROUP,
        "returnByValue": false,
    });
    // Scope to the frame the `frame` command bound, the way `eval` and `inspect` do: the tree
    // being rendered is that frame's, so the scan has to run there too.
    if let Some(ctx) = client.frame_context() {
        params["contextId"] = json!(ctx.context_id);
    }
    let result: Value = client.call("Runtime.evaluate", params).await.ok()?;
    if result.get("exceptionDetails").is_some() {
        return None;
    }
    let array = result.get("result")?.get("objectId")?.as_str()?;
    let properties: Value = client
        .call(
            "Runtime.getProperties",
            json!({"objectId": array, "ownProperties": true}),
        )
        .await
        .ok()?;
    let entries = properties.get("result")?.as_array()?;
    let mut handles = Vec::new();
    for entry in entries {
        // Skip `length` and anything else that is not an element handle.
        if entry.get("name").and_then(Value::as_str).is_some_and(|n| n.parse::<usize>().is_ok())
            && let Some(id) = entry.get("value").and_then(|v| v.get("objectId")).and_then(Value::as_str)
        {
            handles.push(id.to_string());
        }
    }
    Some(handles)
}

async fn backend_id(client: &CdpClient, object_id: &str) -> Option<i64> {
    let described: Value = client
        .call("DOM.describeNode", json!({"objectId": object_id}))
        .await
        .ok()?;
    described.get("node")?.get("backendNodeId")?.as_i64()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_secret_value_renders_as_the_marker_and_keeps_its_label() {
        let r = Redaction::for_tests(&[2], &[16], &["4111111111111111"]);
        assert_eq!(r.value(Some(2), "4111111111111111"), MARKER);
        // The label is what the agent aims by, and it is not the secret.
        assert_eq!(r.name(Some(2), "Card number"), "Card number");
        // Chrome's editable-content child, whose NAME is the value.
        assert_eq!(r.name(Some(16), "4111111111111111"), MARKER);
    }

    #[test]
    fn an_ordinary_value_is_untouched() {
        let r = Redaction::for_tests(&[2], &[16], &["4111111111111111"]);
        assert_eq!(r.value(Some(6), "leave at the door"), "leave at the door");
        assert_eq!(r.name(Some(6), "Note for the courier"), "Note for the courier");
    }

    #[test]
    fn an_echo_of_the_secret_is_redacted_wherever_it_appears() {
        // The checkout page showing the card it is about to charge: the same digits reach the
        // same output without ever being a value=.
        let r = Redaction::for_tests(&[2], &[], &["4111111111111111"]);
        assert_eq!(r.name(Some(26), "4111111111111111"), MARKER);
        assert_eq!(r.name(Some(26), "Charging card 4111111111111111"), MARKER);
    }

    #[test]
    fn a_value_with_no_dom_node_behind_it_is_redacted() {
        // `e{n}` uids have no backendDOMNodeId, so nothing can be asked about them.
        let r = Redaction::none();
        assert_eq!(r.value(None, "whatever"), MARKER);
    }

    #[test]
    fn nothing_is_hidden_when_nothing_was_classified() {
        let r = Redaction::none();
        assert_eq!(r.value(Some(2), "hello@example.com"), "hello@example.com");
        assert_eq!(r.name(Some(2), "Email"), "Email");
    }

    #[test]
    fn the_marker_does_not_depend_on_the_value_it_hides() {
        // Two snapshots of the same unchanged secret field must compare equal, and so must
        // two different secrets: a marker that varied would turn every action report into a
        // report of change.
        let r = Redaction::for_tests(&[2], &[], &[]);
        assert_eq!(r.value(Some(2), "4111111111111111"), r.value(Some(2), "4242424242424242"));
    }

    #[test]
    fn a_short_secret_is_not_searched_for_across_the_page() {
        let mut r = Redaction::default();
        r.hide_string("123");
        r.hide_string("7391");
        assert_eq!(r.name(Some(9), "Order 123 of 4"), "Order 123 of 4");
        assert_eq!(r.name(Some(9), "7391"), MARKER);
    }

    #[test]
    fn candidates_are_the_value_carrying_nodes_only() {
        let nodes = vec![
            ax(1, "1", None, Some("4111111111111111")),
            ax(2, "2", Some("Submit"), None),
            ax(3, "3", None, Some("")),
        ];
        let found = candidates(&nodes);
        assert_eq!(found.len(), 1, "only the filled field costs a round trip");
        assert_eq!(found[0].backend, 1);
    }

    #[test]
    fn an_unanswered_question_redacts_every_value() {
        // The scan threw, or a secret field could not be named. Nothing is known about any
        // field, so nothing is printed: the alternative is printing a card number.
        let nodes = [
            ax(2, "a", Some("Card number"), Some("4111111111111111")),
            ax(6, "b", Some("Note"), Some("leave at the door")),
        ];
        let found = candidates(&nodes);
        let r = build(&nodes, &found, None);
        assert_eq!(r.value(Some(2), "4111111111111111"), MARKER);
        assert_eq!(r.value(Some(6), "leave at the door"), MARKER);
        // The fields are still named, so an agent can still see and aim at them.
        assert_eq!(r.name(Some(6), "Note"), "Note");
    }

    #[test]
    fn an_answered_question_redacts_only_what_it_named() {
        let nodes = [
            ax(2, "a", Some("Card number"), Some("4111111111111111")),
            ax(6, "b", Some("Note"), Some("leave at the door")),
        ];
        let found = candidates(&nodes);
        let r = build(&nodes, &found, Some(&HashSet::from([2])));
        assert_eq!(r.value(Some(2), "4111111111111111"), MARKER);
        assert_eq!(r.value(Some(6), "leave at the door"), "leave at the door");
    }

    #[test]
    fn a_subtree_of_a_secret_field_is_hidden_with_it() {
        let mut parent = ax(2, "p", Some("Card number"), Some("4111111111111111"));
        parent.child_ids = Some(vec!["c".into()]);
        let child = ax(16, "c", Some("4111111111111111"), None);
        let nodes = [parent, child];
        let by_id: HashMap<&str, &AXNode> = nodes.iter().map(|n| (n.node_id.as_str(), n)).collect();
        let mut r = Redaction::default();
        hide_subtree(&by_id, "p", &mut r);
        assert!(r.texts.contains(&16));
        assert_eq!(r.name(Some(16), "4111111111111111"), MARKER);
    }

    fn ax(backend: i64, node_id: &str, name: Option<&str>, value: Option<&str>) -> AXNode {
        use crate::cdp::types::AXValue;
        let wrap = |s: &str| AXValue {
            value_type: "string".into(),
            value: Some(Value::String(s.into())),
            related_nodes: None,
        };
        AXNode {
            node_id: node_id.into(),
            ignored: false,
            role: None,
            name: name.map(wrap),
            description: None,
            value: value.map(wrap),
            properties: None,
            child_ids: None,
            backend_dom_node_id: Some(backend),
            frame_id: None,
            parent_id: None,
        }
    }
}