cfbrowse

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cfbrowse

Go Reference Go Report Card MIT

Minimal Go CDP driver that clears a Cloudflare interactive challenge headless — and never sends Runtime.enable.

Why

Cloudflare's bot scoring reads the control channel, not just the page. chromedp, go-rod, go-rod/stealth and chromedp-undetected all patch the fingerprint layer (navigator.webdriver, UA, window.chrome) but still enable the Runtime domain on attach, and that alone is enough to fail a challenge.

This package evaluates JavaScript through Page.createIsolatedWorld + Runtime.evaluate with an explicit contextId, so the Runtime domain is never enabled. browser_test.go asserts the invariant.

The same leak is already patched in the other ecosystems: rebrowser-patches (Node) and Patchright (Python, Node) reached the isolated-world fix independently of each other, which is a decent sign it is the convergent answer. Go had no equivalent — chromedp-undetected and go-rod/stealth stop at the fingerprint layer. That gap is what this fills.

Scope

This is one layer, and a narrow one: the CDP control channel. It does not touch your TLS fingerprint, your IP, or your request rate, and it deliberately ships no proxy rotation, no concurrency pool, no CAPTCHA-service client, and no per-site selectors. Those are the parts that turn a driver into scraping infrastructure, and they belong in whatever is calling this, if anywhere.

It exists because "which layer actually fails the challenge" was worth pinning down — the answer, Runtime.enable, is useful to a detector as well as to a client. Point it at origins you are allowed to automate.

Intended use

Point this at origins you own, or ones whose operator has authorised you to automate — your own staging and production sites, a customer's, a pentest or bug-bounty target inside its scope, an anti-bot vendor's own test pages. Automating someone else's site against its terms of service is on you, and several jurisdictions treat circumventing an access control as more than a contract problem. The detector side is a first-class use too: Runtime.enable is as useful to whoever writes the check as to whoever fails it.

Use

import "github.com/SP42K/cfbrowse"

b, err := cfbrowse.Launch(cfbrowse.Options{
    UserDataDir: os.ExpandEnv("$HOME/.cfbrowse-profiles/site"), // keeps cf_clearance
    Headless:    true,
})
if err != nil {
    return err
}
defer b.Close()

if err := b.Navigate("https://example.com"); err != nil {
    return err
}
// Solve clicks a challenge if one appears; WaitReady only waits one out.
title, err := b.Solve(90 * time.Second)
if err != nil {
    return err
}
html, err := b.EvalString("document.body.innerHTML")
go get github.com/SP42K/cfbrowse

Solve clears an interactive challenge on its own, headless, from an empty profile. No human, no window, no first run that differs from the rest. Measured against two sites, both of which serve an interactive challenge: headed and headless produced identical results — sixteen mouse events, cf_clearance obtained, full content — so the mode is not a variable.

Use a persistent UserDataDir anyway. Solving costs a few seconds and the cf_clearance it earns is reused until the site expires it, which on one site measured took under eleven minutes and on another survived many runs.

cmd/verify is a reachability check, not a scraper. It reports the title, whether a cf_clearance cookie was obtained, and how many mouse events were dispatched; -eval runs your JavaScript. Site selectors belong in your project, not here.

go run ./cmd/verify -headless -solve -profile ~/.cfbrowse-profiles/site 'https://…'
go run ./cmd/verify -headless -dump 'https://…'                    # page shape
go run ./cmd/verify -headless -eval 'document.title' 'https://…'
go run ./cmd/verify -solve 'https://…'                             # headed, to watch it work
go test ./...

Solving the checkbox

Solve clears an interactive challenge without a human. Two things make it work, and neither costs the invariant:

  • The click is real input. Input.dispatchMouseEvent is injected below Blink's event plumbing, so the page sees isTrusted events. element.click() could not work even in principle — the widget is not reachable from script, and synthetic DOM events are marked untrusted anyway. The cursor is walked in over six steps before the press; arriving instantly is itself a tell.
  • The widget is found through CDP, not JavaScript. Cloudflare renders it inside a closed shadow root, so a page visibly showing a checkbox reports zero iframes and zero open shadow roots to querySelectorAll. DOM.getDocument with pierce: true walks closed shadow roots and nested documents; DOM.getBoxModel turns the node into coordinates. Neither needs an enable.

SolveProgress is Solve with a callback, for callers that put this wait in front of a person. It reports waiting / widget / clicking / cleared and fires only on a change, so a UI can say "clicking it for the third time" instead of spinning for ninety seconds:

title, err := b.SolveProgress(90*time.Second, func(phase string, attempt int) {
    log.Printf("solve: %s (attempt %d)", phase, attempt)
})

verify prints mouse events sent, which is not decoration: a challenge that clears on its own and one that was clicked produce identical output otherwise, and confusing the two sends you debugging the wrong layer. Eight events is one click cycle.

Limits

  • Isolated worlds see the DOM but not the page's own JS globals.
  • No event subscriptions; waiting is done by polling.
  • One page target, no tab management.
  • Clearance lifetime varies wildly by site and is the thing that will bite you. One site tested had its clearance rejected eleven minutes after a solve; another's survived across many runs. Headless is not the discriminator — a headless run fifty seconds after a fresh solve passed in nine. Expect to re-solve, and treat a returning challenge as expiry rather than as a fingerprinting problem.
  • Fingerprint hardening stops at UA + AutomationControlled. On WSL, WEBGL_debug_renderer_info returns nothing (no GPU), which a strict checker can score against.

Documentation

Overview

Package cfbrowse drives Chrome over CDP without ever sending Runtime.enable.

Runtime.enable is the command anti-bot vendors probe for: enabling it changes observable behaviour inside the page, and no amount of fingerprint patching hides it. Everything here evaluates JavaScript through an isolated world created with Page.createIsolatedWorld instead, which needs no Runtime domain.

Index

Constants

View Source
const (
	// StepWaiting: the page is not readable yet, or the widget has not rendered.
	// It renders a beat after the interstitial, so this is the normal opening.
	StepWaiting = "waiting"
	// StepWidget: the widget was located, but this pass is not clicking it —
	// either the attempt budget is spent or the cooldown has not elapsed.
	StepWidget = "widget"
	// StepClicking: a click cycle is being dispatched. attempt is 1-based.
	StepClicking = "clicking"
	// StepCleared: the challenge is gone. Solve returns right after this.
	StepCleared = "cleared"
)

Solve's phases, as reported to SolveProgress's callback.

Variables

This section is empty.

Functions

This section is empty.

Types

type Browser

type Browser struct {
	// contains filtered or unexported fields
}

Browser is one Chrome process and the single page target attached to it. It is safe for concurrent use; there is no tab management.

func Launch

func Launch(opts Options) (*Browser, error)

Launch starts Chrome and attaches to its page target.

With no Options.UserAgent it starts Chrome twice: once to ask what it is, then for real with a matching --user-agent. See resolveUA for why the extra second is not optional.

func (*Browser) Close

func (b *Browser) Close() error

Close shuts Chrome down through Browser.close so the profile keeps the cookies earned this run, then kills the process if it does not exit.

func (*Browser) Cookies

func (b *Browser) Cookies() ([]Cookie, error)

Cookies uses Storage.getCookies, a browser-level command, so the Network domain never has to be enabled.

func (*Browser) Eval

func (b *Browser) Eval(js string) (json.RawMessage, error)

Eval runs js and returns the result as JSON.

The isolated world is recreated per call: it is cheap, and it is invalidated by every navigation, so caching the context id only buys stale-handle bugs. Isolated worlds see the DOM but not the page's own JS globals — fine for scraping, not for reaching into page state.

func (*Browser) EvalString

func (b *Browser) EvalString(js string) (string, error)

EvalString is Eval for expressions that return a string. A result that is not a JSON string is returned as its raw JSON rather than as an error.

func (*Browser) HasClearance

func (b *Browser) HasClearance() bool

HasClearance reports whether a cf_clearance cookie exists. It says nothing about whether the site still honours it — clearance expiry is silent, and the only proof is a request that is not challenged.

func (*Browser) Navigate

func (b *Browser) Navigate(url string) error

Navigate returns as soon as Chrome accepts the command, not when the page has loaded. Follow it with WaitReady, or with Solve if a challenge is expected.

func (*Browser) SentMethods

func (b *Browser) SentMethods() []string

SentMethods returns every CDP method this browser has sent, in order.

func (*Browser) Solve

func (b *Browser) Solve(limit time.Duration) (string, error)

Solve gets past an interactive challenge, clicking the Turnstile widget with real mouse input if one appears, and returns the page title once through.

A page that was never challenged returns as soon as its title settles, so Solve is safe to use in place of WaitReady.

func (*Browser) SolveProgress

func (b *Browser) SolveProgress(limit time.Duration, onStep func(phase string, attempt int)) (string, error)

SolveProgress is Solve with a progress callback, for callers that put this wait in front of a person. It can take a minute and a half, and "still waiting for the widget to render" and "clicking it for the third time" are different enough that one spinner for all of it reads as a hang.

onStep may be nil. It fires only when the phase actually changes — the loop polls at 1 Hz and would otherwise report waiting ninety times — and it runs on Solve's own goroutine, so keep it cheap and non-blocking: the poll cadence is itself part of what the site scores.

func (*Browser) UserAgent

func (b *Browser) UserAgent() string

UserAgent reports the UA the page actually sends. Callers that store a cf_clearance have to store this alongside it; the cookie is scored against it.

func (*Browser) WaitReady

func (b *Browser) WaitReady(limit time.Duration) (string, error)

WaitReady blocks until document.readyState is complete and the Cloudflare interstitial title is gone. The interstitial keeps readyState complete while it works, so the title check is the part that actually matters.

type Cookie struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Domain string `json:"domain"`
}

Cookie is the subset of a CDP cookie this package reads: enough to find cf_clearance and tell which host issued it.

type Options

type Options struct {
	UserDataDir string // persistent profile; keeps cf_clearance between runs
	Headless    bool
	ExecPath    string // defaults to the platform's Chrome, see defaultChrome
	UserAgent   string // defaults to the browser's own UA, see resolveUA
}

Options configures Launch. The zero value launches headed Chrome with a throwaway profile, which loses any cf_clearance when the process exits.

Directories

Path Synopsis
cmd
verify command
Command verify checks that a URL can be reached through its bot challenge.
Command verify checks that a URL can be reached through its bot challenge.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL