car-ffi-common 0.6.0

Shared logic for FFI bindings (NAPI, PyO3) — JSON wrappers for verify, multi-agent, scheduler
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Shared browser-run logic for the FFI bindings.
//!
//! A `BrowserSession` lazily launches Chromium on first `run()` call, and
//! keeps the session alive for the lifetime of the CarRuntime instance so
//! element IDs from `observe` resolve correctly across multiple `run()`
//! invocations. Mirrors the `car browse run` CLI surface — same JSON
//! script shape in, same JSON trace shape out.

use std::sync::Arc;

use car_browser::backend::BrowserBackend;
use car_browser::chromium::{ChromiumBackend, LaunchOptions};
use car_browser::models::{CookieParam, Modifier};

pub use car_browser::chromium::LaunchOptions as BrowserLaunchOptions;
use car_browser::perception::pipeline::{BasicPerceptionPipeline, PerceptionPipeline};
use car_browser::perception::ui_map::UiMap;
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::sync::Mutex;

/// Resettable holder for a lazily launched browser session.
///
/// `tokio::sync::OnceCell` is a bad fit here because `browser.close` needs to
/// invalidate the cached session. Otherwise the next `browser.run` reuses a
/// closed Chromium backend forever.
#[derive(Default)]
pub struct BrowserSessionSlot {
    session: Mutex<Option<Arc<BrowserSession>>>,
}

impl BrowserSessionSlot {
    pub fn new() -> Self {
        Self::default()
    }

    pub async fn get_or_launch(&self, opts: LaunchOptions) -> Result<Arc<BrowserSession>, String> {
        let mut guard = self.session.lock().await;
        if let Some(session) = guard.as_ref() {
            return Ok(session.clone());
        }

        let session = Arc::new(BrowserSession::launch_with_options(opts).await?);
        *guard = Some(session.clone());
        Ok(session)
    }

    pub async fn close(&self) -> Result<bool, String> {
        let session = self.session.lock().await.take();
        if let Some(session) = session {
            session.close().await?;
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

/// A reusable browser session — wraps Chromium + a perception pipeline and
/// caches the last observed UiMap for element-ID resolution.
///
/// # Lifecycle
///
/// Callers should invoke [`BrowserSession::close`] before dropping when a
/// clean teardown matters. The `Drop` impl runs a best-effort shutdown
/// using `tokio::task::block_in_place` when a runtime is available, but
/// it can leak the Chromium process in edge cases (e.g. when the tokio
/// runtime is already shutting down). Explicit `close().await` is the
/// reliable path.
pub struct BrowserSession {
    backend: Arc<ChromiumBackend>,
    pipeline: BasicPerceptionPipeline,
    last_ui_map: Mutex<Option<UiMap>>,
    width: u32,
    height: u32,
    closed: std::sync::atomic::AtomicBool,
}

impl BrowserSession {
    pub async fn launch(width: u32, height: u32) -> Result<Self, String> {
        Self::launch_with_options(LaunchOptions {
            width,
            height,
            headless: true,
            extra_args: Vec::new(),
        })
        .await
    }

    /// Launch with full options (width, height, headless). Used by the FFI
    /// bindings to expose a headed mode for interactive first-time auth.
    pub async fn launch_with_options(opts: LaunchOptions) -> Result<Self, String> {
        let width = opts.width;
        let height = opts.height;
        let backend = Arc::new(
            ChromiumBackend::launch_with_options(opts)
                .await
                .map_err(|e| format!("launch chrome: {}", e))?,
        );
        Ok(Self {
            backend,
            pipeline: BasicPerceptionPipeline::new(),
            last_ui_map: Mutex::new(None),
            width,
            height,
            closed: std::sync::atomic::AtomicBool::new(false),
        })
    }

    /// Viewport dimensions the session was launched with.
    pub fn viewport(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Shut down the Chromium process cleanly. Idempotent — calling twice
    /// is safe.
    pub async fn close(&self) -> Result<(), String> {
        use std::sync::atomic::Ordering;
        if self.closed.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        self.backend
            .shutdown()
            .await
            .map_err(|e| format!("browser shutdown: {}", e))
    }

    /// Run a JSON script of operations against the open browser.
    /// Returns the JSON trace (caller parses if it wants structured access).
    pub async fn run(&self, script_json: &str) -> Result<String, String> {
        let script: BrowseScript =
            serde_json::from_str(script_json).map_err(|e| format!("parse script: {}", e))?;

        // Expand `session_ref` (if any) by reading a SessionBundle from the
        // secret store and prepending set_cookies / set_local_storage /
        // set_extra_headers ops. Real credentials never appear in the script
        // JSON this way — only the reference.
        let expanded = expand_session_ref(script.session_ref.as_ref(), script.operations)?;

        let mut steps = Vec::with_capacity(expanded.len());
        for op in expanded {
            let start = std::time::Instant::now();
            let (name, result) = self.run_op(op).await;
            let elapsed = start.elapsed().as_millis() as u64;
            let (status, data, error) = match result {
                Ok(d) => ("ok", d, None),
                Err(e) => ("error", None, Some(e)),
            };
            let failed = status == "error";
            steps.push(json!({
                "op": name,
                "status": status,
                "data": data,
                "error": error,
                "duration_ms": elapsed,
            }));
            if failed {
                break;
            }
        }

        Ok(json!({ "steps": steps }).to_string())
    }

    async fn run_op(&self, op: BrowseOp) -> (&'static str, Result<Option<Value>, String>) {
        match op {
            BrowseOp::Navigate { url } => (
                "navigate",
                self.backend
                    .navigate(&url)
                    .await
                    .map(|_| Some(json!({ "url": url })))
                    .map_err(|e| e.to_string()),
            ),
            BrowseOp::Observe => {
                let res: Result<Option<Value>, String> = async {
                    let tree = self
                        .backend
                        .get_accessibility_tree()
                        .await
                        .map_err(|e| e.to_string())?;
                    let viewport = self.backend.get_viewport().map_err(|e| e.to_string())?;
                    let url = self.backend.get_current_url().map_err(|e| e.to_string())?;
                    let title = self.backend.get_page_title().await.unwrap_or_default();
                    let screenshot = self
                        .backend
                        .capture_screenshot()
                        .await
                        .map_err(|e| e.to_string())?;
                    let ui_map = self
                        .pipeline
                        .perceive(&screenshot, &tree, &url, viewport)
                        .await
                        .map_err(|e| e.to_string())?;
                    let summary = ui_map.format_summary();
                    let element_count = ui_map.elements.len();
                    *self.last_ui_map.lock().await = Some(ui_map);
                    Ok(Some(json!({
                        "url": url,
                        "title": title,
                        "element_count": element_count,
                        "summary": summary,
                    })))
                }
                .await;
                ("observe", res)
            }
            BrowseOp::Click { element_id } => {
                let ax_id = self.resolve_element(&element_id).await;
                (
                    "click",
                    self.backend
                        .click_element(&ax_id)
                        .await
                        .map(|_| Some(json!({ "element_id": element_id, "resolved_to": ax_id })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::Type { element_id, text } => {
                let ax_id = self.resolve_element(&element_id).await;
                (
                    "type",
                    self.backend
                        .type_into_element(&ax_id, &text)
                        .await
                        .map(|_| Some(json!({ "element_id": element_id, "resolved_to": ax_id })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::Scroll { delta_y } => (
                "scroll",
                self.backend
                    .inject_scroll(delta_y)
                    .await
                    .map(|_| Some(json!({ "delta_y": delta_y })))
                    .map_err(|e| e.to_string()),
            ),
            BrowseOp::Keypress { key, modifiers } => {
                let parsed: Vec<Modifier> = modifiers
                    .iter()
                    .filter_map(|m| match m.to_lowercase().as_str() {
                        "alt" => Some(Modifier::Alt),
                        "control" | "ctrl" => Some(Modifier::Control),
                        "meta" | "command" | "cmd" => Some(Modifier::Meta),
                        "shift" => Some(Modifier::Shift),
                        _ => None,
                    })
                    .collect();
                (
                    "keypress",
                    self.backend
                        .inject_keypress(&key, &parsed)
                        .await
                        .map(|_| Some(json!({ "key": key, "modifiers": modifiers })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::SetCookies { cookies } => {
                let count = cookies.len();
                (
                    "set_cookies",
                    self.backend
                        .set_cookies(&cookies)
                        .await
                        .map(|_| Some(json!({ "cookies_set": count })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::SetExtraHeaders { headers } => {
                let count = headers.len();
                let pairs: Vec<(String, String)> = headers.into_iter().collect();
                (
                    "set_extra_headers",
                    self.backend
                        .set_extra_headers(&pairs)
                        .await
                        .map(|_| Some(json!({ "headers_set": count })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::SetLocalStorage { origin, items } => {
                let count = items.len();
                let pairs: Vec<(String, String)> = items.into_iter().collect();
                (
                    "set_local_storage",
                    self.backend
                        .set_local_storage(&origin, &pairs)
                        .await
                        .map(|_| Some(json!({ "origin": origin, "items_set": count })))
                        .map_err(|e| e.to_string()),
                )
            }
            BrowseOp::Wait {
                condition,
                timeout_ms,
            } => {
                let parsed = match parse_wait_condition(&condition) {
                    Some(c) => c,
                    None => {
                        return (
                            "wait",
                            Err(format!("unknown wait condition: {}", condition)),
                        );
                    }
                };
                (
                    "wait",
                    self.backend
                        .wait_until(&parsed, timeout_ms)
                        .await
                        .map(|success| Some(json!({ "condition": condition, "success": success })))
                        .map_err(|e| e.to_string()),
                )
            }
        }
    }

    }

impl Drop for BrowserSession {
    fn drop(&mut self) {
        use std::sync::atomic::Ordering;
        if self.closed.load(Ordering::SeqCst) {
            return;
        }
        // Best effort: only works if a tokio runtime exists and we're not
        // inside `drop_in_place` during final-shutdown teardown. Callers
        // who care about clean teardown should call `close().await`.
        let backend = self.backend.clone();
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.spawn(async move {
                let _ = backend.shutdown().await;
            });
        }
    }
}

impl BrowserSession {
    async fn resolve_element(&self, element_id: &str) -> String {
        let guard = self.last_ui_map.lock().await;
        if let Some(map) = guard.as_ref() {
            if let Some(el) = map.get_element(element_id) {
                if let Some(ref ax) = el.ax_ref {
                    return ax.clone();
                }
            }
        }
        element_id.to_string()
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BrowseScript {
    operations: Vec<BrowseOp>,
    /// Optional reference to a stored session bundle. When present, the
    /// browser reads `SessionBundle` JSON from the secret store and
    /// prepends auto-replayable ops (cookies + localStorage) to the
    /// script. Headers are NOT auto-replayed — see `expand_session_ref`.
    #[serde(default)]
    session_ref: Option<SessionRef>,
}

/// Points at a stored `SessionBundle` in the OS secret store. Matches the
/// shape that `car secret put` / `rt.secret_put` writes.
#[derive(Deserialize)]
pub struct SessionRef {
    /// Namespace (service) in the OS secret store.
    #[serde(default)]
    pub service: Option<String>,
    /// Entry key — the actual (service, key) pair the secret is stored under.
    pub key: String,
}

/// Persistent session material users store via the secret API and reference
/// from scripts via `session_ref`. All fields are optional — the bundle only
/// replays what's present.
#[derive(Deserialize, serde::Serialize)]
pub struct SessionBundle {
    #[serde(default)]
    pub cookies: Vec<CookieParam>,
    #[serde(default)]
    pub headers: std::collections::HashMap<String, String>,
    /// origin → {key: value}
    #[serde(default)]
    pub local_storage: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
}

/// Read the session bundle (if referenced) and prepend the corresponding
/// ops to the script. Errors cleanly if the ref is present but the secret
/// store is unavailable or the entry isn't a valid bundle.
///
/// # Security contract
///
/// `session_ref` deliberately does NOT auto-replay `headers` from the
/// bundle. Chromium's `Network.setExtraHTTPHeaders` has no per-origin
/// scoping, so headers injected automatically would follow every
/// navigation — a malicious script that references an attacker-controlled
/// URL after a legitimate session would leak `Authorization: Bearer ...`
/// and friends.
///
/// Cookies (domain-scoped) and localStorage (origin-scoped) are safe to
/// auto-replay because the browser enforces scoping at the protocol
/// level. Headers must be added with an explicit `set_extra_headers` op,
/// with the author accepting responsibility for cross-origin exposure.
///
/// The stored `SessionBundle.headers` field is retained so users can
/// store + inspect + manually replay headers; it is never auto-injected.
fn expand_session_ref(
    session_ref: Option<&SessionRef>,
    ops: Vec<BrowseOp>,
) -> Result<Vec<BrowseOp>, String> {
    let sref = match session_ref {
        Some(s) => s,
        None => return Ok(ops),
    };

    let raw = crate::secrets::read_raw(sref.service.as_deref(), &sref.key)
        .map_err(|e| format!("session_ref: {}", e))?;
    let bundle: SessionBundle = serde_json::from_str(&raw)
        .map_err(|e| format!("session_ref value is not a valid SessionBundle: {}", e))?;

    let mut expanded = Vec::with_capacity(ops.len() + 2);
    if !bundle.cookies.is_empty() {
        expanded.push(BrowseOp::SetCookies {
            cookies: bundle.cookies,
        });
    }
    // NOTE: bundle.headers is NOT auto-injected. See security contract above.
    // Callers that need headers replay them explicitly via set_extra_headers.
    for (origin, items) in bundle.local_storage {
        expanded.push(BrowseOp::SetLocalStorage { origin, items });
    }
    expanded.extend(ops);
    Ok(expanded)
}

#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
enum BrowseOp {
    Navigate {
        url: String,
    },
    Observe,
    Click {
        element_id: String,
    },
    Type {
        element_id: String,
        text: String,
    },
    Scroll {
        delta_y: i32,
    },
    Keypress {
        key: String,
        #[serde(default)]
        modifiers: Vec<String>,
    },
    Wait {
        condition: String,
        #[serde(default = "default_wait_timeout_ms")]
        timeout_ms: u64,
    },
    /// Inject cookies before the next navigation.
    SetCookies {
        cookies: Vec<CookieParam>,
    },
    /// Set extra HTTP headers to include on every request.
    SetExtraHeaders {
        headers: std::collections::HashMap<String, String>,
    },
    /// Set localStorage items for an origin.
    SetLocalStorage {
        origin: String,
        items: std::collections::HashMap<String, String>,
    },
}

fn default_wait_timeout_ms() -> u64 {
    30_000
}

fn parse_wait_condition(s: &str) -> Option<car_browser::models::WaitCondition> {
    use car_browser::models::WaitCondition;
    match s {
        "page_loaded" => Some(WaitCondition::PageLoaded),
        "url_changed" => Some(WaitCondition::UrlChanged),
        s if s.starts_with("element_with_name:") => Some(WaitCondition::ElementWithName {
            name_contains: s[18..].to_string(),
            role: None,
        }),
        s if s.starts_with("a11y_contains_text:") => Some(WaitCondition::A11yContainsText {
            text: s[19..].to_string(),
        }),
        _ => None,
    }
}