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
}
+116
View File
@@ -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) }
}
+51
View File
@@ -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
}
+36 -11
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"net/url"
"runtime"
"strconv"
"strings"
http "github.com/bogdanfinn/fhttp"
@@ -83,24 +84,48 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header {
}
}
// secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE
// brand and the brand order from its major version (GenerateBrandVersionList
// in Chromium's user_agent_utils.cc), so a fixed string would stand out after
// an update.
func secCHUA(major int) string {
// Brand is one entry of Chrome's brand list, which sec-ch-ua and
// navigator.userAgentData report.
type Brand struct {
Name string
Version string
}
// Brands is Chrome's brand list. Chrome derives the GREASE brand and the
// brand order from its major version (GenerateBrandVersionList in
// Chromium's user_agent_utils.cc), so a fixed list would stand out after an
// update.
func (b Browser) Brands() []Brand {
return brands(b.Major)
}
func brands(major int) []Brand {
chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"}
versions := []string{"8", "99", "24"}
orders := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
grease := fmt.Sprintf(`"Not%sA%sBrand";v="%s"`, chars[major%len(chars)], chars[(major+1)%len(chars)], versions[major%len(versions)])
grease := Brand{"Not" + chars[major%len(chars)] + "A" + chars[(major+1)%len(chars)] + "Brand", versions[major%len(versions)]}
order := orders[major%len(orders)]
var brands [3]string
brands[order[0]] = grease
brands[order[1]] = fmt.Sprintf(`"Chromium";v="%d"`, major)
brands[order[2]] = fmt.Sprintf(`"Google Chrome";v="%d"`, major)
var out [3]Brand
out[order[0]] = grease
out[order[1]] = Brand{"Chromium", strconv.Itoa(major)}
out[order[2]] = Brand{"Google Chrome", strconv.Itoa(major)}
return strings.Join(brands[:], ", ")
return out[:]
}
func secCHUA(major int) string {
var parts []string
for _, b := range brands(major) { parts = append(parts, fmt.Sprintf(`"%s";v="%s"`, b.Name, b.Version)) }
return strings.Join(parts, ", ")
}
// AcceptLanguage is the Accept-Language a local shopper's browser would
// send to host.
func AcceptLanguage(host string) string {
return acceptLanguage(host)
}
// languages maps a public suffix to the Accept-Language a local shopper's
+5
View File
@@ -21,6 +21,9 @@ const (
Blocked
// HTTPError is any other non-2xx status.
HTTPError
// NeedsHuman is a bot check that headless Chrome could not clear either,
// such as a captcha. classify never returns it.
NeedsHuman
)
func (v Verdict) String() string {
@@ -35,6 +38,8 @@ func (v Verdict) String() string {
return "blocked"
case HTTPError:
return "http-error"
case NeedsHuman:
return "needs-human"
default:
return "unknown"
}
+36
View File
@@ -172,6 +172,42 @@ func TestJarSaveLoad(t *testing.T) {
if err := NewJar().Load(filepath.Join(t.TempDir(), "missing.json")); err != nil { t.Errorf("missing file: %v", err) }
}
// TestJarShared has two processes share a cookie file. Neither may undo the
// other's newer cookies when it saves.
func TestJarShared(t *testing.T) {
path := filepath.Join(t.TempDir(), "cookies.json")
u := mustURL(t, "https://www.amazon.de/")
now := time.Now()
set := func(j *Jar, name, value string, maxAge int) {
j.SetCookies(u, []*fhttp.Cookie{{Name: name, Value: value, Path: "/", Expires: now.Add(time.Hour), MaxAge: maxAge}})
}
watcher, solver := NewJar(), NewJar()
watcher.now = func() time.Time { return now }
solver.now = func() time.Time { return now.Add(time.Minute) }
set(watcher, "session", "old", 0)
set(watcher, "tracking", "x", 0)
if err := watcher.Save(path); err != nil { t.Fatal(err) }
// The solver gets a new session and drops the tracking cookie.
if err := solver.Load(path); err != nil { t.Fatal(err) }
set(solver, "session", "solved", 0)
set(solver, "tracking", "", -1)
if err := solver.Save(path); err != nil { t.Fatal(err) }
// The watcher saves again later, without having seen either change.
watcher.now = func() time.Time { return now.Add(2 * time.Minute) }
if err := watcher.Save(path); err != nil { t.Fatal(err) }
if got := cookieNames(watcher.Cookies(u)); got != "session=solved" { t.Errorf("watcher after saving: %q", got) }
fresh := NewJar()
fresh.now = watcher.now
if err := fresh.Load(path); err != nil { t.Fatal(err) }
if got := cookieNames(fresh.Cookies(u)); got != "session=solved" { t.Errorf("file after both saved: %q", got) }
}
// noLimit lets tests talk to their local server without the host floor.
type noLimit struct{}
+64 -21
View File
@@ -30,17 +30,26 @@ type Cookie struct {
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
Secure bool `json:"secure,omitempty"`
HTTPOnly bool `json:"http_only,omitempty"`
// Set is when the cookie was last set. When dibs processes share a
// cookie file, the newest version of each cookie wins.
Set time.Time `json:"set,omitzero"`
}
func (c Cookie) expired(now time.Time) bool {
return !c.Expires.IsZero() && !c.Expires.After(now)
}
// forgetDeleted is how long a deleted cookie is remembered, so that saving
// does not bring back the copy another process still has on file.
const forgetDeleted = 24 * time.Hour
// Jar is an RFC 6265 cookie jar that remembers every cookie by the host that
// set it, so the cookies can be saved, restored and exported per host.
type Jar struct {
mu sync.Mutex
jar *cookiejar.Jar
mu sync.Mutex
jar *cookiejar.Jar
// cookies keeps deleted and expired cookies too, until forgetDeleted
// has passed.
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
now func() time.Time
}
@@ -115,16 +124,19 @@ func (j *Jar) Export() map[string][]Cookie {
return out
}
// Import adds cookies as if host had set them. Expired cookies are skipped.
// Import adds cookies as if host had set them, unless the jar has a newer
// version. A cookie without a Set time loses to any version in the jar.
func (j *Jar) Import(host string, cookies []Cookie) {
j.mu.Lock()
defer j.mu.Unlock()
host = strings.ToLower(host)
now := j.now()
j.importLocked(strings.ToLower(host), cookies, j.now())
}
// importLocked is Import. Callers hold mu.
func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) {
for _, c := range cookies {
if c.expired(now) { continue }
if have, ok := j.cookies[host][key(c)]; ok && !c.Set.After(have.Set) { continue }
hc := &http.Cookie{
Name: c.Name,
@@ -135,28 +147,52 @@ func (j *Jar) Import(host string, cookies []Cookie) {
HttpOnly: c.HTTPOnly,
}
if !c.HostOnly { hc.Domain = c.Domain }
if c.expired(now) { hc.MaxAge = -1 }
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
j.store(host, c, now)
}
}
// store records c for host, or forgets it when it has expired. Callers hold mu.
func (j *Jar) store(host string, c Cookie, now time.Time) {
key := c.Domain + "|" + c.Path + "|" + c.Name
func key(c Cookie) string { return c.Domain + "|" + c.Path + "|" + c.Name }
if c.expired(now) {
delete(j.cookies[host], key)
return
}
// store records c for host. Callers hold mu.
func (j *Jar) store(host string, c Cookie, now time.Time) {
if c.Set.IsZero() { c.Set = now }
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
j.cookies[host][key] = c
j.cookies[host][key(c)] = c
}
// Save writes the live cookies to path, readable only by the user.
// Save writes the cookies to path, readable only by the user. Other dibs
// processes may share the file, so it first takes in their newer cookies.
func (j *Jar) Save(path string) error {
data, err := json.MarshalIndent(j.Export(), "", " ")
unlock, err := fsutil.Lock(path + ".lock")
if err != nil { return err }
defer unlock()
saved, err := readCookies(path)
if err != nil { return err }
j.mu.Lock()
now := j.now()
for host, cookies := range saved { j.importLocked(host, cookies, now) }
out := map[string][]Cookie{}
for host, byKey := range j.cookies {
for _, k := range slices.Sorted(maps.Keys(byKey)) {
c := byKey[k]
if c.expired(now) && now.Sub(c.Set) > forgetDeleted {
delete(byKey, k)
continue
}
out[host] = append(out[host], c)
}
}
j.mu.Unlock()
data, err := json.MarshalIndent(out, "", " ")
if err != nil { return err }
return fsutil.WriteFileAtomic(path, data, 0o600)
@@ -164,18 +200,25 @@ func (j *Jar) Save(path string) error {
// Load imports the cookies saved at path. A missing file is not an error.
func (j *Jar) Load(path string) error {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) { return nil }
saved, err := readCookies(path)
if err != nil { return err }
var saved map[string][]Cookie
if err := json.Unmarshal(data, &saved); err != nil { return err }
for host, cookies := range saved { j.Import(host, cookies) }
return nil
}
func readCookies(path string) (map[string][]Cookie, error) {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) { return nil, nil }
if err != nil { return nil, err }
var saved map[string][]Cookie
if err := json.Unmarshal(data, &saved); err != nil { return nil, err }
return saved, nil
}
// defaultPath is the RFC 6265 default-path of a request path.
func defaultPath(p string) string {
if p == "" || p[0] != '/' { return "/" }
+9
View File
@@ -81,6 +81,15 @@ func (n *Notifier) Send(ctx context.Context, a alert.Alert) error {
return errors.Join(errs...)
}
// Notice shows a desktop notification that is not an alert, such as a
// request to solve a captcha. It does nothing when desktop notifications
// are off.
func (n *Notifier) Notice(title, message string) error {
if !n.desktop { return nil }
return n.showToast(title, message)
}
// Channels says where alerts go, for the startup log.
func (n *Notifier) Channels() []string {
var out []string
+5 -1
View File
@@ -24,6 +24,10 @@ const (
backoffBase = 2 * time.Minute
backoffCap = 30 * time.Minute
// recheck caps each sleep of a waiting request, so that a cleared
// backoff lets it go soon.
recheck = 5 * time.Second
)
// HostState is what the limiter remembers about a host. It is persisted so
@@ -144,7 +148,7 @@ func (l *Limiter) wait(ctx context.Context, host, checkURL string) error {
if reserved { return nil }
select {
case <-l.clock.After(at.Sub(l.clock.Now())):
case <-l.clock.After(min(at.Sub(l.clock.Now()), recheck)):
case <-ctx.Done():
return ctx.Err()
}
+37 -6
View File
@@ -38,6 +38,9 @@ type Controller interface {
PauseAll(paused bool)
CheckNow(item string) bool
Reload() ([]string, error)
// Solve opens a visible browser on fetchURL for the user to pass its
// bot check. It blocks until the check is passed or the window closes.
Solve(fetchURL string) error
}
// CheckMsg is one finished check and what the alert engine made of it.
@@ -58,15 +61,20 @@ type (
url string
err error
}
solveMsg struct {
host string
err error
}
)
// Status texts, as the STATUS column shows them.
const (
statusWatching = "watching"
statusAvailable = "AVAILABLE"
statusBlocked = "blocked"
statusError = "error"
statusPaused = "paused"
statusWatching = "watching"
statusAvailable = "AVAILABLE"
statusBlocked = "blocked"
statusNeedsHuman = "needs-human"
statusError = "error"
statusPaused = "paused"
)
// result is what the last check of a URL found.
@@ -100,6 +108,7 @@ type Model struct {
noteError bool
noteTime time.Time
reloading bool
solving string // the host whose bot check is open in a browser
}
// New returns the TUI for ctl. path is the config file, and logs is the
@@ -157,6 +166,10 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.widths = nil
m.clampCursor()
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
case solveMsg:
m.solving = ""
if msg.err != nil { m.setNote("bot check on "+msg.host+" not solved: "+msg.err.Error(), true) } else { m.setNote("bot check on "+msg.host+" solved, checking again", false) }
m.rows = m.ctl.Statuses()
case openMsg:
if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) }
case tea.KeyPressMsg:
@@ -200,6 +213,8 @@ func statusOf(c CheckMsg) string {
switch {
case rep == nil:
return statusError
case rep.Verdict == fetch.NeedsHuman.String():
return statusNeedsHuman
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
return statusBlocked
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
@@ -285,7 +300,9 @@ func (m *Model) rowKey(k string) tea.Cmd {
case "o":
return open(row.FetchURL)
case "enter":
if r := m.results[row.URL]; r != nil && r.cartLink != "" { return open(r.cartLink) }
r := m.results[row.URL]
if r != nil && r.status == statusNeedsHuman { return m.solve(row) }
if r != nil && r.cartLink != "" { return open(r.cartLink) }
m.setNote("no cart link yet, opening the product page", false)
return open(row.FetchURL)
@@ -294,6 +311,20 @@ func (m *Model) rowKey(k string) tea.Cmd {
return nil
}
// solve opens the row's page in a browser for the user. One bot check is
// open at a time.
func (m *Model) solve(row watch.Status) tea.Cmd {
if m.solving != "" {
m.setNote("a browser is already open for "+m.solving, true)
return nil
}
m.solving = row.Host
m.setNote("pass the bot check in the Chrome window; it closes by itself", false)
return func() tea.Msg { return solveMsg{host: row.Host, err: m.ctl.Solve(row.FetchURL)} }
}
// pauseAll pauses every URL, or resumes them all if all are paused.
func (m *Model) pauseAll() {
pause := false
+17 -13
View File
@@ -22,6 +22,7 @@ var (
yellow = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
red = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
blue = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
magenta = lipgloss.NewStyle().Foreground(lipgloss.Color("13")).Bold(true)
selected = lipgloss.NewStyle().Reverse(true)
flashing = lipgloss.NewStyle().Background(lipgloss.Color("10")).Foreground(lipgloss.Color("0")).Bold(true)
)
@@ -34,14 +35,14 @@ var columns = []struct {
title string
min, max int
} {
{"ITEM", 8, 32},
{"SHOP", 4, 12},
{"TLD", 3, 6},
{"STATUS", 9, 9},
{"PRICE", 5, 16},
{"SELLER", 6, 11},
{"LAST", 10, 10},
{"NEXT", 9, 9},
{"ITEM", 8, 32},
{"SHOP", 4, 12},
{"TLD", 3, 6},
{"STATUS", 11, 11},
{"PRICE", 5, 16},
{"SELLER", 6, 11},
{"LAST", 10, 10},
{"NEXT", 9, 9},
}
// layout sizes the table and the log pane to the window.
@@ -160,6 +161,8 @@ func statusStyle(status string) lipgloss.Style {
return green
case statusBlocked:
return yellow
case statusNeedsHuman:
return magenta
case statusError:
return red
case statusPaused:
@@ -208,10 +211,11 @@ func (m *Model) statusBar() string {
status string
style lipgloss.Style
} {
{statusAvailable, green},
{statusBlocked, yellow},
{statusError, red},
{statusPaused, faint},
{statusAvailable, green},
{statusNeedsHuman, magenta},
{statusBlocked, yellow},
{statusError, red},
{statusPaused, faint},
} {
if n := m.count(s.status); n > 0 { parts = append(parts, s.style.Render(fmt.Sprintf("%d %s", n, s.status))) }
}
@@ -233,7 +237,7 @@ func (m *Model) statusBar() string {
func (m *Model) help() string {
if m.logFocus { return "↑↓ pgup pgdn scroll · l/esc back to the table · r reload · q quit" }
return "↑↓ select · p pause · P pause all · c check now · o open page · enter cart · l log · r reload · q quit"
return "↑↓ select · p pause · P pause all · c check now · o open page · enter cart or bot check · l log · r reload · q quit"
}
// count is the number of rows showing status.
+19 -6
View File
@@ -295,7 +295,7 @@ func RecordOutcome(l *ratelimit.Limiter, host string, resp *fetch.Response, err
return 0
case err != nil:
return l.Failure(host)
case resp.Verdict == fetch.Challenge || resp.Verdict == fetch.Blocked || resp.Verdict == fetch.HTTPError:
case resp.Verdict == fetch.Challenge || resp.Verdict == fetch.NeedsHuman || resp.Verdict == fetch.Blocked || resp.Verdict == fetch.HTTPError:
return l.Failure(host)
default:
l.Success(host)
@@ -320,16 +320,29 @@ func (s *Scheduler) PauseAll(paused bool) {
// CheckNow moves the checks of the item called name forward, as far as the
// URL floor allows. It reports whether there is such an item.
func (s *Scheduler) CheckNow(name string) bool {
found := s.each(func(t *target) bool { return t.item.Name == name }, func(t *target) {
ready := s.limiter.URLReady(t.fetchURL)
if now := s.clock.Now(); ready.Before(now) { ready = now }
if ready.Before(t.next) { t.next = ready }
})
found := s.each(func(t *target) bool { return t.item.Name == name }, s.soon)
s.poke()
return found
}
// soon moves the check of t forward to the earliest time the URL floor
// allows. Callers hold mu.
func (s *Scheduler) soon(t *target) {
ready := s.limiter.URLReady(t.fetchURL)
if now := s.clock.Now(); ready.Before(now) { ready = now }
if ready.Before(t.next) { t.next = ready }
}
// CheckHost moves the checks of every URL on host forward, as far as the
// URL floor allows.
func (s *Scheduler) CheckHost(host string) {
host = strings.ToLower(host)
s.each(func(t *target) bool { return t.host == host }, s.soon)
s.poke()
}
// Statuses returns a snapshot of every URL, in config order.
func (s *Scheduler) Statuses() []Status {
s.mu.Lock()