Add the Chrome fallback and the needs-human flow.

Bot checks escalate to headless Chrome with stealth, which claims the
same identity as tls-client and hands its cookies back to the jar. The
visit counts against the rate limits. If Chrome can't clear a check,
the URL is marked needs-human. Pressing Enter on it in the TUI, or
running 'dibs solve', opens a visible window; dibs carries on once the
page loads. Processes now merge the cookie file on save, with the
newest cookie winning.
This commit is contained in:
Overlord committed 2026-10-14 14:08:56 +02:00
1 parent f2ea1297e8
commit e2cbc1a55c
20 files changed
+905 -73

No files matched your search

+300
View File
@@ -0,0 +1,300 @@
// Package chrome runs a real Chrome for the bot checks tls-client cannot
// pass: headless for JavaScript challenges, which clear on their own, and in
// a visible window for the ones a person has to solve. Nothing here solves a
// captcha.
//
// Chrome claims the same user agent and client hints as tls-client, so the
// cookies it obtains stay valid for the requests that follow.
package chrome
import (
"context"
"errors"
"fmt"
"log/slog"
stdhttp "net/http"
"net/url"
"runtime"
"strings"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/stealth"
"git.security-command.org/Overlord/dibs/internal/fetch"
)
const (
// ChallengeTimeout is how long headless Chrome waits for a bot check to
// clear.
ChallengeTimeout = 30 * time.Second
// HumanTimeout is how long a visible window waits for the user.
HumanTimeout = 10 * time.Minute
poll = time.Second
)
// ErrClosed means the user closed the window before the bot check cleared.
var ErrClosed = errors.New("the browser window was closed")
// Chrome launches a fresh Chrome per visit, with a throwaway profile that
// gets the cookies of the URL's host from the jar. It is safe for concurrent
// use; visits run one at a time.
type Chrome struct {
browser fetch.Browser
jar *fetch.Jar
logger *slog.Logger
// challengeTimeout is ChallengeTimeout, shorter in tests.
challengeTimeout time.Duration
mu sync.Mutex
bin string
}
func New(browser fetch.Browser, jar *fetch.Jar, logger *slog.Logger) *Chrome {
return &Chrome{browser: browser, jar: jar, logger: logger, challengeTimeout: ChallengeTimeout}
}
// Fetch loads rawURL in headless Chrome and gives a bot check up to
// ChallengeTimeout to clear. The page it ends on is returned as a response,
// which is still a Challenge if the check did not clear. Chrome's cookies go
// into the jar either way.
func (c *Chrome) Fetch(ctx context.Context, rawURL string) (*fetch.Response, error) {
return c.visit(ctx, rawURL, true, c.challengeTimeout)
}
// Solve opens rawURL in a visible window for the user to pass a bot check,
// and closes it as soon as the page shows none. It returns the page then,
// or ErrClosed, and keeps Chrome's cookies.
func (c *Chrome) Solve(ctx context.Context, rawURL string) (*fetch.Response, error) {
resp, err := c.visit(ctx, rawURL, false, HumanTimeout)
if err == nil && resp.Verdict == fetch.Challenge { return resp, fmt.Errorf("the bot check did not clear within %s", HumanTimeout) }
return resp, err
}
func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeout time.Duration) (*fetch.Response, error) {
c.mu.Lock()
defer c.mu.Unlock()
start := time.Now()
u, err := url.Parse(rawURL)
if err != nil { return nil, err }
host := strings.ToLower(u.Hostname())
bin, err := c.binary()
if err != nil { return nil, err }
l := launcher.New().Context(ctx).Bin(bin).Leakless(false)
if headless {
// Images are not needed to clear a bot check, and fewer requests
// reach the shop.
l = l.HeadlessNew(true).Set("blink-settings", "imagesEnabled=false")
} else {
l = l.Headless(false)
}
controlURL, err := l.Launch()
if err != nil { return nil, fmt.Errorf("starting %s: %w", bin, err) }
defer l.Cleanup()
defer l.Kill()
b := rod.New().ControlURL(controlURL).Context(ctx)
if err := b.Connect(); err != nil { return nil, fmt.Errorf("connecting to Chrome: %w", err) }
page, err := stealth.Page(b)
if err != nil { return nil, err }
if err := c.identity(host).Call(page); err != nil { return nil, err }
if cookies := c.jar.Export()[host]; len(cookies) > 0 {
if err := b.SetCookies(cookieParams(cookies, u.Scheme)); err != nil { return nil, err }
}
doc := &document{}
go page.EachEvent(func(e *proto.NetworkResponseReceived) {
if e.Type == proto.NetworkResourceTypeDocument && e.FrameID == page.FrameID { doc.set(e.Response) }
})()
if err := page.Navigate(rawURL); err != nil { return nil, err }
_ = page.Timeout(timeout).WaitLoad()
deadline := time.Now().Add(timeout)
for {
resp, err := snapshot(page, rawURL, doc)
switch {
case err != nil && ctx.Err() != nil:
return nil, ctx.Err()
case err != nil && !headless && !alive(b):
return nil, ErrClosed
case err != nil && headless:
return nil, err
case err == nil && (resp.Verdict != fetch.Challenge || time.Now().After(deadline)):
c.keepCookies(page, rawURL, host)
resp.Elapsed = time.Since(start)
return resp, nil
default:
// A page that is navigating has no document to read for a
// moment, and the bot check may still be running.
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(poll):
}
}
}
// binary finds Chrome, Chromium or Edge, and otherwise downloads the
// Chromium build rod is tested with.
func (c *Chrome) binary() (string, error) {
if c.bin != "" { return c.bin, nil }
if bin, ok := launcher.LookPath(); ok {
c.bin = bin
return bin, nil
}
c.logger.Info("no Chrome, Chromium or Edge found, downloading Chromium")
bin, err := launcher.NewBrowser().Get()
if err != nil { return "", fmt.Errorf("no Chrome found and downloading Chromium failed: %w", err) }
c.bin = bin
return bin, nil
}
// identity makes Chrome claim the browser tls-client claims to be.
func (c *Chrome) identity(host string) proto.NetworkSetUserAgentOverride {
var brands, full []*proto.EmulationUserAgentBrandVersion
for _, br := range c.browser.Brands() {
brands = append(brands, &proto.EmulationUserAgentBrandVersion{Brand: br.Name, Version: br.Version})
full = append(full, &proto.EmulationUserAgentBrandVersion{Brand: br.Name, Version: br.Version + ".0.0.0"})
}
arch := "x86"
if runtime.GOARCH == "arm64" { arch = "arm" }
return proto.NetworkSetUserAgentOverride{
UserAgent: c.browser.UserAgent,
AcceptLanguage: fetch.AcceptLanguage(host),
Platform: navigatorPlatform(c.browser.Platform),
UserAgentMetadata: &proto.EmulationUserAgentMetadata{
Brands: brands,
FullVersionList: full,
Platform: c.browser.Platform,
Architecture: arch,
Bitness: "64",
},
}
}
func navigatorPlatform(platform string) string {
switch platform {
case "Windows":
return "Win32"
case "macOS":
return "MacIntel"
default:
return "Linux x86_64"
}
}
// keepCookies copies Chrome's cookies for rawURL into the jar.
func (c *Chrome) keepCookies(page *rod.Page, rawURL, host string) {
cookies, err := page.Cookies([]string{rawURL})
if err != nil {
c.logger.Warn("reading Chrome's cookies failed", "url", rawURL, "err", err)
return
}
now := time.Now()
out := make([]fetch.Cookie, 0, len(cookies))
for _, ck := range cookies {
fc := fetch.Cookie{
Name: ck.Name,
Value: ck.Value,
Domain: strings.TrimPrefix(ck.Domain, "."),
HostOnly: !strings.HasPrefix(ck.Domain, "."),
Path: ck.Path,
Secure: ck.Secure,
HTTPOnly: ck.HTTPOnly,
Set: now,
}
if !ck.Session { fc.Expires = ck.Expires.Time() }
out = append(out, fc)
}
c.jar.Import(host, out)
}
func cookieParams(cookies []fetch.Cookie, scheme string) []*proto.NetworkCookieParam {
out := make([]*proto.NetworkCookieParam, 0, len(cookies))
for _, ck := range cookies {
p := &proto.NetworkCookieParam{Name: ck.Name, Value: ck.Value, Path: ck.Path, Secure: ck.Secure, HTTPOnly: ck.HTTPOnly}
// Chrome sets a cookie without a domain as host-only for the URL.
if ck.HostOnly { p.URL = scheme + "://" + ck.Domain + ck.Path } else { p.Domain = "." + ck.Domain }
if !ck.Expires.IsZero() { p.Expires = proto.TimeSinceEpoch(ck.Expires.Unix()) }
out = append(out, p)
}
return out
}
// document is the status and headers of the page's latest document.
type document struct {
mu sync.Mutex
status int
header stdhttp.Header
}
func (d *document) set(r *proto.NetworkResponse) {
h := stdhttp.Header{}
for k, v := range r.Headers { h.Set(k, v.Str()) }
d.mu.Lock()
defer d.mu.Unlock()
d.status, d.header = r.Status, h
}
func (d *document) get() (int, stdhttp.Header) {
d.mu.Lock()
defer d.mu.Unlock()
if d.status == 0 { return stdhttp.StatusOK, nil }
return d.status, d.header
}
// snapshot classifies the page as it is now.
func snapshot(page *rod.Page, rawURL string, doc *document) (*fetch.Response, error) {
html, err := page.HTML()
if err != nil { return nil, err }
info, err := page.Info()
if err != nil { return nil, err }
status, header := doc.get()
return fetch.NewResponse(rawURL, info.URL, status, header, []byte(html)), nil
}
// alive reports whether Chrome still answers, which it stops doing once the
// user closes its last window.
func alive(b *rod.Browser) bool {
_, err := b.Pages()
return err == nil
}