Add the Chrome fallback and the needs-human flow.
Bot checks escalate to headless Chrome with stealth, which claims the same identity as tls-client and hands its cookies back to the jar. The visit counts against the rate limits. If Chrome can't clear a check, the URL is marked needs-human. Pressing Enter on it in the TUI, or running 'dibs solve', opens a visible window; dibs carries on once the page loads. Processes now merge the cookie file on save, with the newest cookie winning.
This commit is contained in:
1 parent
f2ea1297e8
commit
e2cbc1a55c
20 files changed
+905
-73
No files matched your search
+6
-2
@@ -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)
|
||||
|
||||
+36
-11
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+4
-1
@@ -20,7 +20,8 @@ var version = "dev"
|
||||
|
||||
const usage = `Usage:
|
||||
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
|
||||
dibs check [--shop NAME] <url> fetch and parse one URL, print JSON
|
||||
dibs check [--shop NAME] [--chrome] <url> fetch and parse one URL, print JSON
|
||||
dibs solve [--shop NAME] <url> pass a bot check in a Chrome window
|
||||
dibs plugin test [--status CODE] <file.lua> <fixture.html> [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
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
)
|
||||
|
||||
// runSolve implements `dibs solve [--shop NAME] <url>`: 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
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user