eoka 0.13.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
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
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
//! A loopback CDP endpoint for third-party clients (Playwright, Puppeteer,
//! Browser Use, ...) in front of an eoka-launched Chrome.
//!
//! Each client connection gets its own upstream WebSocket to Chrome, so ids
//! never collide with eoka's own transport. `/json/version` and `/json/list`
//! are answered with URLs that point back at the proxy.
//!
//! Security: the listener binds to 127.0.0.1 only, requests must use a
//! loopback `Host` (anti DNS rebinding) and upgrades with a browser `Origin`
//! header are refused, so a web page cannot drive the browser through the
//! proxy. WebSocket paths carry a random token, which `/json/version` hands
//! to any local process, as Chrome's own port does: local processes are
//! trusted.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;

use crate::util::LockExt;

mod runtime;
use tokio::task::{JoinHandle, JoinSet};
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::Message;

use crate::error::{Error, Result};

const MAX_MESSAGE_BYTES: usize = 256 * 1024 * 1024;
const HEADER_LIMIT: usize = 16 * 1024;
const HEADER_TIMEOUT: Duration = Duration::from_secs(5);

/// Options for [`crate::Browser::serve_cdp`].
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CdpProxyOptions {
    /// Append one JSON line per CDP message (direction, kind, id, method,
    /// session) to this file. Parameters and results are never logged.
    pub log_path: Option<PathBuf>,
    /// Forward traffic unchanged: no fingerprint setup on client pages and no
    /// `sourceURL` stripping.
    pub pass_through: bool,
    /// How client `Runtime.enable` calls are handled.
    pub runtime: RuntimeMode,
}

/// Handling of a client's `Runtime.enable`, which makes Chrome serialize
/// console arguments in a way pages can detect.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RuntimeMode {
    /// Forward it to Chrome unchanged.
    #[default]
    Forward,
    /// Answer it locally and send no context events. Enough for clients that
    /// evaluate without context ids, such as Browser Use's harness.
    Ack,
    /// Answer it locally and synthesize the execution-context events
    /// Playwright and Puppeteer wait for. Console and exception events are
    /// not delivered. Experimental.
    Emulate,
}

/// Attaches eoka's own session to a page a client opened and gives it
/// eoka's identity (fingerprint, evasions), so the page keeps it after the
/// client disconnects. Does nothing when eoka already
/// owns the target or it is not a page. The flag says whether the page has
/// not loaded yet. A failed setup is undone, so a later attach can retry.
pub(crate) type Adopter =
    Arc<dyn Fn(String, bool) -> futures_util::future::BoxFuture<'static, Result<()>> + Send + Sync>;

/// Upper bound on holding a client's commands while eoka sets up its page.
const ADOPT_TIMEOUT: Duration = Duration::from_secs(10);

/// A running loopback CDP endpoint. Dropping it stops the listener and
/// closes every proxied client connection.
#[derive(Debug)]
pub struct CdpProxy {
    ws_url: String,
    http_url: String,
    task: JoinHandle<()>,
}

impl CdpProxy {
    /// Browser-level WebSocket URL, for `connectOverCDP`, `puppeteer.connect`
    /// (`browserWSEndpoint`) or Browser Use's `cdp_url`.
    pub fn ws_url(&self) -> &str {
        &self.ws_url
    }

    /// HTTP base URL serving `/json/version` and `/json/list`.
    pub fn http_url(&self) -> &str {
        &self.http_url
    }

    /// Stop the listener and every proxied connection.
    pub fn close(self) {}
}

impl Drop for CdpProxy {
    fn drop(&mut self) {
        self.task.abort();
    }
}

struct Shared {
    upstream_host: String,
    upstream_port: u16,
    upstream_browser_path: String,
    token: String,
    port: u16,
    log: Option<mpsc::Sender<String>>,
    started: Instant,
    adopter: Option<Adopter>,
    /// No adoption, rewriting or emulation, so page-level endpoints are allowed.
    pass_through: bool,
    /// Per-endpoint name for Playwright's `UtilityScript` class, which
    /// otherwise shows in page-visible stack frames; random so it is no
    /// signature of its own.
    utility_alias: String,
    runtime: RuntimeMode,
}

pub(crate) async fn serve(
    browser_endpoint: &str,
    options: CdpProxyOptions,
    adopter: Option<Adopter>,
) -> Result<CdpProxy> {
    let rest = browser_endpoint
        .strip_prefix("ws://")
        .ok_or_else(|| Error::invalid_argument("CDP proxy needs a ws:// browser endpoint"))?;
    let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
    let (host, port) = authority
        .rsplit_once(':')
        .and_then(|(h, p)| Some((h.trim_matches(['[', ']']).to_owned(), p.parse().ok()?)))
        .ok_or_else(|| Error::invalid_argument("CDP proxy cannot parse the browser endpoint"))?;
    let listener = TcpListener::bind(("127.0.0.1", 0))
        .await
        .map_err(|e| Error::transport_io("bind CDP proxy", e))?;
    let local = listener
        .local_addr()
        .map_err(|e| Error::transport_io("CDP proxy address", e))?;
    let token = random_token()?;
    let log = match options.log_path {
        Some(path) => Some(spawn_logger(&path)?),
        None => None,
    };
    let shared = Arc::new(Shared {
        upstream_host: host,
        upstream_port: port,
        upstream_browser_path: path.to_owned(),
        token,
        port: local.port(),
        log,
        started: Instant::now(),
        adopter: if options.pass_through { None } else { adopter },
        pass_through: options.pass_through,
        utility_alias: identifier_alias(),
        runtime: if options.pass_through {
            RuntimeMode::Forward
        } else {
            options.runtime
        },
    });
    let ws_url = shared.proxy_ws(&shared.upstream_browser_path);
    let http_url = format!("http://127.0.0.1:{}", local.port());
    let task = tokio::spawn(accept_loop(listener, shared));
    Ok(CdpProxy {
        ws_url,
        http_url,
        task,
    })
}

impl Shared {
    fn proxy_ws(&self, upstream_path: &str) -> String {
        format!(
            "ws://127.0.0.1:{}/{}{}",
            self.port, self.token, upstream_path
        )
    }

    fn log(&self, line: Value) {
        if let Some(log) = &self.log {
            let mut line = line;
            line["t"] = u64::try_from(self.started.elapsed().as_millis())
                .unwrap_or(u64::MAX)
                .into();
            let _ = log.try_send(line.to_string());
        }
    }
}

fn spawn_logger(path: &std::path::Path) -> Result<mpsc::Sender<String>> {
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(|e| Error::transport_io("open CDP proxy log", e))?;
    let (sender, mut receiver) = mpsc::channel::<String>(65_536);
    std::thread::spawn(move || {
        use std::io::Write;
        let mut file = std::io::BufWriter::new(file);
        while let Some(line) = receiver.blocking_recv() {
            if writeln!(file, "{line}")
                .and_then(|()| file.flush())
                .is_err()
            {
                break;
            }
        }
    });
    Ok(sender)
}

fn random_token() -> Result<String> {
    let mut bytes = [0u8; 16];
    #[cfg(unix)]
    {
        use std::io::Read;
        std::fs::File::open("/dev/urandom")
            .and_then(|mut f| f.read_exact(&mut bytes))
            .map_err(|e| Error::transport_io("read /dev/urandom", e))?;
    }
    #[cfg(not(unix))]
    {
        use std::hash::{BuildHasher, Hasher};
        for chunk in bytes.chunks_mut(8) {
            let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
            hasher.write_u128(
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos(),
            );
            chunk.copy_from_slice(&hasher.finish().to_le_bytes()[..chunk.len()]);
        }
    }
    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

async fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
    let mut connections = JoinSet::new();
    loop {
        let stream = match listener.accept().await {
            Ok((stream, _)) => stream,
            Err(error) => {
                // Persistent errors (EMFILE) would otherwise spin.
                tracing::debug!("CDP proxy accept failed: {error}");
                tokio::time::sleep(Duration::from_millis(50)).await;
                continue;
            }
        };
        while connections.try_join_next().is_some() {}
        let shared = Arc::clone(&shared);
        connections.spawn(async move {
            if let Err(error) = handle(stream, &shared).await {
                tracing::debug!("CDP proxy connection ended: {error}");
            }
        });
    }
}

struct Request {
    path: String,
    host: Option<String>,
    origin: Option<String>,
    upgrade: bool,
    head_len: usize,
}

async fn read_head(stream: &TcpStream) -> Result<Request> {
    let deadline = tokio::time::Instant::now() + HEADER_TIMEOUT;
    let mut buffer = vec![0u8; HEADER_LIMIT];
    loop {
        let n = tokio::time::timeout_at(deadline, stream.peek(&mut buffer))
            .await
            .map_err(|_| Error::transport("CDP proxy request header timed out"))?
            .map_err(|e| Error::transport_io("CDP proxy read", e))?;
        if n == 0 {
            return Err(Error::transport("CDP proxy client closed"));
        }
        if let Some(end) = find(&buffer[..n], b"\r\n\r\n") {
            return parse_head(&buffer[..end], end + 4);
        }
        if n == HEADER_LIMIT {
            return Err(Error::transport("CDP proxy request header too large"));
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

fn parse_head(head: &[u8], head_len: usize) -> Result<Request> {
    let text = std::str::from_utf8(head).map_err(|_| Error::transport("non-UTF-8 request"))?;
    let mut lines = text.split("\r\n");
    let request_line = lines.next().unwrap_or_default();
    let mut parts = request_line.split(' ');
    let (Some("GET"), Some(path)) = (parts.next(), parts.next()) else {
        return Err(Error::transport("CDP proxy accepts only GET"));
    };
    let mut request = Request {
        path: path.to_owned(),
        host: None,
        origin: None,
        upgrade: false,
        head_len,
    };
    for line in lines {
        let Some((name, value)) = line.split_once(':') else {
            continue;
        };
        let value = value.trim();
        match name.trim().to_ascii_lowercase().as_str() {
            "host" => request.host = Some(value.to_owned()),
            "origin" => request.origin = Some(value.to_owned()),
            "upgrade" => request.upgrade = value.eq_ignore_ascii_case("websocket"),
            _ => {}
        }
    }
    Ok(request)
}

fn loopback_host(host: Option<&str>) -> bool {
    let Some(host) = host else { return false };
    let name = match host.rsplit_once(':') {
        Some((name, port)) if port.chars().all(|c| c.is_ascii_digit()) => name,
        _ => host,
    };
    matches!(name, "127.0.0.1" | "localhost" | "[::1]")
}

async fn respond(mut stream: TcpStream, head_len: usize, status: &str, body: &str) -> Result<()> {
    use tokio::io::AsyncReadExt;
    let mut discard = vec![0u8; head_len];
    let _ = stream.read_exact(&mut discard).await;
    let response = format!(
        "HTTP/1.1 {status}\r\nContent-Type: application/json; charset=UTF-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    stream
        .write_all(response.as_bytes())
        .await
        .map_err(|e| Error::transport_io("CDP proxy write", e))?;
    let _ = stream.shutdown().await;
    Ok(())
}

async fn handle(stream: TcpStream, shared: &Arc<Shared>) -> Result<()> {
    let request = read_head(&stream).await?;
    if !loopback_host(request.host.as_deref()) {
        shared.log(serde_json::json!({"kind":"refused","reason":"host","path":request.path}));
        return respond(stream, request.head_len, "403 Forbidden", "{}").await;
    }
    let token_prefix = format!("/{}", shared.token);
    let path = request.path.strip_prefix(&token_prefix).map(str::to_owned);
    if request.upgrade {
        // Page-level endpoints would bypass adoption and Runtime emulation,
        // which key on the browser connection's sessions.
        let allowed = if shared.pass_through {
            "/devtools/"
        } else {
            "/devtools/browser/"
        };
        let Some(upstream_path) = path.filter(|p| p.starts_with(allowed)) else {
            shared.log(serde_json::json!({"kind":"refused","reason":"token"}));
            return respond(stream, request.head_len, "403 Forbidden", "{}").await;
        };
        if request.origin.is_some() {
            shared.log(
                serde_json::json!({"kind":"refused","reason":"origin","origin":request.origin}),
            );
            return respond(stream, request.head_len, "403 Forbidden", "{}").await;
        }
        return proxy_ws(stream, shared, &upstream_path).await;
    }
    let path = path.unwrap_or(request.path.clone());
    let route = path.trim_end_matches('/');
    let body = match route.split('?').next().unwrap_or_default() {
        "/json/version" => rewrite_json(shared, "/json/version").await?,
        "/json" | "/json/list" => rewrite_json(shared, "/json/list").await?,
        _ => return respond(stream, request.head_len, "404 Not Found", "{}").await,
    };
    respond(stream, request.head_len, "200 OK", &body).await
}

async fn rewrite_json(shared: &Arc<Shared>, path: &'static str) -> Result<String> {
    let (host, port) = (shared.upstream_host.clone(), shared.upstream_port);
    let text = tokio::task::spawn_blocking(move || super::discover::http_get(&host, port, path))
        .await
        .map_err(|_| Error::transport("CDP proxy discovery task failed"))??;
    let mut value: Value =
        serde_json::from_str(&text).map_err(|e| Error::decode(format!("{path}: {e}")))?;
    let pages_allowed = shared.pass_through;
    let rewrite = |entry: &mut Value| {
        if let Some(url) = entry.get("webSocketDebuggerUrl").and_then(Value::as_str) {
            if let Some(index) = url.find("/devtools/") {
                let path = &url[index..];
                if path.starts_with("/devtools/browser/") || pages_allowed {
                    entry["webSocketDebuggerUrl"] = shared.proxy_ws(path).into();
                } else if let Some(object) = entry.as_object_mut() {
                    object.remove("webSocketDebuggerUrl");
                }
            }
        }
        if let Some(object) = entry.as_object_mut() {
            object.remove("devtoolsFrontendUrl");
        }
    };
    match &mut value {
        Value::Array(entries) => entries.iter_mut().for_each(rewrite),
        entry => rewrite(entry),
    }
    Ok(value.to_string())
}

fn ws_config() -> WebSocketConfig {
    WebSocketConfig::default()
        .max_message_size(Some(MAX_MESSAGE_BYTES))
        .max_frame_size(Some(MAX_MESSAGE_BYTES))
}

/// Client messages held per session while eoka adopts that session's page.
/// A session is held while it has an entry.
type Held = Arc<std::sync::Mutex<HashMap<String, Vec<Message>>>>;

/// Chrome-to-client messages queued per connection; a slow client slows the
/// upstream reader instead of growing the queue.
const CLIENT_QUEUE: usize = 1024;
/// How long queued replies and close frames get to drain once one side ends.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(1);

async fn proxy_ws(stream: TcpStream, shared: &Arc<Shared>, upstream_path: &str) -> Result<()> {
    let client = tokio_tungstenite::accept_async_with_config(stream, Some(ws_config()))
        .await
        .map_err(|e| Error::transport(format!("CDP proxy handshake: {e}")))?;
    let upstream_url = format!(
        "ws://{}:{}{}",
        if shared.upstream_host.contains(':') {
            format!("[{}]", shared.upstream_host)
        } else {
            shared.upstream_host.clone()
        },
        shared.upstream_port,
        upstream_path
    );
    let (upstream, _) =
        tokio_tungstenite::connect_async_with_config(&upstream_url, Some(ws_config()), false)
            .await
            .map_err(|e| Error::transport(format!("CDP proxy upstream: {e}")))?;
    let connection = fastrand::u32(..);
    shared.log(serde_json::json!({"kind":"open","conn":connection,"path":upstream_path}));
    let (mut client_tx, mut client_rx) = client.split();
    let (mut upstream_tx, mut upstream_rx) = upstream.split();
    let (to_client, mut client_queue) = mpsc::channel::<Message>(CLIENT_QUEUE);
    // Client-to-Chrome traffic is commands, which Chrome reads promptly; the
    // client cannot outrun its own replies.
    let (to_upstream, mut upstream_queue) = mpsc::unbounded_channel::<Message>();
    let own = runtime::Own::new(to_upstream.clone());
    let emulator = (shared.runtime == RuntimeMode::Emulate)
        .then(|| runtime::Emulator::new(Arc::clone(&own), to_client.clone()));
    let methods: Methods = Arc::default();
    // Client `Target.attachToTarget` ids, to adopt the target its reply names.
    let attaches: Arc<std::sync::Mutex<HashMap<u64, String>>> = Arc::default();
    let held: Held = Arc::default();
    let mut writers = JoinSet::new();
    let log_shared = Arc::clone(shared);
    writers.spawn(async move {
        while let Some(message) = client_queue.recv().await {
            let close = message.is_close();
            if let Message::Text(text) = &message {
                log_to_client(&log_shared, connection, text);
            }
            if client_tx.send(message).await.is_err() || close {
                break;
            }
        }
    });
    writers.spawn(async move {
        while let Some(message) = upstream_queue.recv().await {
            let close = message.is_close();
            if upstream_tx.send(message).await.is_err() || close {
                break;
            }
        }
    });
    let mut readers = JoinSet::new();
    {
        let shared = Arc::clone(shared);
        let methods = Arc::clone(&methods);
        let attaches = Arc::clone(&attaches);
        let held = Arc::clone(&held);
        let to_client = to_client.clone();
        let to_upstream = to_upstream.clone();
        let emulator = emulator.clone();
        readers.spawn(async move {
            while let Some(Ok(message)) = client_rx.next().await {
                let close = message.is_close();
                let mut message = message;
                if let Message::Text(text) = &message {
                    if let Ok(value) = serde_json::from_str::<Value>(text) {
                        if shared.runtime == RuntimeMode::Ack && value["method"] == "Runtime.enable"
                        {
                            let reply = Message::text(runtime::empty_reply(&value));
                            if to_client.send(reply).await.is_err() {
                                break;
                            }
                            continue;
                        }
                        if let Some(emulator) = &emulator {
                            if let runtime::Client::Answered = emulator.on_client(&value).await {
                                continue;
                            }
                        }
                        log_command(&shared, connection, &value, &methods);
                        if value["method"] == "Target.attachToTarget" {
                            if let (Some(id), Some(target)) =
                                (value["id"].as_u64(), value["params"]["targetId"].as_str())
                            {
                                attaches.lock_unpoisoned().insert(id, target.to_owned());
                            }
                        }
                        if !shared.pass_through {
                            if let Some(rewritten) = strip_source_url(&value, &shared.utility_alias)
                            {
                                message = Message::text(rewritten);
                            }
                        }
                        if let Some(session) = value["sessionId"].as_str() {
                            match hold(&held, session, message) {
                                Some(free) => message = free,
                                None => continue,
                            }
                        }
                    }
                }
                if to_upstream.send(message).is_err() || close {
                    break;
                }
            }
        });
    }
    {
        let shared = Arc::clone(shared);
        let to_client = to_client.clone();
        let emulator = emulator.clone();
        readers.spawn(async move {
            while let Some(Ok(message)) = upstream_rx.next().await {
                let close = message.is_close();
                let mut observed = None;
                if let Message::Text(text) = &message {
                    if let Ok(value) = serde_json::from_str::<Value>(text) {
                        if own.take(&value) {
                            continue;
                        }
                        if value["method"] == "Target.attachedToTarget" {
                            let params = &value["params"];
                            if params["targetInfo"]["type"] == "page" {
                                if let (Some(session), Some(target)) = (
                                    params["sessionId"].as_str(),
                                    params["targetInfo"]["targetId"].as_str(),
                                ) {
                                    let fresh = params["waitingForDebugger"] == true;
                                    adopt(&shared, &held, &to_upstream, session, target, fresh);
                                }
                            }
                        } else if let Some(id) = value["id"].as_u64() {
                            let target = attaches.lock_unpoisoned().remove(&id);
                            if let (Some(target), Some(session)) =
                                (target, value["result"]["sessionId"].as_str())
                            {
                                adopt(&shared, &held, &to_upstream, session, &target, false);
                            }
                        }
                        log_upstream(&shared, connection, &value, &methods);
                        observed = Some(value);
                    }
                }
                if to_client.send(message).await.is_err() || close {
                    break;
                }
                if let (Some(emulator), Some(value)) = (&emulator, &observed) {
                    emulator.on_upstream(value).await;
                }
            }
        });
    }
    drop(to_client);
    readers.join_next().await;
    // A reader forwards the close frame it saw; let the writers send it and
    // anything queued before it.
    let _ = tokio::time::timeout(DRAIN_TIMEOUT, async {
        while writers.join_next().await.is_some() {}
    })
    .await;
    if let Some(emulator) = &emulator {
        emulator.shutdown();
    }
    shared.log(serde_json::json!({"kind":"close","conn":connection}));
    Ok(())
}

/// Queue a client message while its session is held; give it back otherwise.
fn hold(held: &Held, session: &str, message: Message) -> Option<Message> {
    match held.lock_unpoisoned().get_mut(session) {
        Some(queue) => {
            queue.push(message);
            None
        }
        None => Some(message),
    }
}

/// Start adopting a client's page and hold that session's client commands
/// until it is done (at most [`ADOPT_TIMEOUT`]), so eoka's setup lands before
/// the client releases or navigates the page. Other sessions are not held.
fn adopt(
    shared: &Arc<Shared>,
    held: &Held,
    to_upstream: &mpsc::UnboundedSender<Message>,
    session: &str,
    target: &str,
    fresh: bool,
) {
    let Some(adopter) = shared.adopter.clone() else {
        return;
    };
    {
        let mut held = held.lock_unpoisoned();
        if held.contains_key(session) {
            return;
        }
        held.insert(session.to_owned(), Vec::new());
    }
    let (shared, held, to_upstream, session) = (
        Arc::clone(shared),
        Arc::clone(held),
        to_upstream.clone(),
        session.to_owned(),
    );
    // The setup itself runs to completion (each step has the CDP timeout) and
    // undoes itself on failure; only the client's wait is bounded.
    let mut setup = tokio::spawn(adopter(target.to_owned(), fresh));
    let target = target.to_owned();
    tokio::spawn(async move {
        let failure = match tokio::time::timeout(ADOPT_TIMEOUT, &mut setup).await {
            Ok(Ok(Ok(()))) => None,
            Ok(Ok(Err(error))) => Some(error.to_string()),
            Ok(Err(_)) => Some("setup task failed".to_owned()),
            Err(_) => Some("timed out".to_owned()),
        };
        if let Some(error) = failure {
            tracing::debug!("CDP proxy could not set up page {target}: {error}");
            shared.log(serde_json::json!({"kind":"adopt-error","error":error}));
        }
        // Release in order, under the lock the client reader checks.
        let mut held = held.lock_unpoisoned();
        for message in held.remove(&session).unwrap_or_default() {
            let _ = to_upstream.send(message);
        }
    });
}

/// A short identifier that looks like minified code: a letter, then letters
/// or digits.
fn identifier_alias() -> String {
    const LETTERS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const REST: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let mut alias = String::new();
    alias.push(char::from(LETTERS[fastrand::usize(..LETTERS.len())]));
    for _ in 0..3 {
        alias.push(char::from(REST[fastrand::usize(..REST.len())]));
    }
    alias
}

/// Remove `//# sourceURL=...` markers (Puppeteer's `pptr:`) and rename
/// Playwright's `UtilityScript`, which a page can read from `Error().stack`.
fn strip_source_url(value: &Value, alias: &str) -> Option<String> {
    let field = match value["method"].as_str()? {
        "Runtime.evaluate" => "expression",
        "Runtime.callFunctionOn" => "functionDeclaration",
        _ => return None,
    };
    let source = value["params"][field].as_str()?;
    let marker = source.contains("//# sourceURL=");
    let utility = source.contains("UtilityScript") && !source.contains(alias);
    if !marker && !utility {
        return None;
    }
    let mut rewritten: String = if marker {
        source
            .split_inclusive('\n')
            .filter(|line| !line.trim_start().starts_with("//# sourceURL="))
            .collect()
    } else {
        source.to_owned()
    };
    if utility {
        rewritten = rewritten.replace("UtilityScript", alias);
    }
    if rewritten == source {
        return None;
    }
    let mut value = value.clone();
    value["params"][field] = rewritten.into();
    Some(value.to_string())
}

type Methods = Arc<std::sync::Mutex<HashMap<u64, String>>>;

fn log_command(shared: &Shared, connection: u32, value: &Value, methods: &Methods) {
    if shared.log.is_none() {
        return;
    }
    let method = value["method"].as_str().unwrap_or_default();
    if let Some(id) = value["id"].as_u64() {
        methods.lock_unpoisoned().insert(id, method.to_owned());
    }
    shared.log(serde_json::json!({
        "conn": connection, "kind": "cmd", "id": value["id"], "method": method,
        "session": value["sessionId"],
    }));
}

fn log_upstream(shared: &Shared, connection: u32, value: &Value, methods: &Methods) {
    if shared.log.is_none() {
        return;
    }
    if let Some(id) = value["id"].as_u64() {
        let method = methods.lock_unpoisoned().remove(&id);
        shared.log(serde_json::json!({
            "conn": connection, "kind": "resp", "id": id, "method": method,
            "error": value["error"]["message"], "session": value["sessionId"],
        }));
    } else {
        shared.log(serde_json::json!({
            "conn": connection, "kind": "event", "method": value["method"],
            "session": value["sessionId"],
        }));
    }
}

fn log_to_client(shared: &Shared, connection: u32, text: &str) {
    if shared.log.is_none() {
        return;
    }
    if let Ok(value) = serde_json::from_str::<Value>(text) {
        shared.log(serde_json::json!({
            "conn": connection, "kind": "to-client", "id": value["id"],
            "method": value["method"], "session": value["sessionId"],
            "context": value["params"]["context"]["id"],
            "frame": value["params"]["context"]["auxData"]["frameId"],
            "name": value["params"]["context"]["name"],
        }));
    }
}

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

    #[test]
    fn held_sessions_queue_and_other_sessions_pass() {
        let held: Held = Arc::default();
        held.lock_unpoisoned().insert("A".into(), Vec::new());
        assert!(hold(&held, "A", Message::text("1")).is_none());
        assert!(hold(&held, "B", Message::text("2")).is_some());
        assert_eq!(held.lock_unpoisoned()["A"], [Message::text("1")]);
    }

    #[test]
    fn loopback_hosts_only() {
        assert!(loopback_host(Some("127.0.0.1:9222")));
        assert!(loopback_host(Some("localhost")));
        assert!(loopback_host(Some("[::1]:80")));
        assert!(!loopback_host(Some("evil.example:9222")));
        assert!(!loopback_host(Some("127.0.0.1.evil.example")));
        assert!(!loopback_host(None));
    }

    #[test]
    fn strips_source_url_markers_only_from_scripts() {
        let pptr = r#"{"id":1,"method":"Runtime.callFunctionOn","params":{"functionDeclaration":"() => 1\n//# sourceURL=pptr:evaluate;x\n"}}"#;
        let parse = |text: &str| serde_json::from_str::<Value>(text).unwrap();
        let out = parse(&strip_source_url(&parse(pptr), "uS9x").unwrap());
        assert_eq!(out["params"]["functionDeclaration"], "() => 1\n");
        let other =
            r#"{"id":2,"method":"Page.navigate","params":{"url":"https://x/?sourceURL=1"}}"#;
        assert!(strip_source_url(&parse(other), "uS9x").is_none());
        let plain =
            r#"{"id":3,"method":"Runtime.evaluate","params":{"expression":"'sourceURL='"}}"#;
        assert!(strip_source_url(&parse(plain), "uS9x").is_none());
        let pw = r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"class UtilityScript {} new UtilityScript()"}}"#;
        let out = parse(&strip_source_url(&parse(pw), "uS9x").unwrap());
        assert_eq!(out["params"]["expression"], "class uS9x {} new uS9x()");
    }

    /// A fake Chrome: answers /json/version and accepts one WebSocket that
    /// emits Target.attachedToTarget, then records what it receives.
    async fn fake_chrome() -> (u16, mpsc::UnboundedReceiver<Value>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let (seen, received) = mpsc::unbounded_channel();
        tokio::spawn(async move {
            loop {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut peek = [0u8; 64];
                let n = stream.peek(&mut peek).await.unwrap();
                if peek[..n].starts_with(b"GET /json") {
                    let mut request = [0u8; 1024];
                    let _ = stream.read(&mut request).await;
                    let body = format!(
                        r#"{{"Browser":"Chrome/156","webSocketDebuggerUrl":"ws://127.0.0.1:{port}/devtools/browser/abc"}}"#
                    );
                    let reply = format!(
                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    stream.write_all(reply.as_bytes()).await.unwrap();
                    continue;
                }
                let seen = seen.clone();
                tokio::spawn(async move {
                    let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
                    while let Some(Ok(Message::Text(text))) = ws.next().await {
                        let value: Value = serde_json::from_str(&text).unwrap();
                        if value["method"] == "Target.setAutoAttach" {
                            let event = serde_json::json!({"method":"Target.attachedToTarget","params":{"sessionId":"S1","targetInfo":{"targetId":"T1","type":"page"},"waitingForDebugger":true}});
                            ws.send(Message::text(event.to_string())).await.unwrap();
                        }
                        if let Some(id) = value["id"].as_u64() {
                            let result = match value["method"].as_str() {
                                Some("Page.getFrameTree") => {
                                    serde_json::json!({"frameTree":{"frame":{"id":"F1","securityOrigin":"http://x"}}})
                                }
                                Some("Runtime.evaluate") => {
                                    serde_json::json!({"result":{"objectId":"99.7.1"}})
                                }
                                _ => serde_json::json!({}),
                            };
                            let reply = serde_json::json!({"id": id, "result": result, "sessionId": value["sessionId"]});
                            ws.send(Message::text(reply.to_string())).await.unwrap();
                        }
                        let _ = seen.send(value);
                    }
                });
            }
        });
        (port, received)
    }

    async fn raw_get(port: u16, path: &str, extra: &str) -> String {
        let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
        let request = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n{extra}\r\n");
        stream.write_all(request.as_bytes()).await.unwrap();
        let mut response = vec![0u8; 256];
        let n = stream.read(&mut response).await.unwrap();
        String::from_utf8_lossy(&response[..n]).into_owned()
    }

    #[tokio::test]
    async fn proxy_guards_the_endpoint_and_sets_up_client_pages() {
        let (port, mut received) = fake_chrome().await;
        let (adopted_tx, mut adopted_rx) = mpsc::unbounded_channel::<(String, bool)>();
        let adopter: Adopter = Arc::new(move |target, fresh| {
            let adopted_tx = adopted_tx.clone();
            Box::pin(async move {
                tokio::time::sleep(Duration::from_millis(200)).await;
                let _ = adopted_tx.send((target, fresh));
                Ok(())
            })
        });
        let proxy = serve(
            &format!("ws://127.0.0.1:{port}/devtools/browser/abc"),
            CdpProxyOptions::default(),
            Some(adopter),
        )
        .await
        .unwrap();
        let proxy_port: u16 = proxy
            .http_url()
            .rsplit(':')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        let path = proxy
            .ws_url()
            .split_once(&format!(":{proxy_port}"))
            .unwrap()
            .1
            .to_owned();

        // A browser page (Origin header) and a wrong token are refused.
        assert!(
            raw_get(proxy_port, &path, "Origin: https://evil.example\r\n")
                .await
                .starts_with("HTTP/1.1 403")
        );
        assert!(raw_get(proxy_port, "/devtools/browser/abc", "")
            .await
            .starts_with("HTTP/1.1 403"));

        // /json/version points back at the proxy.
        let version = tokio::task::spawn_blocking(move || {
            super::super::discover::http_get("127.0.0.1", proxy_port, "/json/version")
        })
        .await
        .unwrap()
        .unwrap();
        assert!(version.contains(proxy.ws_url()), "{version}");

        // eoka adopts a client's page before the client's own commands on it
        // reach Chrome.
        let (mut client, _) = tokio_tungstenite::connect_async(proxy.ws_url())
            .await
            .unwrap();
        client
            .send(Message::text(
                r#"{"id":1,"method":"Target.setAutoAttach","params":{}}"#,
            ))
            .await
            .unwrap();
        let mut client_saw = Vec::new();
        while client_saw.len() < 2 {
            if let Some(Ok(Message::Text(text))) = client.next().await {
                client_saw.push(serde_json::from_str::<Value>(&text).unwrap());
            }
        }
        client
            .send(Message::text(
                r#"{"id":2,"method":"Runtime.runIfWaitingForDebugger","sessionId":"S1"}"#,
            ))
            .await
            .unwrap();
        assert_eq!(
            received.recv().await.unwrap()["method"],
            "Target.setAutoAttach"
        );
        let release = received.recv().await.unwrap();
        assert_eq!(release["method"], "Runtime.runIfWaitingForDebugger");
        let (target, fresh) = adopted_rx
            .try_recv()
            .expect("adoption finished before the release was forwarded");
        assert_eq!((target.as_str(), fresh), ("T1", true));
        let reply = tokio::time::timeout(Duration::from_secs(2), client.next())
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        let reply: Value = serde_json::from_str(reply.to_text().unwrap()).unwrap();
        assert_eq!(reply["id"], 2);
    }

    #[tokio::test]
    async fn emulated_runtime_enable_never_reaches_chrome() {
        let (port, mut received) = fake_chrome().await;
        let options = CdpProxyOptions {
            runtime: RuntimeMode::Emulate,
            ..Default::default()
        };
        let proxy = serve(
            &format!("ws://127.0.0.1:{port}/devtools/browser/abc"),
            options,
            None,
        )
        .await
        .unwrap();
        let (mut client, _) = tokio_tungstenite::connect_async(proxy.ws_url())
            .await
            .unwrap();
        client
            .send(Message::text(
                r#"{"id":5,"method":"Runtime.enable","sessionId":"S1"}"#,
            ))
            .await
            .unwrap();
        let mut seen = Vec::new();
        while seen.len() < 2 {
            let message = tokio::time::timeout(Duration::from_secs(5), client.next())
                .await
                .unwrap()
                .unwrap()
                .unwrap();
            seen.push(serde_json::from_str::<Value>(message.to_text().unwrap()).unwrap());
        }
        assert_eq!(seen[0]["id"], 5, "answered locally: {}", seen[0]);
        assert_eq!(seen[1]["method"], "Runtime.executionContextCreated");
        let context = &seen[1]["params"]["context"];
        assert_eq!(context["id"], 7);
        assert_eq!(context["auxData"]["frameId"], "F1");
        assert_eq!(context["auxData"]["isDefault"], true);
        let mut chrome_saw = Vec::new();
        while let Ok(value) = received.try_recv() {
            chrome_saw.push(value["method"].as_str().unwrap_or_default().to_owned());
        }
        assert!(
            !chrome_saw.iter().any(|m| m == "Runtime.enable"),
            "{chrome_saw:?}"
        );
        assert!(
            chrome_saw.iter().any(|m| m == "Page.getFrameTree"),
            "{chrome_saw:?}"
        );
    }
}