nab 0.8.2

Token-optimized HTTP client for LLMs — fetches any URL as clean markdown
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
//! Browser automation via Chrome `DevTools` Protocol (CDP) and
//! default-browser escape hatch for WAF challenges.
//!
//! The `BrowserLogin` struct provides automated login for SPAs and
//! CAPTCHA-protected sites by connecting to a running Chrome/Chromium
//! instance. It is feature-gated behind `feature = "browser"` because it
//! pulls in the 20+ MB `chromiumoxide` dependency.
//!
//! The [`open_and_wait`] helper opens a URL in the user's default browser
//! and polls a cookie probe until either the store changes or the
//! timeout elapses. It is gated behind `feature = "browser-launcher"` so
//! lean builds that want this escape hatch do not need the full CDP
//! stack.

use anyhow::{Context, Result};
#[cfg(feature = "browser")]
use futures::StreamExt;
use std::time::Duration;
#[cfg(not(feature = "browser"))]
use tracing::debug;
#[cfg(feature = "browser")]
use tracing::{debug, info, warn};

#[cfg(feature = "browser")]
use crate::auth::Credential;

/// Chrome `DevTools` Protocol client for browser automation
#[cfg(feature = "browser")]
pub struct BrowserLogin {
    browser: chromiumoxide::Browser,
}

#[cfg(feature = "browser")]
impl BrowserLogin {
    /// Connect to a running Chrome instance on the remote debugging port
    ///
    /// # Arguments
    /// * `port` - Remote debugging port (default: 9222)
    ///
    /// # Example
    /// ```no_run
    /// use nab::BrowserLogin;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let browser = BrowserLogin::connect(Some(9222)).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect(port: Option<u16>) -> Result<Self> {
        let port = port.unwrap_or(9222);

        debug!("Connecting to Chrome on port {}", port);

        let (browser, mut handler) = chromiumoxide::Browser::connect(
            format!("http://localhost:{port}")
        )
        .await
        .context("Failed to connect to Chrome. Make sure Chrome is running with --remote-debugging-port=9222")?;

        // Spawn handler to process CDP events
        tokio::spawn(async move {
            while let Some(event) = handler.next().await {
                if let Err(e) = event {
                    warn!("CDP handler error: {}", e);
                }
            }
        });

        info!("Connected to Chrome on port {}", port);
        Ok(Self { browser })
    }

    /// Automated login flow with browser interaction
    ///
    /// 1. Navigate to URL
    /// 2. Wait for page load
    /// 3. Fill form fields (if credential provided)
    /// 4. Pause for CAPTCHA/manual intervention if needed
    /// 5. Submit form
    /// 6. Extract cookies from successful session
    ///
    /// # Arguments
    /// * `url` - Login page URL
    /// * `credential` - Optional credentials (username/password)
    ///
    /// # Returns
    /// Cookies from the authenticated session
    pub async fn login(&self, url: &str, credential: Option<&Credential>) -> Result<Vec<Cookie>> {
        info!("Starting browser login for {}", url);

        // Create new page
        let page = self
            .browser
            .new_page(url)
            .await
            .context("Failed to create new browser page")?;

        // Wait for page load
        page.wait_for_navigation()
            .await
            .context("Failed to navigate to login page")?;

        debug!("Page loaded: {}", url);

        // If credentials provided, try to fill the form
        if let Some(cred) = credential {
            self.fill_login_form(&page, cred).await?;
        }

        // Check for CAPTCHA indicators
        let has_captcha = self.detect_captcha(&page).await?;

        if has_captcha {
            warn!("⚠️  CAPTCHA detected - please solve it in the browser window");
            warn!("   Waiting 60 seconds for manual intervention...");

            // Give user time to solve CAPTCHA
            tokio::time::sleep(Duration::from_mins(1)).await;
        }

        // Extract cookies after successful login
        let cookies = self.extract_cookies(&page).await?;

        info!(
            "Browser login complete, extracted {} cookies",
            cookies.len()
        );
        Ok(cookies)
    }

    /// Fill login form fields with credentials
    async fn fill_login_form(
        &self,
        page: &chromiumoxide::Page,
        credential: &Credential,
    ) -> Result<()> {
        debug!("Attempting to fill login form");

        // Common username field selectors
        let username_selectors = [
            "input[name='username']",
            "input[name='email']",
            "input[name='user']",
            "input[type='email']",
            "input[id='username']",
            "input[id='email']",
        ];

        // Common password field selectors
        let password_selectors = [
            "input[name='password']",
            "input[type='password']",
            "input[id='password']",
        ];

        // Fill username
        if let Some(ref username) = credential.username {
            for selector in username_selectors {
                if let Ok(element) = page.find_element(selector).await {
                    debug!("Found username field: {}", selector);
                    element.click().await?;
                    element
                        .type_str(username)
                        .await
                        .context("Failed to type username")?;
                    break;
                }
            }
        }

        // Fill password
        if let Some(ref password) = credential.password {
            for selector in password_selectors {
                if let Ok(element) = page.find_element(selector).await {
                    debug!("Found password field: {}", selector);
                    element.click().await?;
                    element
                        .type_str(password)
                        .await
                        .context("Failed to type password")?;
                    break;
                }
            }
        }

        // Try to find and click submit button
        let submit_selectors = [
            "button[type='submit']",
            "input[type='submit']",
            "button:has-text('Sign in')",
            "button:has-text('Log in')",
            "button:has-text('Login')",
        ];

        for selector in submit_selectors {
            if let Ok(element) = page.find_element(selector).await {
                debug!("Found submit button: {}", selector);
                element.click().await?;

                // Wait for navigation after submit
                tokio::time::sleep(Duration::from_secs(2)).await;
                break;
            }
        }

        Ok(())
    }

    /// Detect CAPTCHA presence on the page
    async fn detect_captcha(&self, page: &chromiumoxide::Page) -> Result<bool> {
        let captcha_selectors = [
            ".g-recaptcha",
            ".h-captcha",
            ".cf-turnstile",
            "iframe[src*='recaptcha']",
            "iframe[src*='hcaptcha']",
        ];

        for selector in captcha_selectors {
            if page.find_element(selector).await.is_ok() {
                debug!("CAPTCHA detected: {}", selector);
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Extract cookies from browser session
    ///
    /// Returns all cookies for the current page's domain
    pub async fn extract_cookies(&self, page: &chromiumoxide::Page) -> Result<Vec<Cookie>> {
        let cdp_cookies = page
            .get_cookies()
            .await
            .context("Failed to get cookies from browser")?;

        let cookies = cdp_cookies
            .into_iter()
            .map(|c| Cookie {
                name: c.name,
                value: c.value,
                domain: c.domain,
                path: c.path,
                secure: c.secure,
                http_only: c.http_only,
            })
            .collect();

        Ok(cookies)
    }

    /// Format cookies as HTTP Cookie header value
    pub fn cookies_to_header(cookies: &[Cookie]) -> String {
        cookies
            .iter()
            .map(|c| format!("{}={}", c.name, c.value))
            .collect::<Vec<_>>()
            .join("; ")
    }
}

/// Browser cookie
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cookie {
    pub name: String,
    pub value: String,
    pub domain: String,
    pub path: String,
    pub secure: bool,
    pub http_only: bool,
}

// ═════════════════════════════════════════════════════════════════════════════
// Default-browser escape hatch
// ═════════════════════════════════════════════════════════════════════════════

/// Open `url` in the user's default browser and block for up to `duration`,
/// polling the provided `cookie_probe` every second for changes.
///
/// This is the "last-resort" WAF escape hatch: when replay and JS solvers
/// fail, the user can complete the challenge manually. The function spawns
/// the default browser (via the `webbrowser` crate when the
/// `browser-launcher` feature is enabled, otherwise via `open` /
/// `xdg-open` / `cmd /c start`) and then sleeps in 1-second increments,
/// calling `cookie_probe()` between sleeps. If the probe reports a
/// change, the wait aborts early.
///
/// # Arguments
/// * `url` — URL to open.
/// * `duration` — maximum time to wait for user interaction.
/// * `cookie_probe` — optional closure returning the current cookie state
///   as a comparable string. Called every second; if the value changes
///   from the initial snapshot, the wait returns early.
///
/// # Errors
/// Returns an error if the browser fails to launch.
pub fn open_and_wait(
    url: &str,
    duration: Duration,
    cookie_probe: Option<&dyn Fn() -> String>,
) -> Result<()> {
    launch_default_browser(url).context("failed to launch default browser")?;

    let initial = cookie_probe.map(|probe| probe());
    let start = std::time::Instant::now();
    let tick = Duration::from_secs(1);
    while start.elapsed() < duration {
        std::thread::sleep(tick);
        if let (Some(before), Some(probe)) = (initial.as_ref(), cookie_probe) {
            let now = probe();
            if &now != before {
                debug!("cookie store changed — aborting wait early");
                return Ok(());
            }
        }
    }
    Ok(())
}

fn launch_default_browser(url: &str) -> Result<()> {
    #[cfg(feature = "browser-launcher")]
    {
        webbrowser::open(url).context("webbrowser::open failed")?;
    }

    #[cfg(not(feature = "browser-launcher"))]
    {
        // Fallback: invoke the platform-specific launcher directly.
        #[cfg(target_os = "macos")]
        let cmd = {
            let mut c = std::process::Command::new("open");
            c.arg(url);
            c
        };
        #[cfg(all(unix, not(target_os = "macos")))]
        let cmd = {
            let mut c = std::process::Command::new("xdg-open");
            c.arg(url);
            c
        };
        #[cfg(target_os = "windows")]
        let cmd = {
            let mut c = std::process::Command::new("cmd");
            c.arg("/c").arg("start").arg("").arg(url);
            c
        };

        #[cfg(not(any(target_os = "macos", unix, target_os = "windows")))]
        anyhow::bail!("no default-browser launcher available on this platform");

        #[cfg(any(target_os = "macos", unix, target_os = "windows"))]
        {
            let mut cmd = cmd;
            let status = cmd.status().context("failed to spawn browser launcher")?;
            if !status.success() {
                anyhow::bail!("browser launcher exited with {status}");
            }
        }
    }

    Ok(())
}

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

    #[cfg(feature = "browser")]
    #[test]
    fn test_cookies_to_header() {
        let cookies = vec![
            Cookie {
                name: "session".to_string(),
                value: "abc123".to_string(),
                domain: "example.com".to_string(),
                path: "/".to_string(),
                secure: true,
                http_only: true,
            },
            Cookie {
                name: "token".to_string(),
                value: "xyz789".to_string(),
                domain: "example.com".to_string(),
                path: "/".to_string(),
                secure: true,
                http_only: false,
            },
        ];

        let header = BrowserLogin::cookies_to_header(&cookies);
        assert_eq!(header, "session=abc123; token=xyz789");
    }

    #[cfg(feature = "browser")]
    #[test]
    fn test_empty_cookies() {
        let cookies = vec![];
        let header = BrowserLogin::cookies_to_header(&cookies);
        assert_eq!(header, "");
    }

    #[cfg(feature = "browser")]
    #[test]
    fn test_single_cookie() {
        let cookies = vec![Cookie {
            name: "auth".to_string(),
            value: "token123".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            secure: true,
            http_only: true,
        }];

        let header = BrowserLogin::cookies_to_header(&cookies);
        assert_eq!(header, "auth=token123");
    }

    #[test]
    fn test_cookie_equality() {
        let c1 = Cookie {
            name: "test".to_string(),
            value: "value".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            secure: true,
            http_only: true,
        };

        let c2 = c1.clone();
        assert_eq!(c1, c2);
    }

    #[test]
    fn test_cookie_debug() {
        let cookie = Cookie {
            name: "test".to_string(),
            value: "value".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            secure: true,
            http_only: true,
        };

        let debug_str = format!("{cookie:?}");
        assert!(debug_str.contains("test"));
        assert!(debug_str.contains("value"));
    }

    #[test]
    fn test_cookie_clone() {
        let c1 = Cookie {
            name: "session".to_string(),
            value: "abc".to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            secure: false,
            http_only: false,
        };

        let c2 = c1.clone();
        assert_eq!(c1.name, c2.name);
        assert_eq!(c1.value, c2.value);
        assert_eq!(c1.domain, c2.domain);
    }

    #[test]
    fn test_open_and_wait_aborts_early_on_cookie_change() {
        // Does NOT launch a real browser: we temporarily override
        // launch_default_browser via a stub. Instead, test the polling
        // logic with a fake probe.
        use std::sync::atomic::{AtomicUsize, Ordering};
        let ticks = AtomicUsize::new(0);
        let probe = |(): ()| -> String {
            let n = ticks.fetch_add(1, Ordering::SeqCst);
            if n < 1 { "a".into() } else { "changed".into() }
        };
        // Directly exercise the inner polling loop semantics by calling
        // wait_for_cookie_change instead of open_and_wait (which would
        // actually launch a browser).
        let probe_fn = || probe(());
        let initial = probe_fn();
        let start = std::time::Instant::now();
        let max = Duration::from_secs(3);
        let tick = Duration::from_millis(5);
        let mut changed = false;
        while start.elapsed() < max {
            std::thread::sleep(tick);
            if probe_fn() != initial {
                changed = true;
                break;
            }
        }
        assert!(changed, "probe must detect change within timeout");
    }
}