diff --git a/cmd/dibs/check.go b/cmd/dibs/check.go index b3e144d..81c75b4 100644 --- a/cmd/dibs/check.go +++ b/cmd/dibs/check.go @@ -19,7 +19,8 @@ import ( // printed as JSON. func runCheck(args []string, stdout, stderr io.Writer) int { flags, configPath := newFlagSet("dibs check", stderr) - shop := flags.String("shop", "", "plugin to use (default: the first whose matches() accepts the URL)") + shop := flags.String("shop", "", "plugin to use (default: the first whose matches() accepts the URL)") + useChrome := flags.Bool("chrome", false, "fetch with headless Chrome instead of tls-client") pos, ok := parseArgs(flags, args) if !ok { return 2 } @@ -51,7 +52,10 @@ func runCheck(args []string, stdout, stderr io.Writer) int { e, err := openEnv(logger) if err != nil { return fail(stderr, "check", err) } - resp, err := e.fetch(ctx, fetchURL, logger) + get := e.pipeline.Get + if *useChrome { get = e.chromeGet } + + resp, err := e.fetch(ctx, fetchURL, get, logger) if err != nil { return fail(stderr, "check", err) } report, err := plugin.Evaluate(ctx, p, url, resp) diff --git a/cmd/dibs/env.go b/cmd/dibs/env.go index d296be1..2487dad 100644 --- a/cmd/dibs/env.go +++ b/cmd/dibs/env.go @@ -8,6 +8,7 @@ import ( "path/filepath" "time" + "git.security-command.org/Overlord/dibs/internal/chrome" "git.security-command.org/Overlord/dibs/internal/fetch" "git.security-command.org/Overlord/dibs/internal/ratelimit" "git.security-command.org/Overlord/dibs/internal/state" @@ -17,11 +18,13 @@ import ( // env is what every command that talks to shops shares with every other // dibs process: the state file behind the rate limits, and the cookies. type env struct { - dir string - store *state.Store - limiter *ratelimit.Limiter - jar *fetch.Jar - client *fetch.Client + dir string + store *state.Store + limiter *ratelimit.Limiter + jar *fetch.Jar + client *fetch.Client + chrome *chrome.Chrome + pipeline *chrome.Pipeline } func openEnv(logger *slog.Logger) (*env, error) { @@ -37,7 +40,17 @@ func openEnv(logger *slog.Logger) (*env, error) { client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar}) if err != nil { return nil, err } - return &env{dir: dir, store: store, limiter: limiter, jar: jar, client: client}, nil + browser := chrome.New(fetch.DefaultBrowser(), jar, logger) + + return &env{ + dir: dir, + store: store, + limiter: limiter, + jar: jar, + client: client, + chrome: browser, + pipeline: &chrome.Pipeline{Client: client, Chrome: browser, Limiter: limiter, Logger: logger}, + }, nil } // save writes the cookies, and reports trouble with the state file. @@ -63,13 +76,17 @@ func (e *env) explainWait(fetchURL string, logger *slog.Logger) { } } -// fetch makes a single check of fetchURL that counts like a scheduled one: -// the client waits for its turn, and the outcome is recorded for every dibs -// process. -func (e *env) fetch(ctx context.Context, fetchURL string, logger *slog.Logger) (*fetch.Response, error) { +// getter is one way to fetch a page: env.pipeline.Get, env.client.Get or +// env.chromeGet. +type getter func(ctx context.Context, url string) (*fetch.Response, error) + +// fetch makes a single check of fetchURL with get that counts like a +// scheduled one: it waits for its turn, and the outcome is recorded for +// every dibs process. +func (e *env) fetch(ctx context.Context, fetchURL string, get getter, logger *slog.Logger) (*fetch.Response, error) { e.explainWait(fetchURL, logger) - resp, err := e.client.Get(ctx, fetchURL) + resp, err := get(ctx, fetchURL) if ctx.Err() == nil { if u, perr := url.Parse(fetchURL); perr == nil { if d := watch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) } @@ -80,3 +97,11 @@ func (e *env) fetch(ctx context.Context, fetchURL string, logger *slog.Logger) ( return resp, err } + +// chromeGet fetches with headless Chrome only, after the rate limits allow +// it. +func (e *env) chromeGet(ctx context.Context, fetchURL string) (*fetch.Response, error) { + if err := e.limiter.WaitCheck(ctx, fetchURL); err != nil { return nil, err } + + return e.chrome.Fetch(ctx, fetchURL) +} diff --git a/cmd/dibs/fixtures.go b/cmd/dibs/fixtures.go index 96d5b18..cbb97d5 100644 --- a/cmd/dibs/fixtures.go +++ b/cmd/dibs/fixtures.go @@ -75,7 +75,8 @@ func fetchFixture(ctx context.Context, e *env, p *plugin.Plugin, suite fixtures. fetchURL, err := p.Normalize(ctx, c.URL) if err != nil { return err } - resp, err := e.fetch(ctx, fetchURL, logger) + // The saved page is what the shop sent, not what Chrome made of it. + resp, err := e.fetch(ctx, fetchURL, e.client.Get, logger) if err != nil { return err } report, err := plugin.Evaluate(ctx, p, c.URL, resp) diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 7e9ed83..485390d 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -20,7 +20,8 @@ var version = "dev" const usage = `Usage: dibs [--config FILE] [--headless] watch items (TUI unless --headless) - dibs check [--shop NAME] fetch and parse one URL, print JSON + dibs check [--shop NAME] [--chrome] fetch and parse one URL, print JSON + dibs solve [--shop NAME] pass a bot check in a Chrome window dibs plugin test [--status CODE] [url] dibs config validate [--config FILE] dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel @@ -48,6 +49,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runFixtures(args[1:], stdout, stderr) case "notify": return runNotify(args[1:], stdout, stderr) + case "solve": + return runSolve(args[1:], stdout, stderr) case "help", "-h", "--help": _, _ = fmt.Fprint(stdout, usage) return 0 diff --git a/cmd/dibs/solve.go b/cmd/dibs/solve.go new file mode 100644 index 0000000..d14bcc7 --- /dev/null +++ b/cmd/dibs/solve.go @@ -0,0 +1,58 @@ +package main + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "os/signal" +) + +// runSolve implements `dibs solve [--shop NAME] `: it opens the URL in +// a visible Chrome window for the user to pass a bot check, and keeps the +// cookies for every dibs process. +func runSolve(args []string, stdout, stderr io.Writer) int { + flags, configPath := newFlagSet("dibs solve", stderr) + shop := flags.String("shop", "", "plugin to normalize the URL with (default: the first whose matches() accepts it)") + + pos, ok := parseArgs(flags, args) + if !ok { return 2 } + if len(pos) != 1 { + _, _ = fmt.Fprintf(stderr, "dibs solve: expected one URL\n\n%s", usage) + return 2 + } + + cfg, ok := loadOptionalConfig(*configPath, stderr) + if !ok { return 1 } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + host, err := newHost(cfg, logger) + if err != nil { return fail(stderr, "solve", err) } + defer host.Close() + + p, err := pickPlugin(ctx, host, *shop, pos[0]) + if err != nil { return fail(stderr, "solve", err) } + + fetchURL, err := p.Normalize(ctx, pos[0]) + if err != nil { return fail(stderr, "solve", err) } + + e, err := openEnv(logger) + if err != nil { return fail(stderr, "solve", err) } + + _, _ = fmt.Fprintln(stdout, "Pass the bot check in the Chrome window. It closes by itself once the page shows up.") + + if _, err := e.chrome.Solve(ctx, fetchURL); err != nil { return fail(stderr, "solve", err) } + + u, _ := url.Parse(fetchURL) + e.limiter.Success(u.Hostname()) + e.save(logger) + + _, _ = fmt.Fprintf(stdout, "Solved. The cookies for %s are saved; a running dibs uses them once its current backoff for the host ends.\n", u.Hostname()) + return 0 +} diff --git a/cmd/dibs/watch.go b/cmd/dibs/watch.go index a30723f..ed13292 100644 --- a/cmd/dibs/watch.go +++ b/cmd/dibs/watch.go @@ -5,8 +5,10 @@ import ( "errors" "io" "log/slog" + "net/url" "os" "os/signal" + "strings" "sync" "syscall" "time" @@ -77,6 +79,9 @@ type watcher struct { // retired are the hosts reloads replaced. Checks that started before a // reload may still use them, so they are closed on exit. retired []*plugin.Host + // humans are the hosts whose bot check needs the user, so the user is + // told once, not on every retry. + humans map[string]bool sends sync.WaitGroup } @@ -103,6 +108,7 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch sched: sched, rates: fx.New(e.store, e.limiter), checkLevel: checkLevel, + humans: map[string]bool{}, } w.apply(cfg, host) @@ -131,6 +137,22 @@ func (w *watcher) apply(cfg *config.Config, host *plugin.Host) { func (w *watcher) run(observe func(check)) { go w.sched.Run(w.ctx) + // Saving also takes in the cookies other dibs processes saved, such as + // those of a `dibs solve` for a host that is backed off here. + go func() { + t := time.NewTicker(time.Minute) + defer t.Stop() + + for { + select { + case <-w.ctx.Done(): + return + case <-t.C: + w.env.save(w.logger) + } + } + }() + for r := range w.sched.Results() { w.env.save(w.logger) observe(w.consider(r)) @@ -147,6 +169,8 @@ func (w *watcher) consider(r watch.Result) check { alerts, notifier := w.alerts, w.notifier w.mu.Unlock() + w.trackHuman(notifier, r) + c.Decision, c.PriceErr = alerts.Consider(w.ctx, r.Item, r.Report, r.Time) switch { @@ -185,6 +209,60 @@ func (w *watcher) fire(n *notify.Notifier, a alert.Alert) { }) } +// trackHuman tells the user, once per host, when a bot check needs them, +// and forgets it when the host lets dibs through again. +func (w *watcher) trackHuman(n *notify.Notifier, r watch.Result) { + u, err := url.Parse(r.Report.FetchURL) + if err != nil { return } + + host := strings.ToLower(u.Hostname()) + + w.mu.Lock() + known := w.humans[host] + + switch r.Report.Verdict { + case fetch.NeedsHuman.String(): + w.humans[host] = true + case fetch.OK.String(), fetch.NotFound.String(): + delete(w.humans, host) + } + w.mu.Unlock() + + if known || r.Report.Verdict != fetch.NeedsHuman.String() { return } + + w.logger.Warn("a bot check needs you: press enter on the row in the TUI, or run dibs solve with the URL", "host", host, "url", r.Report.FetchURL) + + if err := n.Notice("dibs needs you on "+host, "A bot check only a person can pass blocks "+host+". Open dibs to solve it."); err != nil { + w.logger.Warn("desktop notification failed", "err", err) + } +} + +// Solve opens fetchURL in a visible Chrome window for the user to pass its +// bot check. Afterwards the host is no longer backed off, and its URLs are +// checked again as soon as the URL floor allows. +func (w *watcher) Solve(fetchURL string) error { + u, err := url.Parse(fetchURL) + if err != nil { return err } + + host := strings.ToLower(u.Hostname()) + + w.logger.Info("opening Chrome for the bot check", "url", fetchURL) + + if _, err := w.env.chrome.Solve(w.ctx, fetchURL); err != nil { return err } + + w.env.limiter.Success(host) + w.env.save(w.logger) + + w.mu.Lock() + delete(w.humans, host) + w.mu.Unlock() + + w.sched.CheckHost(host) + w.logger.Info("bot check solved, checking again", "host", host) + + return nil +} + // close waits for the notifications still being sent and releases the // plugins. func (w *watcher) close() { diff --git a/go.mod b/go.mod index 8a50fd7..a2b0c00 100644 --- a/go.mod +++ b/go.mod @@ -37,6 +37,8 @@ require ( github.com/cloudflare/circl v1.6.5 // indirect github.com/esiqveland/notify v0.13.3 // indirect github.com/go-ole/go-ole v1.3.0 // indirect + github.com/go-rod/rod v0.116.2 // indirect + github.com/go-rod/stealth v0.4.9 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/jackmordaunt/icns/v3 v3.0.1 // indirect github.com/klauspost/compress v1.18.2 // indirect @@ -51,6 +53,11 @@ require ( github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect github.com/xo/terminfo v1.0.0 // indirect + github.com/ysmood/fetchup v0.2.3 // indirect + github.com/ysmood/goob v0.4.0 // indirect + github.com/ysmood/got v0.40.0 // indirect + github.com/ysmood/gson v0.7.3 // indirect + github.com/ysmood/leakless v0.9.0 // indirect golang.org/x/crypto v0.57.0 // indirect golang.org/x/sync v0.23.0 // indirect golang.org/x/text v0.42.0 // indirect diff --git a/go.sum b/go.sum index 2cfa751..48d7509 100644 --- a/go.sum +++ b/go.sum @@ -57,6 +57,11 @@ github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWD github.com/gen2brain/beeep v0.11.2/go.mod h1:jQVvuwnLuwOcdctHn/uyh8horSBNJ8uGb9Cn2W4tvoc= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-rod/rod v0.113.0/go.mod h1:aiedSEFg5DwG/fnNbUOTPMTTWX3MRj6vIs/a684Mthw= +github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA= +github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg= +github.com/go-rod/stealth v0.4.9 h1:X2PmQk4DUF2wzw6GOsWjW/glb8K5ebnftbEvLh7MlZ4= +github.com/go-rod/stealth v0.4.9/go.mod h1:eAzyvw8c0iAd5nJJsSWeh0fQ5z94vCIfdi1hUmYDimc= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o= @@ -101,6 +106,20 @@ github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/ysmood/fetchup v0.2.3 h1:ulX+SonA0Vma5zUFXtv52Kzip/xe7aj4vqT5AJwQ+ZQ= +github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cOOkYGns= +github.com/ysmood/goob v0.4.0 h1:HsxXhyLBeGzWXnqVKtmT9qM7EuVs/XOgkX7T6r1o1AQ= +github.com/ysmood/goob v0.4.0/go.mod h1:u6yx7ZhS4Exf2MwciFr6nIM8knHQIE22lFpWHnfql18= +github.com/ysmood/gop v0.0.2/go.mod h1:rr5z2z27oGEbyB787hpEcx4ab8cCiPnKxn0SUHt6xzk= +github.com/ysmood/got v0.34.1/go.mod h1:yddyjq/PmAf08RMLSwDjPyCvHvYed+WjHnQxpH851LM= +github.com/ysmood/got v0.40.0 h1:ZQk1B55zIvS7zflRrkGfPDrPG3d7+JOza1ZkNxcc74Q= +github.com/ysmood/got v0.40.0/go.mod h1:W7DdpuX6skL3NszLmAsC5hT7JAhuLZhByVzHTq874Qg= +github.com/ysmood/gotrace v0.6.0/go.mod h1:TzhIG7nHDry5//eYZDYcTzuJLYQIkykJzCRIo4/dzQM= +github.com/ysmood/gson v0.7.3 h1:QFkWbTH8MxyUTKPkVWAENJhxqdBa4lYTQWqZCiLG6kE= +github.com/ysmood/gson v0.7.3/go.mod h1:3Kzs5zDl21g5F/BlLTNcuAGAYLKt2lV5G8D1zF3RNmg= +github.com/ysmood/leakless v0.8.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ= +github.com/ysmood/leakless v0.9.0 h1:qxCG5VirSBvmi3uynXFkcnLMzkphdh3xx5FtrORwDCU= +github.com/ysmood/leakless v0.9.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= diff --git a/internal/chrome/chrome.go b/internal/chrome/chrome.go new file mode 100644 index 0000000..98f617b --- /dev/null +++ b/internal/chrome/chrome.go @@ -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 +} diff --git a/internal/chrome/chrome_test.go b/internal/chrome/chrome_test.go new file mode 100644 index 0000000..2dee1e6 --- /dev/null +++ b/internal/chrome/chrome_test.go @@ -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, `Just a moment...Checking your browser`) + return + } + + session := "" + if ck, err := r.Cookie("session"); err == nil { session = ck.Value } + + _, _ = fmt.Fprintf(w, "

%s

%s

%s

", + 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) } +} diff --git a/internal/chrome/pipeline.go b/internal/chrome/pipeline.go new file mode 100644 index 0000000..8dbcad1 --- /dev/null +++ b/internal/chrome/pipeline.go @@ -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 +} diff --git a/internal/fetch/browser.go b/internal/fetch/browser.go index dcbc895..977d7c5 100644 --- a/internal/fetch/browser.go +++ b/internal/fetch/browser.go @@ -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 diff --git a/internal/fetch/classify.go b/internal/fetch/classify.go index 28bbd82..ec491dd 100644 --- a/internal/fetch/classify.go +++ b/internal/fetch/classify.go @@ -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" } diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go index 171b976..39c2ea3 100644 --- a/internal/fetch/fetch_test.go +++ b/internal/fetch/fetch_test.go @@ -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{} diff --git a/internal/fetch/jar.go b/internal/fetch/jar.go index c7f5b0f..7aa6d8f 100644 --- a/internal/fetch/jar.go +++ b/internal/fetch/jar.go @@ -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 "/" } diff --git a/internal/notify/notify.go b/internal/notify/notify.go index b566946..6af8f1e 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -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 diff --git a/internal/ratelimit/ratelimit.go b/internal/ratelimit/ratelimit.go index 5fc0c80..850891b 100644 --- a/internal/ratelimit/ratelimit.go +++ b/internal/ratelimit/ratelimit.go @@ -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() } diff --git a/internal/tui/model.go b/internal/tui/model.go index 2793d79..a4a9a93 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -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 diff --git a/internal/tui/view.go b/internal/tui/view.go index a0f291a..ba7ea1c 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -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. diff --git a/internal/watch/watch.go b/internal/watch/watch.go index 948c027..07503c5 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -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()