// 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 and humanTimeout are ChallengeTimeout and // HumanTimeout, shorter in tests. challengeTimeout time.Duration humanTimeout 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, humanTimeout: HumanTimeout} } // 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, c.humanTimeout) if err == nil && resp.Verdict == fetch.Challenge { return resp, fmt.Errorf("the bot check did not clear within %s", c.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()) b, cleanup, err := c.launch(ctx, headless) if err != nil { return nil, err } defer cleanup() page, err := c.open(b, u, host) if 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): } } } // ClickTimeout is how long Click waits for the page a click leads to. const ClickTimeout = 30 * time.Second // Click loads rawURL in headless Chrome, clicks the element sel matches and // returns the page the click leads to. Page scripts run as for a user, so // shops that only accept forms their scripts have seen work. wait is called // between loading and clicking, for the rate limits. Chrome's cookies go // into the jar. func (c *Chrome) Click(ctx context.Context, rawURL, sel string, wait func() error) (*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()) b, cleanup, err := c.launch(ctx, true) if err != nil { return nil, err } defer cleanup() page, err := c.open(b, u, host) if 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 } if err := page.Timeout(ClickTimeout).WaitLoad(); err != nil { return nil, fmt.Errorf("loading %s: %w", rawURL, err) } el, err := page.Timeout(ClickTimeout).Element(sel) if err != nil { return nil, fmt.Errorf("no %s on %s: %w", sel, rawURL, err) } if err := wait(); err != nil { return nil, err } navigated := page.Timeout(ClickTimeout).WaitNavigation(proto.PageLifecycleEventNameLoad) // A script click works even when a banner, such as a cookie notice, // covers the element. if _, err := el.Eval("() => this.click()"); err != nil { return nil, fmt.Errorf("clicking %s: %w", sel, err) } navigated() if ctx.Err() != nil { return nil, ctx.Err() } resp, err := snapshot(page, rawURL, doc) if err != nil { return nil, err } c.keepCookies(page, resp.FinalURL, host) resp.Elapsed = time.Since(start) return resp, nil } // SignIn opens rawURL in a visible window for the user to sign in to a shop. // When the window is closed, or after HumanTimeout, the cookies Chrome has // for rawURL's host go into the jar. It returns how many there were. func (c *Chrome) SignIn(ctx context.Context, rawURL string) (int, error) { return c.signIn(ctx, rawURL, false) } func (c *Chrome) signIn(ctx context.Context, rawURL string, headless bool) (int, error) { c.mu.Lock() defer c.mu.Unlock() u, err := url.Parse(rawURL) if err != nil { return 0, err } host := strings.ToLower(u.Hostname()) b, cleanup, err := c.launch(ctx, headless) if err != nil { return 0, err } defer cleanup() page, err := c.open(b, u, host) if err != nil { return 0, err } if err := page.Navigate(rawURL); err != nil { return 0, err } deadline := time.After(c.humanTimeout) // Once the window is closed, Chrome's cookies are out of reach, so the // latest copy is kept while it is open. var last []*proto.NetworkCookie watch: for { cookies, err := b.GetCookies() if err != nil || !alive(b) { break } last = cookies select { case <-ctx.Done(): return 0, ctx.Err() case <-deadline: break watch case <-time.After(poll): } } now := time.Now() kept := make([]fetch.Cookie, 0, len(last)) for _, ck := range last { if domainMatch(host, strings.TrimPrefix(ck.Domain, ".")) { kept = append(kept, fromChrome(ck, now)) } } c.jar.Import(host, kept) return len(kept), nil } // launch starts Chrome and connects to it. cleanup stops it and removes its // profile. func (c *Chrome) launch(ctx context.Context, headless bool) (*rod.Browser, func(), error) { bin, err := c.binary() if err != nil { return nil, 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, nil, fmt.Errorf("starting %s: %w", bin, err) } cleanup := func() { l.Kill() l.Cleanup() } b := rod.New().ControlURL(controlURL).Context(ctx) if err := b.Connect(); err != nil { cleanup() return nil, nil, fmt.Errorf("connecting to Chrome: %w", err) } return b, cleanup, nil } // open creates a page that claims tls-client's identity and has the jar's // cookies for host. func (c *Chrome) open(b *rod.Browser, u *url.URL, host string) (*rod.Page, error) { 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 } } return page, nil } // 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 { out = append(out, fromChrome(ck, now)) } c.jar.Import(host, out) } func fromChrome(ck *proto.NetworkCookie, now time.Time) fetch.Cookie { c := 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 { c.Expires = ck.Expires.Time() } return c } // domainMatch reports whether a cookie for domain is sent to host. func domainMatch(host, domain string) bool { host, domain = strings.ToLower(host), strings.ToLower(domain) return host == domain || strings.HasSuffix(host, "."+domain) } 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 has a window open. On Linux and // Windows, Chrome exits with its last window; on macOS, it keeps running // without one. func alive(b *rod.Browser) bool { pages, err := b.Pages() return err == nil && len(pages) > 0 }