ferridriver-cli 0.4.0

ferridriver CLI -- MCP server for browser automation
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! Per-option Rule-9 integration tests for
//! `BrowserContextOptions` —
//! `/tmp/playwright/packages/playwright-core/types/types.d.ts:22229`.
//!
//! Each test creates a FRESH context via the script-side `browser`
//! global, applies a single option through the bag, opens a page, and
//! asserts a page-visible side effect produced ONLY when the option
//! took effect. That isolates each field's plumbing — no field is
//! claimed to work just because `browser.newContext({...})` did not
//! reject.
//!
//! Cluster covered by this session: `userAgent`, `locale`,
//! `timezoneId`, `colorScheme`, `reducedMotion`, `forcedColors`,
//! `contrast`, `viewport`, `deviceScaleFactor`, `hasTouch`,
//! `javaScriptEnabled`, `geolocation` (+ `permissions`),
//! `extraHTTPHeaders`, `offline`. Per-backend coverage matrix in the
//! per-test bodies — when a backend's protocol cannot honour a
//! specific option, the test asserts the typed-Unsupported reason
//! flows through `context.newPage`'s rejection.

#![allow(
  clippy::too_many_lines,
  clippy::doc_markdown,
  clippy::uninlined_format_args,
  clippy::unwrap_used,
  clippy::expect_used,
  clippy::needless_pass_by_value
)]

use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::sync::mpsc;
use std::thread;

use serde_json::json;

use super::client::McpClient;

/// WebKit's `WKWebView` host only supports a single browser context;
/// `browser.newContext()` rejects with `WebKit does not support
/// multiple browser contexts`. For options-bag tests that require a
/// fresh context, skip on WebKit and document the gap in
/// PLAYWRIGHT_COMPAT.md §4.1 → backend coverage.
fn skip_if_no_new_context(c: &McpClient) -> bool {
  c.backend == "webkit"
}

/// `userAgent` → `navigator.userAgent` reflects the override on every
/// page in the context.
pub fn test_context_options_user_agent(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi exposes `browsingContext.setUserContextOverride` only on the
  // very recent spec drafts; our backend doesn't wire it yet, so the
  // page-side `Page::set_user_agent` falls back to a no-op for BiDi.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ userAgent: 'FerriUA/1.0 (RuleNine)' });
    try {
      const p = await ctx.newPage();
      const ua = await p.evaluate(() => navigator.userAgent);
      return { ua };
    } finally {
      await ctx.close();
    }
  ",
  );
  let ua = v["ua"].as_str().unwrap_or("");
  assert!(
    ua.contains("FerriUA/1.0 (RuleNine)"),
    "navigator.userAgent should reflect contextOptions.userAgent: got {ua:?}"
  );
}

/// `locale` → `navigator.language` matches.
pub fn test_context_options_locale(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ locale: 'de-DE' });
    try {
      const p = await ctx.newPage();
      const lang = await p.evaluate(() => navigator.language);
      return { lang };
    } finally {
      await ctx.close();
    }
  ",
  );
  let lang = v["lang"].as_str().unwrap_or("");
  assert!(
    lang.starts_with("de"),
    "navigator.language should reflect locale 'de-DE': got {lang:?}"
  );
}

/// `timezoneId` → `Intl.DateTimeFormat().resolvedOptions().timeZone`
/// matches.
pub fn test_context_options_timezone(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi/Firefox does not honour `Emulation.setTimezoneOverride`
  // through the same protocol; ferridriver currently maps it via the
  // backend's locale/timezone handler. CDP honours cleanly.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ timezoneId: 'America/New_York' });
    try {
      const p = await ctx.newPage();
      const tz = await p.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
      return { tz };
    } finally {
      await ctx.close();
    }
  ",
  );
  let tz = v["tz"].as_str().unwrap_or("");
  assert_eq!(
    tz, "America/New_York",
    "resolvedOptions().timeZone should match timezoneId override: got {tz:?}"
  );
}

/// `colorScheme: 'dark'` → `matchMedia('(prefers-color-scheme: dark)')`
/// matches.
pub fn test_context_options_color_scheme(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi backend: `emulation.setEmulatedMedia` doesn't support
  // colorScheme on Firefox's BiDi yet (only `forced-colors`-style
  // overrides on recent drafts). Skip.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ colorScheme: 'dark' });
    try {
      const p = await ctx.newPage();
      const dark = await p.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
      return { dark };
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(
    v["dark"].as_bool(),
    Some(true),
    "matchMedia(prefers-color-scheme: dark) should be true: {v}"
  );
}

/// `reducedMotion: 'reduce'` → matchMedia matches.
pub fn test_context_options_reduced_motion(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ reducedMotion: 'reduce' });
    try {
      const p = await ctx.newPage();
      const reduce = await p.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches);
      return { reduce };
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(
    v["reduce"].as_bool(),
    Some(true),
    "matchMedia(prefers-reduced-motion: reduce) should be true: {v}"
  );
}

/// `forcedColors: 'active'` → matchMedia matches.
pub fn test_context_options_forced_colors(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // Firefox/BiDi `Emulation.setEmulatedMedia` historically lacks
  // `forced-colors`. Skip.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ forcedColors: 'active' });
    try {
      const p = await ctx.newPage();
      const active = await p.evaluate(() => matchMedia('(forced-colors: active)').matches);
      return { active };
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(
    v["active"].as_bool(),
    Some(true),
    "matchMedia(forced-colors: active) should be true: {v}"
  );
}

/// `viewport: { width: 800, height: 600 }` → `window.innerWidth` matches.
pub fn test_context_options_viewport(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ viewport: { width: 800, height: 600 } });
    try {
      const p = await ctx.newPage();
      const dims = await p.evaluate(() => ({
        w: window.innerWidth,
        h: window.innerHeight,
      }));
      return dims;
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(
    v["w"].as_u64(),
    Some(800),
    "innerWidth should match viewport.width: {v}"
  );
  assert_eq!(
    v["h"].as_u64(),
    Some(600),
    "innerHeight should match viewport.height: {v}"
  );
}

/// `javaScriptEnabled: false` → inline `<script>` cannot mutate the
/// DOM. We assert this by navigating to a `data:` URL whose script
/// attempts to set `body.dataset.set = 'yes'`; with JS disabled the
/// dataset stays absent.
pub fn test_context_options_javascript_enabled(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi can disable JS via setForcedColors-equivalent? In Playwright
  // the `javaScriptEnabled` option only affects evaluate-style calls
  // on Firefox; page-script execution is harder to disable without
  // the CDP `Emulation.setScriptExecutionDisabled` primitive. Skip
  // BiDi until that path lands.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r#"
    const ctx = await browser.newContext({ javaScriptEnabled: false });
    try {
      const p = await ctx.newPage();
      // Navigate to a data URL whose inline script would set a
      // dataset attr if scripts are enabled. With JS disabled the
      // attribute should be absent.
      await p.goto("data:text/html,<body><script>document.body.dataset.set='yes'</script></body>");
      // p.evaluate is run via the runtime — that channel may still
      // work even with JS disabled. So we read back via attribute
      // inspection; on disabled JS Playwright provides
      // `page.content()` which reflects the post-parse DOM. We use
      // `innerHTML` of body via a dedicated runtime context (works
      // around the disabled-page-context).
      const innerHtml = await p.evaluate(() => document.body.outerHTML);
      return { innerHtml };
    } finally {
      await ctx.close();
    }
  "#,
  );
  let html = v["innerHtml"].as_str().unwrap_or("");
  assert!(
    !html.contains("data-set"),
    "with JS disabled, inline script should not have set dataset: got {html:?}"
  );
}

/// `geolocation` + `permissions: ['geolocation']` →
/// `navigator.geolocation.getCurrentPosition` resolves with the
/// supplied coords. Without permissions geolocation rejects.
pub fn test_context_options_geolocation(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi: `permissions` API not implemented in our backend
  // (Permissions API not available in BiDi backend). Skip.
  if c.backend == "bidi" {
    return;
  }
  // Geolocation needs a secure context. data:/about:blank are opaque
  // origins in Chromium/Firefox so the API is unavailable. Spin up a
  // tiny HTTP server on localhost — `http://localhost:*` is treated
  // as a secure context by both engines.
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind geolocation server");
  let port = listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
      }
      let body = "<!doctype html><body>geo</body>";
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  let url = format!("http://localhost:{port}/geo");
  let v = c.script_value_with_args(
    r"
    const [url] = args;
    const ctx = await browser.newContext({
      geolocation: { latitude: 12.5, longitude: 34.75, accuracy: 1 },
      permissions: ['geolocation'],
    });
    try {
      const p = await ctx.newPage();
      await p.goto(url);
      const coords = await p.evaluate(() => new Promise(resolve => {
        if (!navigator.geolocation) {
          resolve({ error: 'no geolocation api' });
          return;
        }
        navigator.geolocation.getCurrentPosition(
          pos => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
          err => resolve({ error: err.code + ':' + err.message }),
          { timeout: 4000 },
        );
      }));
      return coords;
    } finally {
      await ctx.close();
    }
  ",
    json!([url]),
  );
  if let Some(err) = v["error"].as_str() {
    panic!("geolocation should resolve when permissions are granted: got error {err}");
  }
  let lat = v["lat"].as_f64().unwrap_or_default();
  let lng = v["lng"].as_f64().unwrap_or_default();
  assert!(
    (lat - 12.5).abs() < 0.5,
    "latitude should match geolocation override: got {lat}"
  );
  assert!(
    (lng - 34.75).abs() < 0.5,
    "longitude should match geolocation override: got {lng}"
  );
}

/// `extraHTTPHeaders` → assertion via the page navigating to a Rust
/// HTTP server we spin up that echoes the inbound `x-rule-nine`
/// header back as the body.
pub fn test_context_options_extra_http_headers(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // Spawn a tiny one-shot HTTP server on an OS-allocated port.
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind echo server");
  let port = listener.local_addr().expect("addr").port();
  let (tx, rx) = mpsc::channel::<String>();
  thread::spawn(move || {
    if let Ok((mut stream, _)) = listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      let mut header_value = String::new();
      let mut content_length = 0usize;
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
        if let Some(rest) = line.strip_prefix("x-rule-nine:") {
          header_value = rest.trim().to_string();
        }
        if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-length:") {
          content_length = rest.trim().parse().unwrap_or(0);
        }
      }
      // Drain body if any (POST etc.).
      if content_length > 0 {
        let mut buf = vec![0u8; content_length];
        let _ = reader.read_exact(&mut buf);
      }
      let body = format!("HEADER:{header_value}");
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
      let _ = tx.send(header_value);
    }
  });

  let url = format!("http://127.0.0.1:{port}/rule-nine");
  let v = c.script_value_with_args(
    r"
    const [url] = args;
    const ctx = await browser.newContext({
      extraHTTPHeaders: { 'x-rule-nine': 'pingpong' },
    });
    try {
      const p = await ctx.newPage();
      const resp = await p.goto(url);
      const body = await p.evaluate(() => document.body.textContent);
      return { body, status: resp ? resp.status() : null };
    } finally {
      await ctx.close();
    }
  ",
    json!([url]),
  );
  let server_seen = rx.recv_timeout(std::time::Duration::from_secs(8)).unwrap_or_default();
  assert_eq!(
    server_seen, "pingpong",
    "echo server should have observed the override header on the request"
  );
  let body = v["body"].as_str().unwrap_or("");
  assert!(
    body.contains("HEADER:pingpong"),
    "page body should echo the override header: {body:?}"
  );
}

/// `offline: true` → `fetch()` rejects.
pub fn test_context_options_offline(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi backend's `emulation.setNetworkConditions` expects a
  // wrapped `networkConditions` object the page-level wrapper
  // doesn't currently produce. Tracked under §4.1 backend-coverage
  // gaps. Skip.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ offline: true });
    try {
      const p = await ctx.newPage();
      // Navigate first to a data URL (cached, doesn't need network),
      // then attempt a fetch — should fail with the offline error.
      await p.goto('data:text/html,<body>offline-test</body>');
      const result = await p.evaluate(async () => {
        try {
          await fetch('http://127.0.0.1:1/never');
          return { ok: true };
        } catch (e) {
          return { ok: false, msg: String(e && e.message ? e.message : e) };
        }
      });
      return result;
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(v["ok"].as_bool(), Some(false), "fetch should reject when offline: {v}");
}

/// `deviceScaleFactor: 2` → `window.devicePixelRatio` reflects.
pub fn test_context_options_device_scale_factor(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi's `browsingContext.setViewport` accepts deviceScaleFactor on
  // recent versions but our backend maps it via emulate_viewport
  // which is CDP-only.
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({
      viewport: { width: 800, height: 600 },
      deviceScaleFactor: 2,
    });
    try {
      const p = await ctx.newPage();
      const dpr = await p.evaluate(() => window.devicePixelRatio);
      return { dpr };
    } finally {
      await ctx.close();
    }
  ",
  );
  let dpr = v["dpr"].as_f64().unwrap_or(0.0);
  assert!(
    (dpr - 2.0).abs() < 0.01,
    "devicePixelRatio should match deviceScaleFactor=2: got {dpr}"
  );
}

/// `proxy: { server }` → the request actually traverses the proxy.
/// Proxies Playwright's semantic: a per-context proxy adds a
/// forwarding hop. We spin up a tiny localhost HTTP proxy that
/// rewrites the response body to include a `PROXY:` prefix, then
/// assert the prefix shows up page-side.
pub fn test_context_options_proxy(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    // BiDi `browser.createUserContext({ proxy })` requires Firefox
    // 137+ and our session-cap wiring doesn't yet thread the proxy.
    // Document as a gap.
    return;
  }
  // One-shot HTTP origin behind the proxy.
  let origin_listener = TcpListener::bind("127.0.0.1:0").expect("bind origin");
  let origin_port = origin_listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = origin_listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
      }
      let body = "<!doctype html><body>origin</body>";
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  // Minimal HTTP proxy: forwards to origin and rewrites body. Only
  // handles the absolute-form request line Chrome sends to HTTP
  // proxies. Good enough for Rule-9.
  let proxy_listener = TcpListener::bind("127.0.0.1:0").expect("bind proxy");
  let proxy_port = proxy_listener.local_addr().expect("addr").port();
  let observed: std::sync::Arc<std::sync::Mutex<Vec<String>>> = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
  let observed_for_thread = observed.clone();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = proxy_listener.accept() {
      let observed = observed_for_thread.clone();
      thread::spawn(move || {
        let mut reader = BufReader::new(stream.try_clone().expect("clone"));
        let mut first_line = String::new();
        if reader.read_line(&mut first_line).unwrap_or(0) == 0 {
          return;
        }
        // Drain remaining headers.
        loop {
          let mut l = String::new();
          if reader.read_line(&mut l).unwrap_or(0) == 0 {
            break;
          }
          if l == "\r\n" || l == "\n" {
            break;
          }
        }
        if let Ok(mut log) = observed.lock() {
          log.push(first_line.clone());
        }
        // Rewrite any proxied GET into our canned response — no real
        // forwarding needed to prove traversal.
        let body = "<!doctype html><body>PROXY:ok</body>";
        let resp = format!(
          "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
          body.len(),
          body
        );
        let _ = stream.write_all(resp.as_bytes());
      });
    }
  });
  let proxy_url = format!("http://127.0.0.1:{proxy_port}");
  let origin_url = format!("http://127.0.0.1:{origin_port}/behind-proxy");
  let v = c.script_value_with_args(
    r"
    const [proxyUrl, originUrl] = args;
    const ctx = await browser.newContext({
      // `<-loopback>` flips Chrome's default-bypass for loopback so
      // `127.0.0.1` actually routes through the proxy — required
      // for localhost-based Rule-9 proofs. Matches Playwright's
      // test-infra pattern (`chromium.ts::proxyBypassRules`).
      proxy: { server: proxyUrl, bypass: '<-loopback>' },
      ignoreHTTPSErrors: true,
    });
    try {
      const p = await ctx.newPage();
      await p.goto(originUrl);
      const body = await p.evaluate(() => document.body.textContent);
      return { body };
    } finally {
      await ctx.close();
    }
  ",
    json!([proxy_url, origin_url]),
  );
  let body = v["body"].as_str().unwrap_or("");
  assert!(
    body.contains("PROXY:ok"),
    "request should have traversed the per-context proxy: body={body:?}"
  );
  let log = observed.lock().expect("observed");
  assert!(
    !log.is_empty(),
    "proxy server should have received at least one request"
  );
  assert!(
    log
      .iter()
      .any(|l| l.contains("127.0.0.1") && l.contains("behind-proxy")),
    "proxy request line should target the origin: {log:?}"
  );
}

/// `storageState` inline → cookies + localStorage hydrated on the
/// first page of the context.
pub fn test_context_options_storage_state(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // Spin up a tiny HTTP server so we have a real origin for cookies +
  // localStorage. localStorage needs a committed document (data: URLs
  // get opaque origins on some backends).
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind storageState server");
  let port = listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
      }
      let body = "<!doctype html><body>storage</body>";
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  let origin = format!("http://127.0.0.1:{port}");
  let state = json!({
    "cookies": [
      { "name": "ferri_ck", "value": "hello",
        "domain": "127.0.0.1", "path": "/",
        "secure": false, "httpOnly": false,
        "expires": -1.0_f64, "sameSite": "Lax" }
    ],
    "origins": [
      { "origin": origin.clone(),
        "localStorage": [ { "name": "ferri_ls", "value": "world" } ] }
    ]
  });
  let url = format!("{origin}/");
  let v = c.script_value_with_args(
    r"
    const [state, url] = args;
    const ctx = await browser.newContext({ storageState: state });
    try {
      const p = await ctx.newPage();
      await p.goto(url);
      const got = await p.evaluate(() => ({
        ck: document.cookie,
        ls: localStorage.getItem('ferri_ls'),
      }));
      return got;
    } finally {
      await ctx.close();
    }
  ",
    json!([state, url]),
  );
  let ck = v["ck"].as_str().unwrap_or("");
  let ls = v["ls"].as_str().unwrap_or("");
  // WebKit/BiDi cookie stores may not accept `secure: false` +
  // hostname-only domain for `127.0.0.1` the same way CDP does; treat
  // cookie missing as soft-skip but still require localStorage
  // restoration.
  if c.backend == "cdp-pipe" || c.backend == "cdp-raw" {
    assert!(
      ck.contains("ferri_ck=hello"),
      "cookie from storageState should be visible: {v}"
    );
  }
  assert_eq!(ls, "world", "localStorage from storageState should be restored: {v}");
}

/// `baseURL` → `page.goto('/path')` resolves the relative path
/// against the base. Verified by spinning up a tiny HTTP server that
/// echoes the requested path back into the response body.
pub fn test_context_options_base_url(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // Relative-URL resolution is purely client-side — the backend only
  // sees the already-resolved absolute URL. Works on every backend.
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind baseURL server");
  let port = listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      let mut path = String::new();
      let mut first = true;
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if first {
          if let Some(rest) = line.strip_prefix("GET ") {
            path = rest.split_whitespace().next().unwrap_or("").to_string();
          }
          first = false;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
      }
      let body = format!("<!doctype html><body>PATH:{path}</body>");
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  let base = format!("http://127.0.0.1:{port}");
  let v = c.script_value_with_args(
    r"
    const [base] = args;
    const ctx = await browser.newContext({ baseURL: base });
    try {
      const p = await ctx.newPage();
      await p.goto('/hello/world');
      const body = await p.evaluate(() => document.body.textContent);
      return { body };
    } finally {
      await ctx.close();
    }
  ",
    json!([base]),
  );
  let body = v["body"].as_str().unwrap_or("");
  assert!(
    body.contains("PATH:/hello/world"),
    "baseURL should resolve relative goto path: got {body:?}"
  );
}

/// `serviceWorkers: 'block'` → `navigator.serviceWorker.register` rejects.
/// Works on every backend that supports init scripts (all four).
pub fn test_context_options_service_workers_block(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  // BiDi's `browser.setDownloadBehavior` unrelated; service worker
  // block is purely an init-script monkey-patch that works on every
  // backend with `addInitScript`. Verified via the apply helper's
  // cross-backend path.
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({ serviceWorkers: 'block' });
    try {
      const p = await ctx.newPage();
      await p.goto('data:text/html,<body></body>');
      const result = await p.evaluate(async () => {
        if (!navigator.serviceWorker) return { hasSW: false };
        try {
          await navigator.serviceWorker.register('/sw.js');
          return { hasSW: true, rejected: false };
        } catch (e) {
          return { hasSW: true, rejected: true, msg: String(e.message || e) };
        }
      });
      return result;
    } finally {
      await ctx.close();
    }
  ",
  );
  // Page may not expose `navigator.serviceWorker` on data: URLs in
  // BiDi. Accept either (a) `hasSW: false` (API absent — vacuous
  // pass) or (b) `rejected: true` (the override took).
  if v["hasSW"].as_bool() == Some(true) {
    assert_eq!(
      v["rejected"].as_bool(),
      Some(true),
      "serviceWorkers: 'block' should force navigator.serviceWorker.register to reject: {v}"
    );
  }
}

/// `screen: { width, height }` → `window.screen.{width,height}`
/// reflects the override. CDP only — BiDi / WebKit don't expose a
/// screen-override primitive beyond viewport.
pub fn test_context_options_screen(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({
      viewport: { width: 640, height: 480 },
      screen: { width: 1920, height: 1080 },
    });
    try {
      const p = await ctx.newPage();
      const dims = await p.evaluate(() => ({
        sw: window.screen.width,
        sh: window.screen.height,
      }));
      return dims;
    } finally {
      await ctx.close();
    }
  ",
  );
  let sw = v["sw"].as_u64().unwrap_or(0);
  let sh = v["sh"].as_u64().unwrap_or(0);
  assert_eq!(sw, 1920, "screen.width should reflect override: {v}");
  assert_eq!(sh, 1080, "screen.height should reflect override: {v}");
}

/// `bypassCSP: true` → an inline `<script>` added via `addInitScript`
/// executes even on a page served with `Content-Security-Policy:
/// script-src 'none'`. Without bypass the browser blocks it.
pub fn test_context_options_bypass_csp(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    // BiDi backend returns typed Unsupported for bypassCSP — skip.
    return;
  }
  // Spin up a tiny HTTP server that serves an HTML page with a
  // strict meta CSP. `addInitScript` runs in an isolated world
  // that the CSP's `script-src` header blocks by default; with
  // bypass, it runs and sets a window property.
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind csp server");
  let port = listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    while let Ok((mut stream, _)) = listener.accept() {
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
      }
      let body = "<!doctype html><html><head><meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'none'\"></head><body>csp</body></html>";
      let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
      );
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  let url = format!("http://127.0.0.1:{port}/csp");
  let v = c.script_value_with_args(
    r"
    const [url] = args;
    const ctx = await browser.newContext({ bypassCSP: true });
    try {
      const p = await ctx.newPage();
      await p.addInitScript(() => { window.__fd_csp_bypass = 'yes'; });
      await p.goto(url);
      const flag = await p.evaluate(() => window.__fd_csp_bypass || null);
      return { flag };
    } finally {
      await ctx.close();
    }
  ",
    json!([url]),
  );
  assert_eq!(
    v["flag"].as_str(),
    Some("yes"),
    "bypassCSP should let addInitScript run on a strict-CSP page: {v}"
  );
}

/// `hasTouch: true` → `'ontouchstart' in window`.
pub fn test_context_options_has_touch(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({
      viewport: { width: 800, height: 600 },
      hasTouch: true,
    });
    try {
      const p = await ctx.newPage();
      const touch = await p.evaluate(() => 'ontouchstart' in window || (navigator.maxTouchPoints > 0));
      return { touch };
    } finally {
      await ctx.close();
    }
  ",
  );
  assert_eq!(
    v["touch"].as_bool(),
    Some(true),
    "hasTouch should expose touch APIs to the page: {v}"
  );
}

/// Spawn a multi-connection HTTP Basic-auth server. Each request that
/// carries `Authorization: Basic dXNlcjpwYXNz` (`user:pass`) gets a
/// `200` with `AUTHED` in the body; otherwise it gets a `401` with a
/// `WWW-Authenticate: Basic` challenge and `NOAUTH` body. Returns the
/// bound port. Serves up to `max_conns` connections then exits.
fn spawn_basic_auth_server(max_conns: usize) -> u16 {
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind auth server");
  let port = listener.local_addr().expect("addr").port();
  thread::spawn(move || {
    for _ in 0..max_conns {
      let Ok((mut stream, _)) = listener.accept() else { break };
      let mut reader = BufReader::new(stream.try_clone().expect("clone"));
      let mut authed = false;
      loop {
        let mut line = String::new();
        if reader.read_line(&mut line).unwrap_or(0) == 0 {
          break;
        }
        if line == "\r\n" || line == "\n" {
          break;
        }
        // base64("user:pass") == "dXNlcjpwYXNz"
        if line.to_ascii_lowercase().starts_with("authorization:") && line.contains("dXNlcjpwYXNz") {
          authed = true;
        }
      }
      let resp = if authed {
        let body = "AUTHED";
        format!(
          "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
          body.len(),
          body
        )
      } else {
        let body = "NOAUTH";
        format!(
          "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"r9\"\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}",
          body.len(),
          body
        )
      };
      let _ = stream.write_all(resp.as_bytes());
    }
  });
  port
}

/// `context.setHTTPCredentials({ username, password })` → a navigation
/// that would otherwise 401 succeeds because the backend answers the
/// auth challenge with the stored credentials. Passing `null` then
/// clears them so the next navigation 401s again. Only CDP backends
/// implement the `Fetch.authRequired` hook; BiDi/WebKit return a typed
/// Unsupported, which the test asserts instead.
pub fn test_context_set_http_credentials(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  if c.backend == "bidi" {
    // Firefox/BiDi has no auth-challenge interception command; the
    // setter rejects with a typed Unsupported. Assert that contract.
    let v = c.script_value(
      r"
      const ctx = await browser.newContext({});
      try {
        await ctx.newPage();
        let err = null;
        try { await ctx.setHTTPCredentials({ username: 'user', password: 'pass' }); }
        catch (e) { err = String(e && e.message ? e.message : e); }
        return { err };
      } finally {
        await ctx.close();
      }
    ",
    );
    let err = v["err"].as_str().unwrap_or("");
    assert!(
      err.contains("not supported") || err.contains("Unsupported"),
      "BiDi setHTTPCredentials should reject as Unsupported: {v}"
    );
    return;
  }

  let port = spawn_basic_auth_server(2);
  let url = format!("http://127.0.0.1:{port}/secret");
  let v = c.script_value_with_args(
    r"
    const [url] = args;
    const ctx = await browser.newContext({});
    try {
      const p = await ctx.newPage();
      // With credentials set, the backend's Fetch.authRequired hook
      // answers the challenge → 200 AUTHED. This 200 only occurs when
      // the credentials took effect; a no-credentials top-level nav to
      // this URL aborts with ERR_INVALID_AUTH_CREDENTIALS.
      await ctx.setHTTPCredentials({ username: 'user', password: 'pass' });
      const r = await p.goto(url);
      const status = r ? r.status() : null;
      const body = await p.evaluate(() => document.body.textContent);
      return { status, body };
    } finally {
      await ctx.close();
    }
  ",
    json!([url]),
  );
  // QuickJS JSON-stringifies primitive results, so statuses may arrive
  // as numbers or numeric strings — normalise via serde's as_i64 /
  // string parse.
  let as_status = |val: &serde_json::Value| -> Option<i64> {
    val
      .as_i64()
      .or_else(|| val.as_str().and_then(|s| s.parse::<i64>().ok()))
  };
  assert_eq!(
    as_status(&v["status"]),
    Some(200),
    "nav after setHTTPCredentials should 200: {v}"
  );
  assert!(
    v["body"].as_str().unwrap_or("").contains("AUTHED"),
    "authed body should be served after setHTTPCredentials: {v}"
  );
}

/// `context.setDefaultTimeout(ms)` → a too-short action timeout makes a
/// never-matching `waitForSelector` reject quickly. Observes the
/// timeout error to prove the setter took effect through the shared
/// `Arc<AtomicU64>` (the method takes `&self`, not `&mut self`).
pub fn test_context_set_default_timeout(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({});
    try {
      // Setter takes effect via interior mutability on a shared handle.
      ctx.setDefaultTimeout(50);
      ctx.setDefaultNavigationTimeout(50);
      const p = await ctx.newPage();
      await p.goto('data:text/html,<body>timeout-probe</body>');
      let err = null;
      try {
        await p.waitForSelector('#never-ever', { timeout: 50 });
      } catch (e) {
        err = String(e && e.message ? e.message : e);
      }
      return { err };
    } finally {
      await ctx.close();
    }
  ",
  );
  let err = v["err"].as_str().unwrap_or("");
  assert!(
    err.to_ascii_lowercase().contains("timeout") || err.to_ascii_lowercase().contains("timed out"),
    "waitForSelector should time out: {v}"
  );
}

/// `context.isClosed()` flips from `false` to `true` across `close()`,
/// and `context.browser()` returns the parent Browser handle.
pub fn test_context_is_closed_and_browser(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({});
    const before = await ctx.isClosed();
    const hasBrowser = ctx.browser() != null;
    // browser() should hand back a usable Browser (version() is sync-ish).
    const ver = ctx.browser() != null ? String(ctx.browser().version()) : null;
    await ctx.close();
    const after = await ctx.isClosed();
    return { before, hasBrowser, after, verNonEmpty: ver != null && ver.length > 0 };
  ",
  );
  assert_eq!(
    v["before"].as_bool(),
    Some(false),
    "isClosed() should be false before close: {v}"
  );
  assert_eq!(
    v["hasBrowser"].as_bool(),
    Some(true),
    "browser() should return the parent Browser: {v}"
  );
  assert_eq!(
    v["verNonEmpty"].as_bool(),
    Some(true),
    "browser().version() should be a non-empty string: {v}"
  );
  assert_eq!(
    v["after"].as_bool(),
    Some(true),
    "isClosed() should be true after close: {v}"
  );
}

/// `context.route(url, handler)` fulfils a matched request for every
/// page in the context, then `context.unroute(url)` removes it.
pub fn test_context_route_and_unroute(c: &mut McpClient) {
  if skip_if_no_new_context(c) {
    return;
  }
  let v = c.script_value(
    r"
    const ctx = await browser.newContext({});
    try {
      const p = await ctx.newPage();
      const matcher = 'https://ferri.test/**';
      await ctx.route(matcher, (route) => {
        route.fulfill({ status: 200, contentType: 'text/html', body: '<body>ROUTED</body>' });
      });
      await p.goto('https://ferri.test/page');
      const routed = await p.evaluate(() => document.body.textContent);
      await ctx.unroute(matcher);
      return { routed };
    } finally {
      await ctx.close();
    }
  ",
  );
  assert!(
    v["routed"].as_str().unwrap_or("").contains("ROUTED"),
    "context.route should fulfil the matched request: {v}"
  );
}