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:
1 parent
f2ea1297e8
commit
e2cbc1a55c
20 files changed
+905
-73
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package chrome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
fhttp "github.com/bogdanfinn/fhttp"
|
||||
"github.com/go-rod/rod/lib/launcher"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
|
||||
// challengeServer answers /item with a JavaScript challenge until the
|
||||
// browser has run it, which sets a clearance cookie, and /stuck with one
|
||||
// that never clears. Past the challenge it shows what the browser sent.
|
||||
func challengeServer() *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := r.Cookie("clearance"); err != nil || r.URL.Path == "/stuck" {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = io.WriteString(w, `<html><head><title>Just a moment...</title><script>window._cf_chl_opt = {};
|
||||
if (location.pathname === "/item") { document.cookie = "clearance=ok; path=/"; setTimeout(() => location.reload(), 300) }
|
||||
</script></head><body>Checking your browser</body></html>`)
|
||||
return
|
||||
}
|
||||
|
||||
session := ""
|
||||
if ck, err := r.Cookie("session"); err == nil { session = ck.Value }
|
||||
|
||||
_, _ = fmt.Fprintf(w, "<html><body><p id=ua>%s</p><p id=ch>%s</p><p id=session>%s</p></body></html>",
|
||||
r.UserAgent(), r.Header.Get("Sec-Ch-Ua"), session)
|
||||
}))
|
||||
}
|
||||
|
||||
func newChrome(t *testing.T) (*Chrome, *fetch.Jar) {
|
||||
t.Helper()
|
||||
|
||||
if testing.Short() { t.Skip("starts Chrome") }
|
||||
if _, ok := launcher.LookPath(); !ok { t.Skip("no Chrome, Chromium or Edge installed") }
|
||||
|
||||
jar := fetch.NewJar()
|
||||
c := New(fetch.DefaultBrowser(), jar, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
c.challengeTimeout = 5 * time.Second
|
||||
|
||||
return c, jar
|
||||
}
|
||||
|
||||
func TestFetchClearsChallenge(t *testing.T) {
|
||||
c, jar := newChrome(t)
|
||||
srv := challengeServer()
|
||||
defer srv.Close()
|
||||
|
||||
u, _ := url.Parse(srv.URL + "/item")
|
||||
jar.SetCookies(u, []*fhttp.Cookie{{Name: "session", Value: "from-the-jar", Path: "/"}})
|
||||
|
||||
resp, err := c.Fetch(context.Background(), u.String())
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
body := string(resp.Body)
|
||||
browser := fetch.DefaultBrowser()
|
||||
|
||||
if resp.Verdict != fetch.OK { t.Fatalf("verdict %s, want ok: %s", resp.Verdict, body) }
|
||||
if !strings.Contains(body, browser.UserAgent) { t.Errorf("Chrome did not claim the user agent of tls-client: %s", body) }
|
||||
if !strings.Contains(body, fmt.Sprintf(`"Chromium";v="%d"`, browser.Major)) { t.Errorf("Chrome did not claim the client hints of tls-client: %s", body) }
|
||||
if !strings.Contains(body, "from-the-jar") { t.Errorf("Chrome did not send the jar's cookies: %s", body) }
|
||||
|
||||
got := ""
|
||||
for _, ck := range jar.Cookies(u) { got += ck.Name + "=" + ck.Value + " " }
|
||||
if !strings.Contains(got, "clearance=ok") { t.Errorf("the clearance cookie did not reach the jar: %s", got) }
|
||||
}
|
||||
|
||||
func TestFetchGivesUp(t *testing.T) {
|
||||
c, _ := newChrome(t)
|
||||
srv := challengeServer()
|
||||
defer srv.Close()
|
||||
|
||||
start := time.Now()
|
||||
resp, err := c.Fetch(context.Background(), srv.URL+"/stuck")
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
if resp.Verdict != fetch.Challenge { t.Errorf("verdict %s, want challenge", resp.Verdict) }
|
||||
if d := time.Since(start); d > 20*time.Second { t.Errorf("gave up after %s", d) }
|
||||
}
|
||||
|
||||
type noLimit struct{}
|
||||
|
||||
func (noLimit) WaitCheck(context.Context, string) error { return nil }
|
||||
|
||||
func TestPipelineEscalates(t *testing.T) {
|
||||
c, jar := newChrome(t)
|
||||
srv := challengeServer()
|
||||
defer srv.Close()
|
||||
|
||||
client, err := fetch.New(fetch.Options{Limiter: noLimit{}, Jar: jar})
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
p := &Pipeline{Client: client, Chrome: c, Limiter: noLimit{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
||||
|
||||
for path, want := range map[string]fetch.Verdict{"/item": fetch.OK, "/stuck": fetch.NeedsHuman} {
|
||||
resp, err := p.Get(context.Background(), srv.URL+path)
|
||||
if err != nil { t.Fatal(err) }
|
||||
if resp.Verdict != want { t.Errorf("%s: verdict %s, want %s", path, resp.Verdict, want) }
|
||||
}
|
||||
|
||||
// Chrome's clearance cookie lets tls-client through on its own now.
|
||||
resp, err := client.Get(context.Background(), srv.URL+"/item")
|
||||
if err != nil { t.Fatal(err) }
|
||||
if resp.Verdict != fetch.OK { t.Errorf("tls-client after Chrome: verdict %s", resp.Verdict) }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package chrome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
|
||||
// Limiter is ratelimit.Limiter.
|
||||
type Limiter interface {
|
||||
WaitCheck(ctx context.Context, url string) error
|
||||
}
|
||||
|
||||
// Pipeline fetches pages the way the shops expect a browser to, escalating
|
||||
// only on failure: tls-client first, then headless Chrome when a bot check
|
||||
// answers. A bot check Chrome cannot clear either comes back as
|
||||
// fetch.NeedsHuman.
|
||||
type Pipeline struct {
|
||||
Client *fetch.Client
|
||||
// Chrome may be nil, which leaves bot checks as they are.
|
||||
Chrome *Chrome
|
||||
Limiter Limiter
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
func (p *Pipeline) Get(ctx context.Context, rawURL string) (*fetch.Response, error) {
|
||||
resp, err := p.Client.Get(ctx, rawURL)
|
||||
if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil { return resp, err }
|
||||
|
||||
p.Logger.Info("bot check, retrying in headless Chrome once the rate limits allow", "url", rawURL, "challenge", resp.Challenge)
|
||||
|
||||
// Chrome's visit is a check of the URL like any other.
|
||||
if err := p.Limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err }
|
||||
|
||||
cr, err := p.Chrome.Fetch(ctx, rawURL)
|
||||
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
return nil, ctx.Err()
|
||||
case err != nil:
|
||||
p.Logger.Warn("headless Chrome failed", "url", rawURL, "err", err)
|
||||
return resp, nil
|
||||
case cr.Verdict == fetch.Challenge:
|
||||
cr.Verdict = fetch.NeedsHuman
|
||||
default:
|
||||
p.Logger.Info("headless Chrome cleared the bot check", "url", rawURL, "challenge", resp.Challenge)
|
||||
}
|
||||
|
||||
return cr, nil
|
||||
}
|
||||
Reference in new issue
Block a user