captchaforge 0.2.35

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for chromiumoxide-driven browsers. The architecture is in place (vendor solvers, retry-loop iframe walking, VLM provider abstraction, real-WAF bench harness) but the live-vendor success rate is still 0% — Cloudflare Turnstile / hCaptcha / reCAPTCHA detect us at a TLS / CDP fingerprint layer that no flag-based stealth has cleared. Watch the repo; do not depend on this for any real workload.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! Cross-origin iframe evaluation helpers.
//!
//! CAPTCHA providers (reCAPTCHA, hCaptcha, Turnstile) render their challenges
//! inside sandboxed cross-origin iframes.  JavaScript running in the parent
//! page cannot pierce these iframes via `contentDocument` or
//! `contentWindow.document` — doing so throws a `SecurityError`.
//!
//! This module uses the Chrome DevTools Protocol to evaluate expressions in
//! each frame's own execution context, which works regardless of origin.

use anyhow::{anyhow, Result};
use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;
use chromiumoxide::Page;
use std::time::{Duration, Instant};

/// Default poll cadence for the retry helpers. CAPTCHA iframes typically
/// attach within 50–500ms of navigation; 100ms strikes a balance between
/// responsiveness and CDP traffic.
pub const DEFAULT_FRAME_RETRY_INTERVAL: Duration = Duration::from_millis(100);

/// Default upper bound for the retry helpers. If a captcha widget hasn't
/// attached after 8s the page is almost certainly broken or behind a
/// network stall — caller should fall back rather than wait longer.
pub const DEFAULT_FRAME_RETRY_TIMEOUT: Duration = Duration::from_secs(8);

/// Compute the next sleep duration for a polling loop, clamped so we
/// never overshoot the deadline. Pulled out as a pure function so the
/// retry behaviour can be unit-tested without a real browser.
///
/// Returns `None` when the deadline has been reached or passed.
fn next_poll_sleep(now: Instant, deadline: Instant, interval: Duration) -> Option<Duration> {
    if now >= deadline {
        return None;
    }
    let remaining = deadline.saturating_duration_since(now);
    Some(remaining.min(interval))
}

/// Escape a Rust string so it is safe to embed in a JavaScript string literal
/// surrounded by either single or double quotes.
///
/// Handles the following escapes:
/// - `\`  → `\\`
/// - `'`  → `\'`
/// - `"`  → `\"`
/// - `\n` → `\\n`
/// - `\r` → `\\r`
/// - `\t` → `\\t`
/// - `\0` → `\\0`
fn escape_js_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '\'' => out.push_str("\\'"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\0' => out.push_str("\\0"),
            c => out.push(c),
        }
    }
    out
}

/// Look up the iframe offset for a given URL and optional iframe index.
///
/// `iframe_offsets` is a Vec of `(idx, src, id, x, y)` tuples collected from
/// the main frame in DOM order.  If `iframe_idx` is non-negative we prefer an
/// exact index match to disambiguate duplicate URLs.
fn lookup_iframe_offset(
    iframe_offsets: &[(usize, String, String, f64, f64)],
    url: &str,
    iframe_idx: i64,
) -> (f64, f64) {
    if iframe_idx >= 0 {
        iframe_offsets
            .iter()
            .find(|(idx, src, id, _, _)| *idx == iframe_idx as usize && (src == url || id == url))
            .map(|(_, _, _, x, y)| (*x, *y))
    } else {
        iframe_offsets
            .iter()
            .find(|(_, src, id, _, _)| src == url || id == url)
            .map(|(_, _, _, x, y)| (*x, *y))
    }
    .unwrap_or((0.0, 0.0))
}

/// Evaluate `expression` in every frame of the page (main document + all
/// iframes) and return the deserialized results from every frame that
/// produced a valid value.
///
/// This is the robust replacement for parent-page JS that tries to walk
/// into `iframe.contentDocument`.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::evaluate_in_all_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let titles: Vec<String> = evaluate_in_all_frames(page, "document.title").await?;
/// # Ok(()) }
/// ```
pub async fn evaluate_in_all_frames<T>(page: &Page, expression: &str) -> Result<Vec<T>>
where
    T: serde::de::DeserializeOwned,
{
    let frame_ids = page.frames().await?;
    let mut out = Vec::with_capacity(frame_ids.len());
    for fid in frame_ids {
        if let Some(ctx) = page.frame_execution_context(fid.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(expression)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(v) = eval.into_value::<T>() {
                out.push(v);
            }
        }
    }
    Ok(out)
}

/// Evaluate `expression` in every frame and return the **first** result that
/// passes `filter`.  If no frame produces a matching result, `default` is
/// returned.
pub async fn evaluate_in_frames_first<T, F>(
    page: &Page,
    expression: &str,
    filter: F,
    default: T,
) -> Result<T>
where
    T: serde::de::DeserializeOwned + Clone,
    F: Fn(&T) -> bool,
{
    let all = evaluate_in_all_frames::<T>(page, expression).await?;
    Ok(all.into_iter().find(filter).unwrap_or(default))
}

/// Search every frame for a DOM element matching `selector` and return its
/// bounding-box centre coordinates **relative to the main viewport**.
///
/// For elements inside cross-origin iframes this sums the iframe's own
/// bounding box with the element's position inside the iframe so the
/// resulting coordinates are safe to pass to `Input.dispatchMouseEvent`.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::find_element_centre_in_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let centre = find_element_centre_in_frames(page, "#submit-btn").await?;
/// if let Some((x, y)) = centre {
///     // x, y are viewport-relative coordinates
/// }
/// # Ok(()) }
/// ```
pub async fn find_element_centre_in_frames(
    page: &Page,
    selector: &str,
) -> Result<Option<(f64, f64)>> {
    let frame_ids = page.frames().await?;
    let main_frame = page.mainframe().await?;

    // Build a Vec of iframe offsets keyed by the iframe's index in the
    // DOM querySelectorAll result combined with src/id.  Using a Vec
    // prevents HashMap collisions when two iframes share the same src.
    let mut iframe_offsets: Vec<(usize, String, String, f64, f64)> = Vec::new();
    if let Some(ref main) = main_frame {
        let js = r#"
            (function() {
                const out = [];
                const frames = document.querySelectorAll('iframe');
                for (let i = 0; i < frames.length; i++) {
                    const f = frames[i];
                    const r = f.getBoundingClientRect();
                    out.push({ idx: i, src: f.src, id: f.id, x: r.left, y: r.top });
                }
                return out;
            })()
        "#;
        if let Some(ctx) = page.frame_execution_context(main.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(js)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(vals) = eval.into_value::<Vec<serde_json::Value>>() {
                for v in vals {
                    if let (Some(idx), Some(x), Some(y)) =
                        (v["idx"].as_u64(), v["x"].as_f64(), v["y"].as_f64())
                    {
                        let src = v["src"].as_str().unwrap_or("").to_string();
                        let id = v["id"].as_str().unwrap_or("").to_string();
                        iframe_offsets.push((idx as usize, src, id, x, y));
                    }
                }
            }
        }
    }

    let escaped = escape_js_string(selector);
    let js = format!(
        r#"(function() {{
            const el = document.querySelector('{}');
            if (!el) return null;
            const r = el.getBoundingClientRect();
            let iframeIdx = -1;
            try {{
                const frames = window.parent.frames;
                for (let i = 0; i < frames.length; i++) {{
                    if (frames[i] === window) {{
                        iframeIdx = i;
                        break;
                    }}
                }}
            }} catch (e) {{}}
            return {{ x: r.left + r.width / 2, y: r.top + r.height / 2, url: window.location.href, iframeIdx: iframeIdx }};
        }})()"#,
        escaped
    );

    for fid in frame_ids {
        if let Some(ctx) = page.frame_execution_context(fid.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(&js)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(val) = eval.into_value::<serde_json::Value>() {
                if let (Some(x), Some(y)) = (val["x"].as_f64(), val["y"].as_f64()) {
                    let url = val["url"].as_str().unwrap_or("");
                    let iframe_idx = val["iframeIdx"].as_i64().unwrap_or(-1);
                    let (offset_x, offset_y) = if Some(&fid) == main_frame.as_ref() {
                        (0.0, 0.0)
                    } else {
                        lookup_iframe_offset(&iframe_offsets, url, iframe_idx)
                    };
                    return Ok(Some((x + offset_x, y + offset_y)));
                }
            }
        }
    }
    Ok(None)
}

/// Retrying variant of [`find_element_centre_in_frames`].
///
/// Captcha widgets frequently inject their iframe asynchronously a few
/// hundred milliseconds after the host page loads (Turnstile, hCaptcha
/// invisible, recaptcha v2 audio fallback). A single-shot
/// [`find_element_centre_in_frames`] call against a freshly-navigated
/// page will return `Ok(None)` for those cases — not because the widget
/// is missing, but because the iframe hasn't attached yet.
///
/// This wrapper polls the frame tree on `interval` until either:
/// - a frame returns coordinates (returns `Ok(Some((x, y)))`), or
/// - the wall-clock deadline `timeout` elapses (returns `Ok(None)`).
///
/// `interval` is clamped to never overshoot the deadline, so the actual
/// number of CDP round-trips is bounded by `timeout / interval + 1`.
///
/// Errors from the underlying single-shot call are propagated immediately
/// — only the "not found" outcome triggers a retry.
pub async fn find_element_centre_in_frames_retry(
    page: &Page,
    selector: &str,
    timeout: Duration,
    interval: Duration,
) -> Result<Option<(f64, f64)>> {
    let deadline = Instant::now() + timeout;
    loop {
        if let Some(centre) = find_element_centre_in_frames(page, selector).await? {
            return Ok(Some(centre));
        }
        match next_poll_sleep(Instant::now(), deadline, interval) {
            Some(d) => tokio::time::sleep(d).await,
            None => return Ok(None),
        }
    }
}

/// Retrying variant of [`harvest_token_in_frames`].
///
/// Mirrors [`find_element_centre_in_frames_retry`]: re-walks the frame
/// tree on `interval` until either a populated token is harvested or
/// `timeout` elapses. Used by the post-solve verification paths that
/// need to wait for a vendor's `siteverify`-style response field to be
/// written into the page after a click.
pub async fn harvest_token_in_frames_retry(
    page: &Page,
    token_input_name: &str,
    timeout: Duration,
    interval: Duration,
) -> Result<Option<String>> {
    let deadline = Instant::now() + timeout;
    loop {
        if let Some(tok) = harvest_token_in_frames(page, token_input_name).await? {
            return Ok(Some(tok));
        }
        match next_poll_sleep(Instant::now(), deadline, interval) {
            Some(d) => tokio::time::sleep(d).await,
            None => return Ok(None),
        }
    }
}

/// Check whether a CAPTCHA response token exists in **any** frame.
/// Used for post-solve verification when the provider may inject the token
/// into a hidden input in the main document or inside an iframe.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::verify_token_in_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let found = verify_token_in_frames(page, "g-recaptcha-response").await?;
/// assert!(found);
/// # Ok(()) }
/// ```
/// Search every frame for a populated captcha token field of any
/// well-known shape (`cf-turnstile-response`, `g-recaptcha-response`,
/// `h-captcha-response`, `frc-captcha-solution`, `altcha`,
/// `mcaptcha__token`, `cap_token`, `captchaToken`).
///
/// Returns `Ok(true)` as soon as one frame reports a non-empty
/// `el.value` for any of those fields. Useful as a "did anything
/// pass?" check after a passive WAF challenge — saves the caller
/// from running [`verify_token_in_frames`] once per vendor name.
pub async fn verify_any_token_in_frames(page: &Page) -> Result<bool> {
    const ANY_TOKEN_JS: &str = r#"(() => {
        const sels = [
            '[name="cf-turnstile-response"]',
            '[name="g-recaptcha-response"]',
            '#g-recaptcha-response',
            '[name="h-captcha-response"]',
            '[name="captchaToken"]',
            '[name="frc-captcha-solution"]',
            '[name="altcha"]',
            '[name="mcaptcha__token"]',
            '[name="cap_token"]',
        ];
        for (const sel of sels) {
            try {
                const els = document.querySelectorAll(sel);
                for (const el of els) {
                    const v = (el.value || el.textContent || '').trim();
                    if (v) return true;
                }
            } catch (_) { /* keep going */ }
        }
        return false;
    })()"#;
    let results = evaluate_in_all_frames::<bool>(page, ANY_TOKEN_JS).await?;
    Ok(results.into_iter().any(|v| v))
}

pub async fn verify_token_in_frames(page: &Page, token_input_name: &str) -> Result<bool> {
    Ok(harvest_token_in_frames(page, token_input_name).await?.is_some())
}

/// Like [`verify_token_in_frames`] but returns the populated token
/// VALUE so the chain can hand a real `cf-turnstile-response` /
/// `g-recaptcha-response` / `h-captcha-response` token back to the
/// caller. The chain previously emitted hardcoded label strings
/// (`"behavioral:pre-pass"`, …) which downstream code treated as a
/// success token but couldn't actually validate against the vendor's
/// `siteverify` endpoint.
///
/// Walks every frame; returns the FIRST non-empty value found.
/// Order is BFS-stable per [`crate::frame::evaluate_in_all_frames`].
pub async fn harvest_token_in_frames(
    page: &Page,
    token_input_name: &str,
) -> Result<Option<String>> {
    let escaped = escape_js_string(token_input_name);
    // Same selector + .value-property contract as
    // verify_token_in_frames; returns the value instead of a bool.
    let js = format!(
        r#"(() => {{
            const els = document.querySelectorAll('input[name="{0}"], textarea[name="{0}"], #{0}');
            for (const el of els) {{
                const v = (el.value || el.textContent || '').trim();
                if (v) return v;
            }}
            return null;
        }})()"#,
        escaped
    );
    let results = evaluate_in_all_frames::<Option<String>>(page, &js).await?;
    Ok(results
        .into_iter()
        .flatten()
        .find(|v| !v.is_empty()))
}

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

    #[test]
    fn escape_js_string_all_special_chars() {
        let input = "\\'\"\n\r\t\0";
        assert_eq!(escape_js_string(input), "\\\\\\\'\\\"\\n\\r\\t\\0");
    }

    #[test]
    fn escape_js_string_backslash() {
        assert_eq!(escape_js_string(r"\"), "\\\\");
    }

    #[test]
    fn escape_js_string_single_quote() {
        assert_eq!(escape_js_string("'"), "\\'");
    }

    #[test]
    fn escape_js_string_double_quote() {
        assert_eq!(escape_js_string("\""), "\\\"");
    }

    #[test]
    fn escape_js_string_newline() {
        assert_eq!(escape_js_string("a\nb"), "a\\nb");
    }

    #[test]
    fn escape_js_string_carriage_return() {
        assert_eq!(escape_js_string("a\rb"), "a\\rb");
    }

    #[test]
    fn escape_js_string_tab() {
        assert_eq!(escape_js_string("a\tb"), "a\\tb");
    }

    #[test]
    fn escape_js_string_null_byte() {
        assert_eq!(escape_js_string("a\0b"), "a\\0b");
    }

    #[test]
    fn escape_js_string_mixed() {
        let input = "line1\nline2\tcol\0end\\\"'";
        assert_eq!(
            escape_js_string(input),
            "line1\\nline2\\tcol\\0end\\\\\\\"\\'"
        );
    }

    #[test]
    fn escape_js_string_no_special_chars() {
        assert_eq!(escape_js_string("#simple-id"), "#simple-id");
    }

    #[test]
    fn lookup_iframe_offset_by_index_and_url() {
        let offsets = vec![
            (0, "a.html".into(), "".into(), 10.0, 20.0),
            (1, "b.html".into(), "".into(), 30.0, 40.0),
        ];
        assert_eq!(lookup_iframe_offset(&offsets, "a.html", 0), (10.0, 20.0));
        assert_eq!(lookup_iframe_offset(&offsets, "b.html", 1), (30.0, 40.0));
    }

    #[test]
    fn lookup_iframe_offset_fallback_when_index_missing() {
        let offsets = vec![(0, "a.html".into(), "".into(), 10.0, 20.0)];
        assert_eq!(lookup_iframe_offset(&offsets, "a.html", -1), (10.0, 20.0));
    }

    #[test]
    fn lookup_iframe_offset_disambiguates_duplicate_src() {
        let offsets = vec![
            (0, "same.html".into(), "".into(), 10.0, 20.0),
            (1, "same.html".into(), "".into(), 30.0, 40.0),
        ];
        // With index we can tell them apart.
        assert_eq!(lookup_iframe_offset(&offsets, "same.html", 0), (10.0, 20.0));
        assert_eq!(lookup_iframe_offset(&offsets, "same.html", 1), (30.0, 40.0));
        // Without index, fallback to first match.
        assert_eq!(
            lookup_iframe_offset(&offsets, "same.html", -1),
            (10.0, 20.0)
        );
    }

    #[test]
    fn lookup_iframe_offset_empty_src_and_id() {
        let offsets = vec![
            (0, "".into(), "".into(), 5.0, 5.0),
            (1, "".into(), "".into(), 15.0, 15.0),
        ];
        assert_eq!(lookup_iframe_offset(&offsets, "", 0), (5.0, 5.0));
        assert_eq!(lookup_iframe_offset(&offsets, "", 1), (15.0, 15.0));
    }

    #[test]
    fn lookup_iframe_offset_no_match() {
        let offsets = vec![(0, "a.html".into(), "".into(), 10.0, 20.0)];
        assert_eq!(
            lookup_iframe_offset(&offsets, "missing.html", -1),
            (0.0, 0.0)
        );
    }

    #[test]
    fn find_element_js_contains_query_selector() {
        let selector = "#btn";
        let escaped = escape_js_string(selector);
        let js = format!(
            r#"(function() {{ const el = document.querySelector('{}'); if (!el) return null; const r = el.getBoundingClientRect(); return {{ x: r.left + r.width / 2, y: r.top + r.height / 2, url: window.location.href }}; }})()"#,
            escaped
        );
        assert!(js.contains("document.querySelector"));
        assert!(js.contains("getBoundingClientRect"));
    }

    #[test]
    fn verify_token_js_contains_input_selector() {
        let name = "g-recaptcha-response";
        let escaped = escape_js_string(name);
        let js = format!(
            r#"!!document.querySelector('input[name="{}"][value]:not([value=""])')"#,
            escaped
        );
        assert!(js.contains("input[name="));
        assert!(js.contains("value]:not([value=\"\"])"));
    }

    #[test]
    fn verify_token_escapes_quotes() {
        let name = r#"token"value"#;
        let escaped = escape_js_string(name);
        assert!(escaped.contains("\\\""));
        for (i, ch) in escaped.char_indices() {
            if ch == '"' {
                assert!(
                    i > 0 && escaped.as_bytes()[i - 1] == b'\\',
                    "quote at {} not escaped",
                    i
                );
            }
        }
    }

    #[test]
    fn next_poll_sleep_returns_interval_when_deadline_far() {
        let now = Instant::now();
        let deadline = now + Duration::from_secs(10);
        let interval = Duration::from_millis(100);
        let s = next_poll_sleep(now, deadline, interval).unwrap();
        assert_eq!(s, Duration::from_millis(100));
    }

    #[test]
    fn next_poll_sleep_clamps_to_remaining_when_close_to_deadline() {
        let now = Instant::now();
        let deadline = now + Duration::from_millis(40);
        let interval = Duration::from_millis(100);
        let s = next_poll_sleep(now, deadline, interval).unwrap();
        // Must not overshoot the deadline.
        assert!(s <= Duration::from_millis(40));
        assert!(s >= Duration::from_millis(30));
    }

    #[test]
    fn next_poll_sleep_returns_none_at_deadline() {
        let now = Instant::now();
        let deadline = now;
        assert!(next_poll_sleep(now, deadline, Duration::from_millis(100)).is_none());
    }

    #[test]
    fn next_poll_sleep_returns_none_past_deadline() {
        let now = Instant::now();
        let deadline = now - Duration::from_millis(1);
        assert!(next_poll_sleep(now, deadline, Duration::from_millis(100)).is_none());
    }

    #[test]
    fn next_poll_sleep_zero_interval_still_yields_zero_sleep() {
        // A degenerate interval=0 must not panic; it should yield Some(0)
        // which lets the caller spin once and re-check (callers may use
        // this as an "as fast as CDP allows" mode).
        let now = Instant::now();
        let deadline = now + Duration::from_millis(50);
        let s = next_poll_sleep(now, deadline, Duration::ZERO).unwrap();
        assert_eq!(s, Duration::ZERO);
    }

    #[test]
    fn default_retry_constants_are_sane() {
        // Lock the contract: interval must be smaller than timeout and
        // both must be > 0. Catches a regression where someone swaps
        // them or sets either to zero.
        assert!(DEFAULT_FRAME_RETRY_INTERVAL > Duration::ZERO);
        assert!(DEFAULT_FRAME_RETRY_TIMEOUT > DEFAULT_FRAME_RETRY_INTERVAL);
        // Bound on CDP round-trips per retry call.
        let max_polls = DEFAULT_FRAME_RETRY_TIMEOUT.as_millis()
            / DEFAULT_FRAME_RETRY_INTERVAL.as_millis()
            + 1;
        assert!(
            max_polls <= 200,
            "default retry would issue {max_polls} CDP calls per attempt — too chatty",
        );
    }

    #[test]
    fn verify_token_escapes_null_and_newline() {
        let name = "token\0value\n";
        let escaped = escape_js_string(name);
        assert!(escaped.contains("\\0"));
        assert!(escaped.contains("\\n"));
        assert!(!escaped.contains('\0'));
        assert!(!escaped.contains('\n'));
    }
}