R/chrome.R

Defines functions sc_browser_read sc_anchor sc_read_url sc_on_origin sc_page_origin sc_await_spill sc_read_limit sc_browser_download sc_move_file sc_download_dir sc_check_note sc_secs_since sc_now sc_check_wait sc_page_grace print.safeconduct_clearance sc_clearance sc_snapshot_clearance sc_wait_pass sc_pump sc_gone_message sc_document_kind sc_watch_documents sc_raise sc_focus sc_focus_script sc_cookie_header sc_set_useragent sc_useragent_check sc_launch_chrome sc_devtools_port sc_window_args sc_headed_mode sc_display_available sc_browser_unavailable_reason sc_browser_advice browser_advice browser_available

Documented in browser_advice browser_available

# Running Chrome.
#
# What was tried against Cloudflare, and what holds (October 2026):
#
#   * Headless Chrome under its own name does not pass a managed challenge:
#     the check falls through to its interactive form, a "Verify you are
#     human" box, and sits there. Simulating a click on that box is not
#     something this package does: it is the one thing the check exists to
#     ask a person for. Headless Chrome is not held up by a firewall rule
#     that blocks clients which do not look like a browser, and it has been
#     seen to pass a lighter, non-interactive check. Hence the "auto" mode:
#     headless first, a window only when the headless run ends on a check or
#     a block, so that a window is shown only when someone may need to click.
#     With `useragent = TRUE` (below) headless Chrome passed the managed
#     challenge at www12.statcan.gc.ca on 2026-10-24 with nothing clicked, at
#     the root and again at the file's URL, and downloaded 310 MB; the
#     clearance did not transfer to curl. How long that holds is Cloudflare's
#     to decide.
#   * A visible Chrome window launched with an empty, throwaway profile passes
#     in one to two seconds with nothing clicked -- usually. Cloudflare
#     escalates: after a dozen challenges in half an hour from one address it
#     showed the box to the window too. So the window is left on screen with a
#     message asking the user to click the box if it shows, and the wait is
#     long enough for them to. Clicked, the box yields a clearance like any
#     other.
#   * Whether the browser got through is read off the main frame's document
#     responses (`Network.responseReceived`), not off a cookie: a challenge is
#     a `403` with `cf-mitigated: challenge` followed, once passed, by the
#     page; a block is a `403` whose body is Cloudflare's block page and
#     nothing follows it; anything else is the host answering the browser.
#     A host that blocks plain clients but never challenges a browser hands
#     out no `cf_clearance`, so waiting for the cookie would wait for ever.
#   * Chrome is launched directly, headless or not, rather than through
#     chromote's launcher, which always passes `--headless` and supervises the
#     process (see `sc_launch_chrome()`). `--remote-debugging-port=0` makes Chrome pick
#     a free port and write it to `DevToolsActivePort` in the profile
#     directory, which `chromote::ChromeRemote` then connects to. Nothing of
#     the user's own Chrome profile is touched: the profile is a fresh temp
#     directory, removed when the window closes.
#   * A new `ChromoteSession` applies a device-metrics override of 992 by
#     1323 pixels, chromote's stand-in viewport for headless work. In a real
#     window that makes the page lay itself out in an imaginary viewport
#     taller than the window, so the check page's centred card sat below the
#     fold whatever the window's size. The override is cleared right after
#     the session is made, and the viewport is then the window's.
#   * Headless Chrome's user-agent string says `HeadlessChrome`. The Vancouver hosts
#     (results.vancouver.ca, webtransfer.vancouver.ca) block headless Chrome
#     on that word alone: the same browser with `Chrome/` in place of
#     `HeadlessChrome/` is served, while curl is blocked whatever it says;
#     and with the word gone headless Chrome passed StatCan's managed
#     challenge too. So by default (`useragent = TRUE`) the word is dropped
#     and nothing else; the version and platform in the string stay what
#     they are. `useragent = NULL` leaves Chrome's own string.

#' Can this package open a browser here?
#'
#' @return `TRUE`, or `FALSE` with a `reason` attribute: the
#'   `safeconduct.browser` option is `FALSE`, or no Chrome or Chromium was
#'   found (the `CHROMOTE_CHROME` environment variable points at one).
#' @examples
#' browser_available()
#' attr(browser_available(), "reason")
#' @export
browser_available <- function() {
  reason <- sc_browser_unavailable_reason()
  structure(is.null(reason), reason = reason)
}

#' What to tell a person when no browser can be opened
#'
#' One line of advice for when [browser_available()] is `FALSE`, saying what
#' is missing and how to put it right, for a package that uses safeconduct
#' to show its users. It is the advice safeconduct's own errors give, so the
#' wording is the same whichever package shows it.
#'
#' @param url Optionally, the URL that needs the browser, to name its host.
#' @return A string, or `NULL` when a browser can be opened.
#' @examples
#' browser_advice("https://www12.statcan.gc.ca/")
#' if (!browser_available()) message(browser_advice())
#' @export
browser_advice <- function(url = NULL) {
  reason <- sc_browser_unavailable_reason()
  if (is.null(reason)) return(NULL)
  sc_browser_advice(reason, url)
}

# The advice itself, for a known `reason` from
# `sc_browser_unavailable_reason()`. The option is the person's own doing,
# or a calling package's, so it is named and nothing more is suggested.
sc_browser_advice <- function(reason, url = NULL) {
  what <- if (is.null(url)) "A browser is needed here"
          else paste0("'", sc_url_host(url), "' needs a browser")
  if (grepl("safeconduct.browser", reason, fixed = TRUE))
    return(paste0(what, ", and opening one is switched off by ",
                  "`options(safeconduct.browser = FALSE)`."))
  paste0(what, ", and no Chrome or Chromium was found. Install Google Chrome ",
         "(https://www.google.com/chrome/) or Chromium, or set the ",
         "`CHROMOTE_CHROME` environment variable to the path of one ",
         "installed somewhere unusual.")
}

sc_browser_unavailable_reason <- function() {
  if (!isTRUE(getOption("safeconduct.browser", TRUE)))
    return("the `safeconduct.browser` option is FALSE")
  chrome <- tryCatch(suppressMessages(chromote::find_chrome()),
                     error = function(e) NULL)
  if (is.null(chrome) || !nzchar(chrome))
    return(paste0("no Chrome or Chromium was found (set the `CHROMOTE_CHROME` ",
                  "environment variable to its path)"))
  NULL
}

# Can a window be shown? Always on macOS and Windows; on Linux only under a
# display server.
sc_display_available <- function() {
  sysname <- Sys.info()[["sysname"]]
  if (sysname %in% c("Darwin", "Windows")) return(TRUE)
  nzchar(Sys.getenv("DISPLAY")) || nzchar(Sys.getenv("WAYLAND_DISPLAY"))
}

# How the browser is run: "headed" (a window), "headless", or "auto"
# (headless first, a window if that does not get through). The `headed`
# argument of the public functions -- `"auto"` by default, `TRUE` or `FALSE`
# -- decides. "auto" without a display is plain headless.
sc_headed_mode <- function(headed = "auto") {
  headed <- headed %||% "auto"
  if (identical(headed, "auto"))
    return(if (sc_display_available()) "auto" else "headless")
  if (isTRUE(headed)) return("headed")
  if (isFALSE(headed)) return("headless")
  stop("`headed` must be \"auto\", TRUE or FALSE.", call. = FALSE)
}

# How big the window is: 1000 by 800 pixels, or what the `safeconduct.window`
# option says, a `c(width, height)` in pixels or `"maximized"`. (Before the
# viewport override above was found, the card was cut off at every size and
# the window was opened maximized; that is no longer needed by default.)
sc_window_args <- function() {
  size <- getOption("safeconduct.window", c(1000L, 800L))
  if (identical(size, "maximized")) return("--start-maximized")
  if (!is.numeric(size) || length(size) != 2L || any(is.na(size)) || any(size < 200))
    stop("`options(safeconduct.window)` must be \"maximized\" or two pixel ",
         "sizes, c(width, height).", call. = FALSE)
  paste0("--window-size=", paste(as.integer(size), collapse = ","))
}

# Chrome's `DevToolsActivePort` file: the port on the first line, written once
# the DevTools server is listening.
sc_devtools_port <- function(profile, proc = NULL, timeout = 15) {
  path <- file.path(profile, "DevToolsActivePort")
  deadline <- Sys.time() + timeout
  while (Sys.time() < deadline) {
    if (!is.null(proc) && !proc$is_alive())
      stop("Chrome exited before starting its DevTools server.", call. = FALSE)
    if (file.exists(path)) {
      port <- suppressWarnings(as.integer(readLines(path, n = 1L, warn = FALSE)))
      if (length(port) == 1L && !is.na(port) && port > 0L) return(port)
    }
    Sys.sleep(0.2)
  }
  stop("Chrome did not start a DevTools server within ", timeout, " seconds.",
       call. = FALSE)
}

# Start Chrome and attach a DevTools session to it. Returns a list with the
# `session` (a `chromote::ChromoteSession`), `headed` (whether a window is on
# screen) and `close()`, which shuts everything down and removes the profile.
#
# Both modes launch Chrome here, not through chromote's launcher, and without
# processx's supervisor (`supervise = FALSE`). The supervisor is a helper
# process shared by the whole R session, which R talks to over two fifo
# connections that stay open for the rest of the session once any supervised
# process has been started; chromote's launcher starts one. Those fifos sat
# in `showConnections()` after every fetch, and `R CMD check` fails an
# example that leaves a connection open, so a package whose examples called
# this one could not pass its check. What the supervisor would have done is
# kill Chrome should R itself be killed outright. `cleanup = TRUE` still
# kills it when R exits or the handle is collected, and `close()` asks Chrome
# to quit and then makes sure.
sc_launch_chrome <- function(headed = TRUE) {
  profile <- tempfile("safeconduct-chrome-")
  dir.create(profile)
  proc <- processx::process$new(
    chromote::find_chrome(),
    c(if (!headed) "--headless",
      "--remote-debugging-port=0",
      paste0("--user-data-dir=", profile),
      "--no-first-run", "--no-default-browser-check",
      "--disable-extensions", "--disable-sync", "--mute-audio",
      if (headed) sc_window_args(),
      "about:blank"),
    stdout = NULL, stderr = NULL, supervise = FALSE, cleanup = TRUE)
  state <- new.env()
  # Close the websocket from R's side first, while it is idle, and only then
  # tell Chrome to quit, with a signal rather than over the protocol. Then
  # make sure. See the comment inside for why in this order.
  close <- function() {
    if (!is.null(state$chrome)) {
      # websocketpp, under chromote, writes straight to stderr, where no R
      # condition handler and no `quiet` can reach, about either end of a
      # connection it did not close cleanly. A socket that Chrome drops when
      # it quits, with R's side still open, gives "[error] handle_read_frame
      # error ... (End of File)". Sending `Browser.close` without waiting and
      # closing the socket at once, as chromote's own close() does for a
      # browser it launched, only narrows that: Chrome's reply to the command
      # can land while R is closing, which gives "[warning] got non-close
      # frame while closing" (3 closes in 16 on macOS). Closed while idle,
      # the socket has nothing in flight, and a SIGTERM afterwards has Chrome
      # quit on its own terms. On Windows processx makes SIGTERM a hard kill,
      # which is harmless here: the socket is already closed and the profile
      # is thrown away.
      try(state$chrome$close(), silent = TRUE)
      state$chrome <- NULL
    }
    try(proc$signal(tools::SIGTERM), silent = TRUE)
    try(proc$wait(timeout = 2000), silent = TRUE)
    try(if (proc$is_alive()) proc$kill(), silent = TRUE)
    unlink(profile, recursive = TRUE)
  }
  tryCatch({
    port <- sc_devtools_port(profile, proc)
    remote <- chromote::ChromeRemote$new(host = "127.0.0.1", port = port)
    state$chrome <- chromote::Chromote$new(browser = remote)
    state$session <- chromote::ChromoteSession$new(parent = state$chrome)
    # A new session carries chromote's 992 by 1323 viewport override, meant
    # for headless work and kept there; in a window it is cleared, so that
    # the viewport is the window's (see the top of this file).
    if (headed) invisible(state$session$Emulation$clearDeviceMetricsOverride())
  }, error = function(e) {
    close()
    stop(e)
  })
  list(session = state$session, headed = headed, close = close)
}

# The user-agent string the browser announces, from the `useragent` argument
# of the public functions: `TRUE` (the default) drops the word `Headless`
# from Chrome's own, `NULL` leaves it, a string is used as given. The override is set through
# the protocol before the first navigation and holds for the browser's life;
# it is what the clearance then reports too, so curl under the clearance
# says the same.
sc_useragent_check <- function(useragent) {
  if (is.null(useragent) || isTRUE(useragent)) return(useragent)
  if (is.character(useragent) && length(useragent) == 1L && !is.na(useragent) &&
      nzchar(useragent)) return(useragent)
  stop("`useragent` must be NULL, TRUE or one string.", call. = FALSE)
}

sc_set_useragent <- function(session, useragent) {
  useragent <- sc_useragent_check(useragent)
  if (is.null(useragent)) return(invisible(NULL))
  if (isTRUE(useragent)) {
    own <- session$Runtime$evaluate("navigator.userAgent")$result$value
    useragent <- sub("HeadlessChrome/", "Chrome/", own, fixed = TRUE)
    if (identical(useragent, own)) return(invisible(own))
  }
  invisible(session$Network$setUserAgentOverride(userAgent = useragent))
  invisible(useragent)
}

# The CDP cookie list as one `Cookie:` header value.
sc_cookie_header <- function(cookies) {
  paste(vapply(cookies, function(ck) paste0(ck$name, "=", ck$value),
               character(1)),
        collapse = "; ")
}

# Bringing the check into view.
#
# The challenge page puts the check -- the spinner, or the "Verify you are
# human" box -- in one element, surrounded by a heading, a footer and a good
# deal of margin, and in a window of the size used here the box can sit below
# the fold. While the check is pending, that element is pinned to the top left
# corner of the window and enlarged, and everything that is not it, inside it
# or above it is made invisible. The styles are set on the elements themselves
# through the CSSOM, because an added `<style>` element is subject to the
# page's Content Security Policy and was blocked on the one real check page
# tried, while element styles are not. It is a presentational change, as a
# user stylesheet or the browser's zoom would be: nothing in the element is
# read, filled or clicked, and the check's widget runs untouched inside it.
# It is opt-in: the `safeconduct.focus` option names the selector (`.card` on
# the pages met so far) and `safeconduct.zoom` the enlargement. Verified on a
# local mock page with a blocking CSP; the one real run with it on ended with
# the browser going away before the download, for reasons not established, so
# it is not on by default.
sc_focus_script <- function(selector = getOption("safeconduct.focus", NULL),
                            zoom = getOption("safeconduct.zoom", 1.5)) {
  if (isFALSE(selector) || is.null(selector)) return(NULL)
  sprintf(
    "(function(sel, zoom){
      if (window.__safeconductFocused) return 'kept';
      var el = document.querySelector(sel);
      if (!el) return 'absent';
      window.__safeconductFocused = true;
      var set = function(n, prop, value) { n.style.setProperty(prop, value, 'important'); };
      set(document.documentElement, 'overflow', 'hidden');
      set(document.body, 'margin', '0');
      set(el, 'position', 'fixed');
      set(el, 'top', '10px');
      set(el, 'left', '10px');
      set(el, 'margin', '0');
      set(el, 'max-width', 'none');
      set(el, 'width', 'calc(100vw / ' + zoom + ' - 20px)');
      set(el, 'zoom', zoom);
      set(el, 'z-index', '2147483647');
      var keep = new Set();
      for (var n = el; n; n = n.parentElement) keep.add(n);
      el.querySelectorAll('*').forEach(function(n) { keep.add(n); });
      document.body.querySelectorAll('*').forEach(function(n) {
        if (!keep.has(n)) set(n, 'visibility', 'hidden');
      });
      return 'focused';
    })(%s, %s)", encodeString(selector, quote = '"'), zoom)
}

sc_focus <- function(session, script) {
  if (is.null(script)) return(invisible(NULL))
  try(session$Runtime$evaluate(script), silent = TRUE)
  invisible(NULL)
}

# Bring the window to the front. A window Chrome has just opened is in front,
# because the system activates a newly launched application; a window a
# session keeps is wherever the person left it, mostly behind the console,
# and a check that turns up in it there goes unseen, and so unclicked, until
# the wait runs out (www12.statcan.gc.ca, November 2026, where a session's
# second file timed out that way). `Page.bringToFront` raises and focuses the
# window across applications, verified on macOS; in headless Chrome it does
# nothing. It is called once per check, when the check's document first
# shows, so that a window the person has moved aside on purpose is not
# pulled back every tick.
#
# Raising the window is not enough on its own: the check wants the page kept
# in the foreground while it runs. A window that was in the background when
# the challenge loaded loops even once raised and clicked, reissuing the
# check on every click; the same file through a window left in front passes
# in one click (www12.statcan.gc.ca on a fresh address, November 2026). So
# the message asks the person to leave the window in front until it is
# through, and the raise is there to make a buried check seen at all.
sc_raise <- function(session) {
  try(session$Page$bringToFront(), silent = TRUE)
  invisible(NULL)
}

# Watching what the main frame is served.
#
# Events only reach R while a protocol call is in flight, so the loops below
# make a cheap synchronous call each turn, which also notices a browser that
# has gone away. `sc_watch_documents()` records the latest document response
# of the main frame -- the challenge iframe's documents are not it -- and
# `sc_document_kind()` says what it is:
#
#   "challenge"  the check is running (or waiting for a click)
#   "block"      Cloudflare's block page: the browser is refused too
#   "redirect"   a 3xx; the real answer follows
#   "pending"    a 403 from Cloudflare whose body is not readable yet
#   "page"       anything else: the host answered the browser
#   NULL         nothing yet
sc_watch_documents <- function(session) {
  invisible(session$Network$enable())
  frame <- tryCatch(session$Page$getFrameTree()$frameTree$frame$id,
                    error = function(e) NULL)
  w <- new.env(parent = emptyenv())
  w$doc <- NULL
  unregister <- session$Network$responseReceived(callback_ = function(ev) {
    if (!identical(ev$type, "Document")) return(invisible(NULL))
    if (!is.null(frame) && !is.null(ev$frameId) && !identical(ev$frameId, frame))
      return(invisible(NULL))
    h <- sc_parse_headers(ev$response$headers %||% list())
    w$doc <- list(requestId = ev$requestId, status = ev$response$status %||% 0,
                  headers = h, url = ev$response$url,
                  type = tolower(h[["content-type"]] %||%
                                   ev$response$mimeType %||% ""),
                  body = NULL)
  }, wait_ = FALSE)
  w$stop <- function() try(unregister(), silent = TRUE)
  w
}

sc_document_kind <- function(session, w) {
  doc <- w$doc
  if (is.null(doc)) return(NULL)
  if (is_challenge(doc$headers)) return("challenge")
  status <- as.integer(doc$status)
  if (status >= 300L && status < 400L) return("redirect")
  if (status == 403L &&
      identical(tolower(doc$headers[["server"]] %||% ""), "cloudflare")) {
    if (is.null(doc$body)) {
      body <- tryCatch(
        session$Network$getResponseBody(requestId = doc$requestId)$body,
        error = function(e) NULL)
      if (is.null(body)) return("pending")
      w$doc$body <- body
      doc$body <- body
    }
    if (is_block(403L, doc$headers, doc$body)) return("block")
  }
  "page"
}

# How a browser that is no longer there is reported: the message says so,
# and `reason = "gone"` lets a session tell it from other failures.
sc_gone_message <- function() "the browser went away: closed, or crashed."

# The protocol call that pumps events; a browser that has gone away raises.
sc_pump <- function(session, what = "safeconduct_not_passed") {
  tryCatch(session$Browser$getVersion(), error = function(e) {
    stop(sc_error(what, paste0("The browser check was not passed: ",
                               sc_gone_message()), reason = "gone"))
  })
  invisible(NULL)
}

# Load `url` in the session and wait for the host to answer the browser with
# something other than a check or a block. Returns the clearance -- the
# browser's user-agent string and its cookies for the host, whatever they are
# -- or raises `safeconduct_not_passed`, with `reason` `"blocked"` when the
# browser was shown the block page and `"timeout"` when the check was still
# pending after `timeout` seconds.
sc_wait_pass <- function(session, url, timeout) {
  w <- sc_watch_documents(session)
  on.exit(w$stop(), add = TRUE)
  invisible(session$Page$navigate(url, wait_ = FALSE))
  focus <- sc_focus_script()
  deadline <- Sys.time() + timeout
  pending_since <- NULL
  raised <- FALSE
  repeat {
    Sys.sleep(0.5)
    sc_pump(session)
    sc_focus(session, focus)
    kind <- sc_document_kind(session, w)
    if (identical(kind, "challenge") && !raised) {
      sc_raise(session)
      raised <- TRUE
    }
    if (identical(kind, "page")) return(sc_snapshot_clearance(session, url))
    if (identical(kind, "pending")) {
      pending_since <- pending_since %||% sc_now()
      if (sc_secs_since(pending_since) > 3) kind <- "block"
    } else {
      pending_since <- NULL
    }
    if (identical(kind, "block")) {
      stop(sc_error("safeconduct_not_passed", paste0(
        "'", sc_url_host(url), "' blocks this browser too; there is no safe ",
        "conduct to be had here."), reason = "blocked"))
    }
    if (Sys.time() > deadline) {
      stop(sc_error("safeconduct_not_passed", paste0(
        "The browser check at '", sc_url_host(url), "' was not passed within ",
        timeout, " seconds. A host may tighten its check after a burst of ",
        "requests from one address, the browser's and plain ones alike; try ",
        "again in a while, or with `headed = TRUE` so that a person can click ",
        "it."), reason = "timeout"))
    }
  }
}

# What the browser now holds for the host.
sc_snapshot_clearance <- function(session, url) {
  cookies <- tryCatch(session$Network$getCookies(urls = list(url))$cookies,
                      error = function(e) list())
  ua <- session$Runtime$evaluate("navigator.userAgent")$result$value
  sc_clearance(url, ua, sc_cookie_header(cookies))
}

sc_clearance <- function(url, useragent, cookie) {
  structure(list(host = sc_url_host(url), useragent = useragent,
                 cookie = cookie, time = Sys.time()),
            class = "safeconduct_clearance")
}

#' @export
print.safeconduct_clearance <- function(x, ...) {
  cat("<safeconduct clearance for '", x$host, "', issued ",
      format(x$time, "%Y-%m-%d %H:%M:%S"), ">\n", sep = "")
  cat("  user agent: ", x$useragent, "\n", sep = "")
  names <- if (nzchar(x$cookie)) sub("=.*", "", strsplit(x$cookie, "; ")[[1]])
           else "none"
  cat("  cookies:    ", paste(names, collapse = ", "), "\n", sep = "")
  invisible(x)
}

# Download `url` through the browser into `destfile`. The file is written
# beside its destination under Chrome's own name for it and renamed on
# completion, so a transfer that fails leaves nothing at `destfile`. A
# transfer that makes no progress for two minutes, or runs past `timeout`
# seconds, is cancelled and raises a `safeconduct_download_error`.
#
# `Browser.setDownloadBehavior` with `allowAndName` lands the file as
# `<dir>/<guid>` under `tempdir()` and reports progress through
# `Browser.downloadProgress`; the file is moved into place when complete.
# The main frame's documents are watched as well: a check at the file's URL
# runs and the download follows, a check still running after its wait and a
# block page end the attempt as `safeconduct_not_passed` (the check with
# `reason = "timeout"`, so that a caller may open a window instead), and an
# HTML page that starts no download within fifteen seconds is a
# `safeconduct_download_error` -- the server answered with a page, not the
# file.
sc_page_grace <- function() 15

# How long a check at the file's URL may run before the download is given up
# as not passed. A window waits for a person, as the root wait does. Headless
# Chrome has no one to wait for, but Cloudflare has let it through such a
# check with nothing clicked after holding it for about two minutes
# (www12.statcan.gc.ca, October 2026), so it is given a little more than that.
sc_check_wait <- function(headed) if (headed) 120 else 150

# The clock the waiting loops read, and the seconds since a moment on it. The
# subtraction of two times is a `difftime` whose unit R picks for the size of
# the gap: seconds under a minute, then minutes, then hours. Compared with a
# bare number, a gap of 200 seconds reads as 3.3 and a limit of 150 seconds
# is never reached, so every limit in a loop that had passed the one-minute
# mark was in effect read in minutes, and the check wait and the download
# timeout never fired (found November 2026 with a check at the file's URL
# that headless Chrome sat on for twelve minutes with no window opened).
# Hence the unit is always named. Tests replace `sc_now()` to move time.
sc_now <- function() Sys.time()
sc_secs_since <- function(then, now = sc_now()) {
  as.numeric(difftime(now, then, units = "secs"))
}

# What is said when a check turns up at the file's URL. `fallback` says
# whether a window follows should headless Chrome not get through in time.
sc_check_note <- function(headed, fallback = FALSE) {
  paste0("  The server is asking for a browser check at the file's URL first; ",
    if (headed) paste0("if it shows a \"Verify you are human\" box, click the box ",
                       "and leave the window in front until the file is through.")
    else paste0("headless Chrome passes it without a click, but it may take ",
                "two minutes.\n  If it has not passed by then, ",
                if (fallback) "a window is opened." else "the download fails."))
}

# Where the browser lands files before they are moved into place: under
# `tempdir()`, not next to the destination, so that nothing of the package's
# turns up in a working directory.
sc_download_dir <- function() {
  dir <- file.path(tempdir(), "safeconduct")
  if (!dir.exists(dir)) dir.create(dir)
  dir
}

# Move a finished download into place: a rename where the two are on one
# volume, a copy otherwise.
sc_move_file <- function(from, to) {
  if (isTRUE(suppressWarnings(file.rename(from, to)))) return(TRUE)
  ok <- isTRUE(file.copy(from, to, overwrite = TRUE))
  if (ok) unlink(from)
  ok
}

sc_browser_download <- function(session, url, destfile, quiet = FALSE,
                                timeout = 3600, headed = TRUE,
                                fallback = FALSE, hints = FALSE) {
  if (!dir.exists(dirname(destfile)))
    stop("The directory for '", destfile, "' does not exist.", call. = FALSE)
  dir <- sc_download_dir()
  invisible(session$Browser$setDownloadBehavior(
    behavior = "allowAndName", downloadPath = dir, eventsEnabled = TRUE))
  progress <- NULL
  unregister <- session$Browser$downloadProgress(
    callback_ = function(ev) progress <<- ev, wait_ = FALSE)
  on.exit(try(unregister(), silent = TRUE), add = TRUE)
  w <- sc_watch_documents(session)
  on.exit(w$stop(), add = TRUE)
  invisible(session$Page$navigate(url, wait_ = FALSE))

  started <- sc_now()
  last_bytes <- -1
  last_change <- started
  last_report <- started
  page_since <- NULL
  check_since <- NULL
  told <- FALSE
  cleanup <- function() {
    guid <- progress$guid
    if (!is.null(guid)) {
      try(session$Browser$cancelDownload(guid = guid), silent = TRUE)
      unlink(list.files(dir, pattern = paste0("^", guid), full.names = TRUE))
    }
  }
  fail <- function(why, class = "safeconduct_download_error", reason = NULL) {
    cleanup()
    stop(sc_error(class, paste0(
      "Could not download '", url, "' in the browser: ", why), reason = reason))
  }
  repeat {
    Sys.sleep(0.5)
    tryCatch(session$Browser$getVersion(),
             error = function(e) fail(sc_gone_message(), reason = "gone"))
    now <- sc_now()
    state <- progress$state %||% "pending"
    if (identical(state, "completed")) break
    if (identical(state, "canceled")) fail("the browser cancelled it.")
    if (is.null(progress)) {
      kind <- sc_document_kind(session, w)
      if (identical(kind, "block")) {
        fail(paste0("'", sc_url_host(url), "' blocks this browser too."),
             "safeconduct_not_passed")
      }
      if (identical(kind, "challenge")) {
        page_since <- NULL
        check_since <- check_since %||% now
        last_change <- now
        if (!told) {
          if (headed) sc_raise(session)
          sc_message(quiet, sc_check_note(headed, fallback))
          if (!headed) {
            sc_hint(hints, paste0("headed:", sc_url_host(url)),
              "rather than wait, headed = TRUE opens a window at once, where ",
              "the check shows its box to click.")
          }
          told <- TRUE
        }
        if (sc_secs_since(check_since, now) > sc_check_wait(headed)) {
          fail(paste0("the browser check at the file's URL was not passed ",
                      "within ", sc_check_wait(headed), " seconds."),
               "safeconduct_not_passed", reason = "timeout")
        }
      } else if (identical(kind, "page") && grepl("html", w$doc$type %||% "")) {
        page_since <- page_since %||% now
        if (sc_secs_since(page_since, now) > sc_page_grace()) {
          fail(paste0("the server answered with a page (status ",
                      w$doc$status, "), not the file."))
        }
      }
    }
    received <- progress$receivedBytes %||% 0
    if (received != last_bytes) { last_bytes <- received; last_change <- now }
    if (sc_secs_since(last_change, now) > 120) fail("no data arrived for two minutes.")
    if (sc_secs_since(started, now) > timeout) fail(paste0("it did not finish in ", timeout,
                                             " seconds."))
    if (!quiet && sc_secs_since(last_report, now) > 10 && received > 0) {
      total <- progress$totalBytes %||% 0
      sc_message(quiet, sprintf("  %.0f MB%s", received / 1e6,
        if (total > 0) sprintf(" of %.0f", total / 1e6) else ""))
      last_report <- now
    }
  }
  from <- file.path(dir, progress$guid)
  if (!file.exists(from) || file.info(from)$size == 0)
    fail("the browser reported it complete but there is no file.")
  if (!sc_move_file(from, destfile)) {
    unlink(from)
    fail("the file could not be moved into place.")
  }
  invisible(destfile)
}

# Reading a resource in the browser.
#
# The page the session holds -- a page on the host -- runs `fetch()` on the
# URL and hands back status, headers and the body. The body comes as base64
# so that binary resources survive the trip; the request is same-origin, so
# every response header is readable, including `cf-mitigated` on a check.
#
# Same-origin is not a given. The check is passed on the host's root, and a
# root may redirect to another host: https://www150.statcan.gc.ca/ ends on
# https://www.statcan.gc.ca/ (November 2026, issue #1). From there the fetch
# is cross-origin, the server sends no CORS headers, and Chrome refuses it
# with nothing more than "TypeError: Failed to fetch". The document wait
# took the other host's page for the host answering, so the browser had in
# fact never been on the host at all, and the clearance it handed over held
# no cookies of the host's. `sc_anchor()` therefore loads the URL itself
# when the tab has ended on another origin, and waits only until the tab is
# on the URL's origin, not until any check there is passed: Cloudflare
# checks navigations, not the requests a page makes, and a same-origin
# `fetch()` from the check page at www150.statcan.gc.ca was served 200 while
# every navigation there, for twenty seconds and more, got the 403 check in
# headless Chrome. Waiting for that check to pass would have meant a window
# and a click for a read that needs neither. A block page there is still a
# block. The clearance is taken again on the right host, whatever its
# cookies are by then.
#
# A URL that does not open as a page -- a CSV or a ZIP, one Chrome would
# download -- leaves the tab where it was. Downloads are denied while it
# loads, so nothing is saved, and `Page.navigate` says so in its reply
# (`isDownload`, with `errorText` "net::ERR_ABORTED"; checked against
# Chrome in December 2026), which comes as soon as the response headers are
# in. The tab is then sent to the host's `/robots.txt` instead. Any document
# on the origin will do to read from, and that one is either plain text,
# which Chrome shows as a page, or a 404 page, which is on the origin all
# the same; behind a check it is the check page, which is also on the
# origin, and the read is then made from there as above. Only when that
# does not get the tab onto the origin either does the read, after
# `sc_page_grace()` seconds, say plainly where the browser is rather than
# passing on the bare "Failed to fetch".
#
# An `http://` URL whose host moves the browser to `https://` would never
# match its page's origin, and a page served over https may not fetch
# plain http anyway (mixed content). So a page on the same host over https
# counts as being on the URL's origin (`sc_on_origin()`), and the read is
# made from the https URL (`sc_read_url()`); a host that serves plain http
# stays on http and is read that way.
# This is for pages and feeds read into memory; `fetch()` and
# `sc_browser_download()` are the way to put a resource on disk.
#
# A small body rides back inside one `Runtime.evaluate` reply as base64. A
# reply much past 32 MB of base64 never arrives whole -- Chrome, the
# websocket or chromote, it does not matter which -- and the call hangs, its
# `timeout_` never firing (www12.statcan.gc.ca, a 27.8 MB file, November
# 2026; the why of the stuck timeout is in notes/NOTE-www12-files-blob-download.md).
# So the script measures the body before encoding it: under the limit it
# returns the base64 as before; over it, it wraps the bytes in a `Blob` and
# clicks an `<a download>`, which `Browser.setDownloadBehavior allowAndName`
# lands as a file while `Browser.downloadProgress` reports it, exactly as a
# navigated download does. The reply is then small either way -- a body, or
# a size and a note that one is on the way -- so nothing large crosses the
# protocol and the read never hangs. `sc_browser_read()` reads the spilled
# file back into the `content` it would otherwise have decoded, so its
# return is the same shape whichever route the body took. The limit sits
# well under the size where the hang was seen.
#
# The link is made as an XHTML element and hung on the document's root when
# there is no body, so that the spill works on any page the tab may be on,
# an XML document or a plain-text one among them, where `document.body` is
# null and a plain `createElement('a')` has no `click()`. The Blob URL is
# revoked after five minutes rather than at once, since Chrome reads the
# Blob after the click returns; without that each large read would hold its
# body in the tab's memory for the life of a `browser_session()`. A body
# still being written when the URL is revoked keeps going: Chrome holds the
# Blob itself, not the URL, once the download has started.
sc_read_limit <- function() 16L * 1024L * 1024L

sc_read_script <- "(async function(url, limit) {
  try {
    var r = await fetch(url, {cache: 'no-store', credentials: 'include',
                              redirect: 'follow'});
    var buf = new Uint8Array(await r.arrayBuffer());
    var headers = {};
    r.headers.forEach(function(v, k) { headers[k] = v; });
    if (buf.length > limit) {
      var a = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      var href = URL.createObjectURL(new Blob([buf]));
      a.href = href;
      a.download = 'safeconduct.bin';
      (document.body || document.documentElement).appendChild(a);
      a.click(); a.remove();
      setTimeout(function() { URL.revokeObjectURL(href); }, 300000);
      return {ok: true, status: r.status, url: r.url, headers: headers,
              spilled: true, size: buf.length};
    }
    var bin = '';
    for (var i = 0; i < buf.length; i += 32768)
      bin += String.fromCharCode.apply(null, buf.subarray(i, i + 32768));
    return {ok: true, status: r.status, url: r.url, headers: headers,
            body: btoa(bin)};
  } catch (e) {
    return {ok: false, error: String(e)};
  }
})(%s, %s)"

# Wait for the download the read script started with its Blob click to
# finish, and return the file Chrome wrote under `sc_download_dir()`. It is
# the tail of `sc_browser_download()` without the navigation and the
# document watching: the fetch has already answered 200, so there is no
# check to pass here, only bytes to collect. `pr$ev` is the latest progress
# event, written by the callback the caller registered before the script ran.
sc_await_spill <- function(session, pr, timeout = 120) {
  started <- sc_now()
  last_bytes <- -1
  last_change <- started
  repeat {
    Sys.sleep(0.25)
    tryCatch(session$Browser$getVersion(), error = function(e) {
      stop(sc_error("safeconduct_download_error",
        paste0("the browser went away mid-read: ", sc_gone_message()),
        reason = "gone"))
    })
    now <- sc_now()
    ev <- pr$ev
    state <- ev$state %||% "pending"
    if (identical(state, "completed")) return(file.path(sc_download_dir(), ev$guid))
    if (identical(state, "canceled"))
      stop(sc_error("safeconduct_download_error", "the browser cancelled the read."))
    received <- ev$receivedBytes %||% 0
    if (received != last_bytes) { last_bytes <- received; last_change <- now }
    if (sc_secs_since(last_change, now) > 120)
      stop(sc_error("safeconduct_download_error", "no data arrived for two minutes."))
    if (sc_secs_since(started, now) > timeout)
      stop(sc_error("safeconduct_download_error",
        paste0("the large body did not arrive within ", timeout, " seconds.")))
  }
}

# The origin of the page the tab is showing, or NULL when it cannot be had.
sc_page_origin <- function(session) {
  v <- tryCatch(session$Runtime$evaluate("location.origin")$result$value,
                error = function(e) NULL)
  if (is.character(v) && length(v) == 1L) tolower(v) else NULL
}

# Is a page whose origin is `here` on the origin of `url`? The same origin
# is, and so is the https origin of the same host for an http URL, since a
# host that moves the browser to https serves the URL there as well.
sc_on_origin <- function(here, url) {
  if (is.null(here)) return(FALSE)
  want <- sc_url_origin(url)
  identical(here, want) ||
    (startsWith(want, "http://") && identical(here, sub("^http:", "https:", want)))
}

# The URL to read from a page whose origin is `here`: `url` itself, or its
# https form when the page is the https origin of an http URL's host.
sc_read_url <- function(here, url) {
  if (!is.null(here) && startsWith(here, "https://") && grepl("^http://", url, ignore.case = TRUE))
    sub("^http://", "https://", url, ignore.case = TRUE)
  else url
}

# Bring the tab onto the origin of `url` if it is not there. Returns the
# clearance taken once it is there, or NULL when the tab was there already
# or could not be brought there within `sc_page_grace()` seconds. Raises
# `safeconduct_not_passed` (`reason = "blocked"`) on a block page. See
# "Reading a resource in the browser" above.
sc_anchor <- function(session, url) {
  here <- sc_page_origin(session)
  if (is.null(here) || sc_on_origin(here, url)) return(NULL)
  invisible(session$Browser$setDownloadBehavior(behavior = "deny"))
  w <- sc_watch_documents(session)
  on.exit(w$stop(), add = TRUE)
  # Waited for, so that a URL Chrome would download is known at once. The
  # reply comes once the response headers are in, the check page's
  # included; a server too slow for that is left to the loop below.
  nav <- tryCatch(session$Page$navigate(url, timeout_ = sc_page_grace()),
                  error = function(e) NULL)
  if (isTRUE(nav$isDownload))
    invisible(session$Page$navigate(paste0(sc_url_origin(url), "/robots.txt"),
                                    wait_ = FALSE))
  started <- sc_now()
  repeat {
    sc_pump(session)
    if (sc_on_origin(sc_page_origin(session), url)) {
      kind <- sc_document_kind(session, w)
      if (identical(kind, "block"))
        stop(sc_error("safeconduct_not_passed", paste0(
          "'", sc_url_host(url), "' blocks this browser too; there is no safe ",
          "conduct to be had here."), reason = "blocked"))
      if (!identical(kind, "pending")) return(sc_snapshot_clearance(session, url))
    }
    if (sc_secs_since(started) > sc_page_grace()) return(NULL)
    Sys.sleep(0.25)
  }
}

# Returns a list like `curl::curl_fetch_memory()`'s: `url`, `status_code`,
# `type`, `headers` (a named list) and `content` (raw). Raises
# `safeconduct_download_error` when the request could not be made at all:
# the page's `fetch()` failed (the message is the browser's), the call did
# not come back in time, or the browser is no longer there (`reason`
# `"gone"`; a session opens another and reads again).
sc_browser_read <- function(session, url, timeout = 120) {
  here <- sc_page_origin(session)
  if (!is.null(here) && !sc_on_origin(here, url))
    stop(sc_error("safeconduct_download_error", paste0(
      "Could not read '", url, "' in the browser: the browser is on '", here,
      "', not '", sc_url_origin(url), "', and a page reads only from its own ",
      "origin. Neither '", url, "' nor the host's robots.txt opened as a page ",
      "there; fetch() downloads it instead.")))
  url <- sc_read_url(here, url)
  limit <- sc_read_limit()
  # Registered before the script runs: a large body is handed to Chrome as a
  # download from inside the script, and its first progress event can arrive
  # before the script's reply does.
  invisible(session$Browser$setDownloadBehavior(
    behavior = "allowAndName", downloadPath = sc_download_dir(),
    eventsEnabled = TRUE))
  pr <- new.env(parent = emptyenv())
  pr$ev <- NULL
  unregister <- session$Browser$downloadProgress(
    callback_ = function(ev) pr$ev <- ev, wait_ = FALSE)
  on.exit(try(unregister(), silent = TRUE), add = TRUE)
  js <- sprintf(sc_read_script, encodeString(url, quote = '"'),
                format(limit, scientific = FALSE))
  failed <- NULL
  res <- tryCatch(
    session$Runtime$evaluate(js, awaitPromise = TRUE, returnByValue = TRUE,
                             timeout_ = timeout * 1000),
    error = function(e) { failed <<- conditionMessage(e); NULL })
  v <- res$result$value
  if (is.null(v) || !isTRUE(v$ok)) {
    gone <- !isTRUE(tryCatch(session$is_active(), error = function(e) FALSE))
    why <- if (gone) sc_gone_message()
           else if (!is.null(v$error)) paste0("the page's request failed: ", v$error)
           else if (!is.null(failed)) failed
           else paste0("no answer within ", timeout, " seconds.")
    stop(sc_error("safeconduct_download_error", paste0(
      "Could not read '", url, "' in the browser: ", why),
      reason = if (gone) "gone"))
  }
  h <- sc_parse_headers(as.list(v$headers %||% list()))
  content <- if (isTRUE(v$spilled)) {
    from <- sc_await_spill(session, pr, timeout)
    if (!file.exists(from) || file.info(from)$size == 0)
      stop(sc_error("safeconduct_download_error", paste0(
        "Could not read '", url, "' in the browser: the large body (",
        sprintf("%.0f MB", (v$size %||% 0) / 1024^2),
        ") was reported complete but there is no file.")))
    on.exit(unlink(from), add = TRUE)
    readBin(from, "raw", n = file.info(from)$size)
  } else {
    jsonlite::base64_dec(v$body %||% "")
  }
  list(url = v$url %||% url, status_code = as.integer(v$status),
       type = tolower(h[["content-type"]] %||% NA_character_),
       headers = h, content = content)
}

Try the safeconduct package in your browser

Any scripts or data that you put into this service are public.

safeconduct documentation built on Dec. 3, 2026, 1:07 a.m.