proofsheet-core 0.1.10

Core driver for proofsheet: CDP browser control, deterministic capture, receipts.
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
//! Launching a headless Chromium and speaking the DevTools Protocol to it.

use std::io::{BufRead, BufReader, Read};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::{json, Value};

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

/// Where to look for a browser binary when the caller does not name one.
const CANDIDATES: &[&str] = &[
    "chrome-headless-shell",
    "chromium",
    "chromium-browser",
    "google-chrome-stable",
    "google-chrome",
];

/// Locate a browser binary.
///
/// Order: the `PROOFSHEET_CHROME` environment variable, then the local
/// managed download, then anything on `PATH`. Explicit beats implicit, and a
/// pinned local build beats whatever the machine happens to have.
pub fn find_browser(managed_root: Option<&Path>) -> Result<PathBuf> {
    // Empty means unset. `export PROOFSHEET_CHROME=$(which chrome)` on a box
    // without chrome sets it to "", and env::var happily returns Ok(""),
    // which produced the nonsense "points at , which is not a file" instead
    // of falling through to discovery.
    if let Some(p) = std::env::var("PROOFSHEET_CHROME")
        .ok()
        .filter(|v| !v.trim().is_empty())
    {
        let p = PathBuf::from(p.trim());
        if p.is_file() {
            return Ok(p);
        }
        return Err(Error::Browser(format!(
            "PROOFSHEET_CHROME points at {}, which is not a file",
            p.display()
        )));
    }
    // Fall back to the default managed root when the caller does not name
    // one. Every call site passed None, so a browser installed by
    // `install-browser` was never actually found -- the install worked and
    // then the next command still said "no browser".
    let default_root;
    let root = match managed_root {
        Some(r) => r,
        None => {
            default_root = crate::install::managed_root();
            &default_root
        }
    };
    if let Some(found) = find_in_managed(root) {
        return Ok(found);
    }
    for name in CANDIDATES {
        if let Some(p) = which(name) {
            return Ok(p);
        }
    }
    Err(Error::Browser(
        "no browser found. Set PROOFSHEET_CHROME, or run `proofsheet install-browser`.".into(),
    ))
}

fn which(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|d| d.join(name))
        .find(|c| c.is_file())
}

/// Locate a managed headless shell under `root`, if one is installed.
pub(crate) fn find_in_managed(root: &Path) -> Option<PathBuf> {
    if !root.is_dir() {
        return None;
    }
    let name = if cfg!(windows) {
        "chrome-headless-shell.exe"
    } else {
        "chrome-headless-shell"
    };
    find_in_tree(root, name)
}

fn find_in_tree(root: &Path, name: &str) -> Option<PathBuf> {
    let entries = std::fs::read_dir(root).ok()?;
    let mut dirs = Vec::new();
    for e in entries.flatten() {
        let p = e.path();
        if p.is_file() && p.file_name().map(|f| f == name).unwrap_or(false) {
            return Some(p);
        }
        if p.is_dir() {
            dirs.push(p);
        }
    }
    dirs.iter().find_map(|d| find_in_tree(d, name))
}

/// Options for launching the browser.
#[derive(Debug, Clone)]
pub struct LaunchOptions {
    pub binary: PathBuf,
    pub port: u16,
    pub user_data_dir: Option<PathBuf>,
    pub extra_args: Vec<String>,
    pub timeout: Duration,
}

impl LaunchOptions {
    pub fn new(binary: impl Into<PathBuf>) -> Self {
        LaunchOptions {
            binary: binary.into(),
            // 0 asks the OS for a free port, which Chrome reports back on
            // stderr. Fixed ports collide when runs overlap.
            port: 0,
            user_data_dir: None,
            extra_args: Vec::new(),
            timeout: Duration::from_secs(30),
        }
    }
}

/// A live browser process plus an attached CDP session.
#[derive(Debug)]
pub struct Browser {
    child: Child,
    ws: Ws,
    next_id: u64,
    /// The port Chrome actually bound, which may differ from the requested one.
    pub port: u16,
}

impl Browser {
    pub fn launch(opts: &LaunchOptions) -> Result<Browser> {
        let mut cmd = Command::new(&opts.binary);
        cmd.arg(format!("--remote-debugging-port={}", opts.port))
            .arg("--headless")
            .arg("--no-sandbox")
            .arg("--disable-gpu")
            .arg("--hide-scrollbars")
            .arg("--mute-audio")
            .arg("--no-first-run")
            .arg("--no-default-browser-check")
            .arg("--disable-dev-shm-usage")
            // Keep the browser's own scaling out of it: every scale decision
            // is made explicitly per device via Emulation.
            .arg("--force-device-scale-factor=1")
            // Background throttling would make timing depend on wall clock.
            .arg("--disable-background-timer-throttling")
            .arg("--disable-renderer-backgrounding")
            .arg("--disable-backgrounding-occluded-windows");
        if let Some(dir) = &opts.user_data_dir {
            cmd.arg(format!("--user-data-dir={}", dir.display()));
        }
        for a in &opts.extra_args {
            cmd.arg(a);
        }
        cmd.arg("about:blank");
        cmd.stdout(Stdio::null()).stderr(Stdio::piped());

        let mut child = cmd.spawn().map_err(|e| {
            Error::Browser(format!("could not spawn {}: {e}", opts.binary.display()))
        })?;

        let stderr = child
            .stderr
            .take()
            .ok_or_else(|| Error::Browser("no stderr pipe".into()))?;
        let port = match read_devtools_port(stderr, opts.timeout) {
            Ok(p) => p,
            Err(e) => {
                let _ = child.kill();
                return Err(e);
            }
        };

        match attach(port, opts.timeout) {
            Ok(ws) => Ok(Browser {
                child,
                ws,
                next_id: 0,
                port,
            }),
            Err(e) => {
                let _ = child.kill();
                Err(e)
            }
        }
    }

    /// Issue a CDP command and wait for its matching reply, discarding events.
    pub fn call(&mut self, method: &str, params: Value) -> Result<Value> {
        self.next_id += 1;
        let id = self.next_id;
        let msg = json!({ "id": id, "method": method, "params": params });
        self.ws.send_text(&msg.to_string())?;
        loop {
            let raw = self.ws.recv_text()?;
            let v: Value = serde_json::from_str(&raw)?;
            if v.get("id").and_then(Value::as_u64) != Some(id) {
                continue; // an event, or a reply we are not waiting on
            }
            if let Some(err) = v.get("error") {
                let message = err
                    .get("message")
                    .and_then(Value::as_str)
                    .unwrap_or("unknown")
                    .to_string();
                return Err(Error::Cdp {
                    method: method.to_string(),
                    message,
                });
            }
            return Ok(v.get("result").cloned().unwrap_or(Value::Null));
        }
    }
}

impl Drop for Browser {
    fn drop(&mut self) {
        self.ws.close();
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// Chrome prints `DevTools listening on ws://127.0.0.1:<port>/...` to stderr
/// once it is ready. Reading it is how we support `--remote-debugging-port=0`
/// and avoid guessing whether the browser has finished starting.
fn read_devtools_port(stderr: impl Read + Send + 'static, timeout: Duration) -> Result<u16> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let reader = BufReader::new(stderr);
        for line in reader.lines().map_while(std::result::Result::ok) {
            if let Some(rest) = line.split("ws://").nth(1) {
                if let Some(hostport) = rest.split('/').next() {
                    if let Some((_, p)) = hostport.rsplit_once(':') {
                        if let Ok(port) = p.parse::<u16>() {
                            let _ = tx.send(port);
                            return;
                        }
                    }
                }
            }
        }
    });
    rx.recv_timeout(timeout)
        .map_err(|_| Error::Browser("browser did not report a DevTools port".into()))
}

/// Fetch the target list over the plain HTTP endpoint and attach to a page.
fn attach(port: u16, timeout: Duration) -> Result<Ws> {
    let deadline = Instant::now() + timeout;
    let mut last = String::from("no attempt made");
    while Instant::now() < deadline {
        match http_get(port, "/json/list", Duration::from_secs(5)) {
            Ok(body) => match serde_json::from_str::<Value>(&body) {
                Ok(Value::Array(targets)) => {
                    let page = targets
                        .iter()
                        .find(|t| t.get("type").and_then(Value::as_str) == Some("page"));
                    if let Some(url) = page
                        .and_then(|t| t.get("webSocketDebuggerUrl"))
                        .and_then(Value::as_str)
                    {
                        return Ws::connect(url, timeout);
                    }
                    last = "no page target yet".into();
                }
                Ok(_) => last = "target list was not an array".into(),
                Err(e) => last = format!("bad target list: {e}"),
            },
            Err(e) => last = e.to_string(),
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    Err(Error::Browser(format!("could not attach: {last}")))
}

/// A single-shot HTTP/1.1 GET. The DevTools HTTP endpoint is the only thing
/// we need it for, so it stays deliberately small.
///
/// Reads by `Content-Length` rather than to EOF. `read_to_end` on a socket
/// carrying a read timeout surfaces `WouldBlock`/`TimedOut` as a hard error
/// even when the full body already arrived, which presented as an opaque
/// "Resource temporarily unavailable" during bring-up.
fn http_get(port: u16, path: &str, timeout: Duration) -> Result<String> {
    use std::io::Write;
    let mut s = TcpStream::connect(("127.0.0.1", port))?;
    s.set_read_timeout(Some(timeout))?;
    s.set_write_timeout(Some(timeout))?;
    write!(
        s,
        "GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"
    )?;
    s.flush()?;

    let mut raw: Vec<u8> = Vec::with_capacity(8192);
    let mut chunk = [0u8; 8192];

    // Headers first.
    let head_end = loop {
        if let Some(i) = find_subslice(&raw, b"\r\n\r\n") {
            break i;
        }
        match s.read(&mut chunk) {
            Ok(0) => return Err(Error::Shape("http response ended in headers".into())),
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(e) => return Err(Error::Io(e)),
        }
    };

    let head = String::from_utf8_lossy(&raw[..head_end]).to_string();
    let want: Option<usize> = head
        .split("\r\n")
        .filter_map(|l| l.split_once(':'))
        .find(|(k, _)| k.trim().eq_ignore_ascii_case("content-length"))
        .and_then(|(_, v)| v.trim().parse().ok());

    let body_start = head_end + 4;
    loop {
        let have = raw.len() - body_start;
        match want {
            Some(n) if have >= n => break,
            _ => {}
        }
        match s.read(&mut chunk) {
            Ok(0) => break, // clean EOF
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(ref e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                ) =>
            {
                // Timed out with a body already in hand: use what we have
                // rather than discarding a complete response.
                if want.is_none() && !raw[body_start..].is_empty() {
                    break;
                }
                return Err(Error::Shape("timed out reading http body".into()));
            }
            Err(e) => return Err(Error::Io(e)),
        }
    }

    Ok(String::from_utf8_lossy(&raw[body_start..]).to_string())
}

fn find_subslice(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

#[cfg(test)]
mod env_tests {
    /// An empty PROOFSHEET_CHROME must fall through to discovery rather than
    /// being treated as a path. `export PROOFSHEET_CHROME=$(which chrome)` on
    /// a machine without chrome sets it to "", and the old code reported
    /// "PROOFSHEET_CHROME points at , which is not a file".
    #[test]
    fn empty_env_var_is_not_a_path() {
        let raw = Some(String::new());
        let kept = raw.filter(|v: &String| !v.trim().is_empty());
        assert!(kept.is_none(), "empty string must be discarded");

        let blank = Some("   ".to_string()).filter(|v: &String| !v.trim().is_empty());
        assert!(blank.is_none(), "whitespace-only must be discarded");

        let real = Some(" /usr/bin/chrome ".to_string())
            .filter(|v: &String| !v.trim().is_empty())
            .map(|v| v.trim().to_string());
        assert_eq!(
            real.as_deref(),
            Some("/usr/bin/chrome"),
            "real path survives, trimmed"
        );
    }
}

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

    #[test]
    fn missing_env_binary_is_an_error_not_a_fallback() {
        // Pointing at a nonexistent path must fail loudly rather than
        // silently searching PATH -- substituting a different browser than
        // the caller named would make runs irreproducible.
        std::env::set_var("PROOFSHEET_CHROME", "/nonexistent/definitely/not/here");
        let r = find_browser(None);
        std::env::remove_var("PROOFSHEET_CHROME");
        assert!(matches!(r, Err(Error::Browser(_))));
    }

    #[test]
    fn launch_options_default_to_ephemeral_port() {
        let o = LaunchOptions::new("/bin/true");
        assert_eq!(o.port, 0);
    }
}