Add session mode: signing in and adding to the cart.
With cart_mode = "session", dibs signs in to the shop's account and puts an item in the cart when it fires. The account's cookies are kept apart from the watcher's and stored encrypted, with the key in the OS keyring. Without a keyring, they're stored in a file only you can read. An alert now goes out right away, without a cart link, and a second one follows once the item is in the cart. If adding fails, the second alert carries the cart link instead. Amazon only accepts additions its page scripts have seen, so plugins can now press a button in headless Chrome with ctx:click. The TUI asks for one-time codes and shows the plugin's warning about account locks in a modal. 'dibs login' signs in from a terminal, or with --browser in a Chrome window, and 'dibs logout' deletes the cookies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e2cbc1a55c
commit
15a34e1f84
39 files changed
+3529
-163
No files matched your search
+202
-49
@@ -47,15 +47,17 @@ type Chrome struct {
|
||||
browser fetch.Browser
|
||||
jar *fetch.Jar
|
||||
logger *slog.Logger
|
||||
// challengeTimeout is ChallengeTimeout, shorter in tests.
|
||||
// challengeTimeout and humanTimeout are ChallengeTimeout and
|
||||
// HumanTimeout, shorter in tests.
|
||||
challengeTimeout time.Duration
|
||||
humanTimeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
bin string
|
||||
}
|
||||
|
||||
func New(browser fetch.Browser, jar *fetch.Jar, logger *slog.Logger) *Chrome {
|
||||
return &Chrome{browser: browser, jar: jar, logger: logger, challengeTimeout: ChallengeTimeout}
|
||||
return &Chrome{browser: browser, jar: jar, logger: logger, challengeTimeout: ChallengeTimeout, humanTimeout: HumanTimeout}
|
||||
}
|
||||
|
||||
// Fetch loads rawURL in headless Chrome and gives a bot check up to
|
||||
@@ -70,8 +72,8 @@ func (c *Chrome) Fetch(ctx context.Context, rawURL string) (*fetch.Response, err
|
||||
// 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) }
|
||||
resp, err := c.visit(ctx, rawURL, false, c.humanTimeout)
|
||||
if err == nil && resp.Verdict == fetch.Challenge { return resp, fmt.Errorf("the bot check did not clear within %s", c.humanTimeout) }
|
||||
|
||||
return resp, err
|
||||
}
|
||||
@@ -87,35 +89,13 @@ func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeou
|
||||
|
||||
host := strings.ToLower(u.Hostname())
|
||||
|
||||
bin, err := c.binary()
|
||||
b, cleanup, err := c.launch(ctx, headless)
|
||||
if err != nil { return nil, err }
|
||||
defer cleanup()
|
||||
|
||||
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)
|
||||
page, err := c.open(b, u, host)
|
||||
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) }
|
||||
@@ -153,6 +133,170 @@ func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeou
|
||||
}
|
||||
}
|
||||
|
||||
// ClickTimeout is how long Click waits for the page a click leads to.
|
||||
const ClickTimeout = 30 * time.Second
|
||||
|
||||
// Click loads rawURL in headless Chrome, clicks the element sel matches and
|
||||
// returns the page the click leads to. Page scripts run as for a user, so
|
||||
// shops that only accept forms their scripts have seen work. wait is called
|
||||
// between loading and clicking, for the rate limits. Chrome's cookies go
|
||||
// into the jar.
|
||||
func (c *Chrome) Click(ctx context.Context, rawURL, sel string, wait func() error) (*fetch.Response, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
host := strings.ToLower(u.Hostname())
|
||||
|
||||
b, cleanup, err := c.launch(ctx, true)
|
||||
if err != nil { return nil, err }
|
||||
defer cleanup()
|
||||
|
||||
page, err := c.open(b, u, host)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
doc := &document{}
|
||||
go page.EachEvent(func(e *proto.NetworkResponseReceived) {
|
||||
if e.Type == proto.NetworkResourceTypeDocument && e.FrameID == page.FrameID { doc.set(e.Response) }
|
||||
})()
|
||||
|
||||
if err := page.Navigate(rawURL); err != nil { return nil, err }
|
||||
if err := page.Timeout(ClickTimeout).WaitLoad(); err != nil { return nil, fmt.Errorf("loading %s: %w", rawURL, err) }
|
||||
|
||||
el, err := page.Timeout(ClickTimeout).Element(sel)
|
||||
if err != nil { return nil, fmt.Errorf("no %s on %s: %w", sel, rawURL, err) }
|
||||
|
||||
if err := wait(); err != nil { return nil, err }
|
||||
|
||||
navigated := page.Timeout(ClickTimeout).WaitNavigation(proto.PageLifecycleEventNameLoad)
|
||||
|
||||
// A script click works even when a banner, such as a cookie notice,
|
||||
// covers the element.
|
||||
if _, err := el.Eval("() => this.click()"); err != nil { return nil, fmt.Errorf("clicking %s: %w", sel, err) }
|
||||
|
||||
navigated()
|
||||
|
||||
if ctx.Err() != nil { return nil, ctx.Err() }
|
||||
|
||||
resp, err := snapshot(page, rawURL, doc)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
c.keepCookies(page, resp.FinalURL, host)
|
||||
resp.Elapsed = time.Since(start)
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// SignIn opens rawURL in a visible window for the user to sign in to a shop.
|
||||
// When the window is closed, or after HumanTimeout, the cookies Chrome has
|
||||
// for rawURL's host go into the jar. It returns how many there were.
|
||||
func (c *Chrome) SignIn(ctx context.Context, rawURL string) (int, error) {
|
||||
return c.signIn(ctx, rawURL, false)
|
||||
}
|
||||
|
||||
func (c *Chrome) signIn(ctx context.Context, rawURL string, headless bool) (int, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil { return 0, err }
|
||||
|
||||
host := strings.ToLower(u.Hostname())
|
||||
|
||||
b, cleanup, err := c.launch(ctx, headless)
|
||||
if err != nil { return 0, err }
|
||||
defer cleanup()
|
||||
|
||||
page, err := c.open(b, u, host)
|
||||
if err != nil { return 0, err }
|
||||
|
||||
if err := page.Navigate(rawURL); err != nil { return 0, err }
|
||||
|
||||
deadline := time.After(c.humanTimeout)
|
||||
|
||||
// Once the window is closed, Chrome's cookies are out of reach, so the
|
||||
// latest copy is kept while it is open.
|
||||
var last []*proto.NetworkCookie
|
||||
|
||||
watch:
|
||||
for {
|
||||
cookies, err := b.GetCookies()
|
||||
if err != nil || !alive(b) { break }
|
||||
|
||||
last = cookies
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0, ctx.Err()
|
||||
case <-deadline:
|
||||
break watch
|
||||
case <-time.After(poll):
|
||||
}
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
kept := make([]fetch.Cookie, 0, len(last))
|
||||
|
||||
for _, ck := range last {
|
||||
if domainMatch(host, strings.TrimPrefix(ck.Domain, ".")) { kept = append(kept, fromChrome(ck, now)) }
|
||||
}
|
||||
|
||||
c.jar.Import(host, kept)
|
||||
|
||||
return len(kept), nil
|
||||
}
|
||||
|
||||
// launch starts Chrome and connects to it. cleanup stops it and removes its
|
||||
// profile.
|
||||
func (c *Chrome) launch(ctx context.Context, headless bool) (*rod.Browser, func(), error) {
|
||||
bin, err := c.binary()
|
||||
if err != nil { return nil, nil, err }
|
||||
|
||||
l := launcher.New().Context(ctx).Bin(bin).Leakless(false)
|
||||
if headless {
|
||||
// Images are not needed to clear a bot check, and fewer requests
|
||||
// reach the shop.
|
||||
l = l.HeadlessNew(true).Set("blink-settings", "imagesEnabled=false")
|
||||
} else {
|
||||
l = l.Headless(false)
|
||||
}
|
||||
|
||||
controlURL, err := l.Launch()
|
||||
if err != nil { return nil, nil, fmt.Errorf("starting %s: %w", bin, err) }
|
||||
|
||||
cleanup := func() {
|
||||
l.Kill()
|
||||
l.Cleanup()
|
||||
}
|
||||
|
||||
b := rod.New().ControlURL(controlURL).Context(ctx)
|
||||
if err := b.Connect(); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("connecting to Chrome: %w", err)
|
||||
}
|
||||
|
||||
return b, cleanup, nil
|
||||
}
|
||||
|
||||
// open creates a page that claims tls-client's identity and has the jar's
|
||||
// cookies for host.
|
||||
func (c *Chrome) open(b *rod.Browser, u *url.URL, host string) (*rod.Page, error) {
|
||||
page, err := stealth.Page(b)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
if err := c.identity(host).Call(page); err != nil { return nil, err }
|
||||
|
||||
if cookies := c.jar.Export()[host]; len(cookies) > 0 {
|
||||
if err := b.SetCookies(cookieParams(cookies, u.Scheme)); err != nil { return nil, err }
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// binary finds Chrome, Chromium or Edge, and otherwise downloads the
|
||||
// Chromium build rod is tested with.
|
||||
func (c *Chrome) binary() (string, error) {
|
||||
@@ -218,26 +362,34 @@ func (c *Chrome) keepCookies(page *rod.Page, rawURL, host string) {
|
||||
|
||||
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)
|
||||
}
|
||||
for _, ck := range cookies { out = append(out, fromChrome(ck, now)) }
|
||||
|
||||
c.jar.Import(host, out)
|
||||
}
|
||||
|
||||
func fromChrome(ck *proto.NetworkCookie, now time.Time) fetch.Cookie {
|
||||
c := fetch.Cookie{
|
||||
Name: ck.Name,
|
||||
Value: ck.Value,
|
||||
Domain: strings.TrimPrefix(ck.Domain, "."),
|
||||
HostOnly: !strings.HasPrefix(ck.Domain, "."),
|
||||
Path: ck.Path,
|
||||
Secure: ck.Secure,
|
||||
HTTPOnly: ck.HTTPOnly,
|
||||
Set: now,
|
||||
}
|
||||
if !ck.Session { c.Expires = ck.Expires.Time() }
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// domainMatch reports whether a cookie for domain is sent to host.
|
||||
func domainMatch(host, domain string) bool {
|
||||
host, domain = strings.ToLower(host), strings.ToLower(domain)
|
||||
|
||||
return host == domain || strings.HasSuffix(host, "."+domain)
|
||||
}
|
||||
|
||||
func cookieParams(cookies []fetch.Cookie, scheme string) []*proto.NetworkCookieParam {
|
||||
out := make([]*proto.NetworkCookieParam, 0, len(cookies))
|
||||
|
||||
@@ -292,9 +444,10 @@ func snapshot(page *rod.Page, rawURL string, doc *document) (*fetch.Response, er
|
||||
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.
|
||||
// alive reports whether Chrome still has a window open. On Linux and
|
||||
// Windows, Chrome exits with its last window; on macOS, it keeps running
|
||||
// without one.
|
||||
func alive(b *rod.Browser) bool {
|
||||
_, err := b.Pages()
|
||||
return err == nil
|
||||
pages, err := b.Pages()
|
||||
return err == nil && len(pages) > 0
|
||||
}
|
||||
@@ -92,6 +92,7 @@ func TestFetchGivesUp(t *testing.T) {
|
||||
type noLimit struct{}
|
||||
|
||||
func (noLimit) WaitCheck(context.Context, string) error { return nil }
|
||||
func (noLimit) Wait(context.Context, string) error { return nil }
|
||||
|
||||
func TestPipelineEscalates(t *testing.T) {
|
||||
c, jar := newChrome(t)
|
||||
@@ -114,3 +115,59 @@ func TestPipelineEscalates(t *testing.T) {
|
||||
if err != nil { t.Fatal(err) }
|
||||
if resp.Verdict != fetch.OK { t.Errorf("tls-client after Chrome: verdict %s", resp.Verdict) }
|
||||
}
|
||||
|
||||
// TestSignIn has the page sign in the way a user would, by script here, and
|
||||
// checks that the cookies reach the jar when the window's time is up.
|
||||
func TestSignIn(t *testing.T) {
|
||||
c, jar := newChrome(t)
|
||||
c.humanTimeout = 3 * time.Second
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := r.Cookie("guest"); err != nil { t.Error("the jar's cookie did not reach Chrome") }
|
||||
|
||||
http.SetCookie(w, &http.Cookie{Name: "account", Value: "signed-in", Path: "/", HttpOnly: true, Expires: time.Now().Add(time.Hour)})
|
||||
_, _ = io.WriteString(w, `<html><body><script>document.cookie = "later=1; path=/"</script>Signed in</body></html>`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
u, _ := url.Parse(srv.URL + "/")
|
||||
jar.SetCookies(u, []*fhttp.Cookie{{Name: "guest", Value: "1", Path: "/"}})
|
||||
|
||||
n, err := c.signIn(context.Background(), u.String(), true)
|
||||
if err != nil { t.Fatal(err) }
|
||||
if n != 3 { t.Errorf("kept %d cookies, want 3", n) }
|
||||
|
||||
got := map[string]string{}
|
||||
for _, ck := range jar.Cookies(u) { got[ck.Name] = ck.Value }
|
||||
if got["account"] != "signed-in" || got["later"] != "1" { t.Errorf("jar after signing in: %v", got) }
|
||||
}
|
||||
|
||||
func TestClick(t *testing.T) {
|
||||
c, _ := newChrome(t)
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/item":
|
||||
_, _ = io.WriteString(w, `<html><body><form method="post" action="/wrong"><input type="hidden" name="id" value="X">
|
||||
<input type="submit" id="add" name="submit.add" value="Add" formaction="/cart"></form></body></html>`)
|
||||
case "/cart":
|
||||
_ = r.ParseForm()
|
||||
_, _ = fmt.Fprintf(w, "<html><body><p id=added>%s %s</p></body></html>", r.PostForm.Get("id"), r.PostForm.Get("submit.add"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
waited := 0
|
||||
wait := func() error {
|
||||
waited++
|
||||
return nil
|
||||
}
|
||||
|
||||
resp, err := c.Click(context.Background(), srv.URL+"/item", "#add", wait)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
if !strings.Contains(string(resp.Body), "X Add") || resp.FinalURL != srv.URL+"/cart" { t.Errorf("after the click: %s %s", resp.FinalURL, resp.Body) }
|
||||
if waited != 1 { t.Errorf("waited %d times before clicking, want 1", waited) }
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package chrome
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
// Limiter is ratelimit.Limiter.
|
||||
type Limiter interface {
|
||||
WaitCheck(ctx context.Context, url string) error
|
||||
Wait(ctx context.Context, host string) error
|
||||
}
|
||||
|
||||
// Pipeline fetches pages the way the shops expect a browser to, escalating
|
||||
@@ -28,10 +30,27 @@ func (p *Pipeline) Get(ctx context.Context, rawURL string) (*fetch.Response, err
|
||||
resp, err := p.Client.Get(ctx, rawURL)
|
||||
if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil { return resp, err }
|
||||
|
||||
// Chrome's visit is a check of the URL like any other.
|
||||
return p.escalate(ctx, rawURL, resp, func() error { return p.Limiter.WaitCheck(ctx, rawURL) })
|
||||
}
|
||||
|
||||
// Do sends a session request. A GET that runs into a bot check is retried
|
||||
// in headless Chrome like a check, but waits only for the host floor.
|
||||
func (p *Pipeline) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||
resp, err := p.Client.Do(ctx, r)
|
||||
if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil || r.Method != "GET" { return resp, err }
|
||||
|
||||
u, err := url.Parse(r.URL)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
return p.escalate(ctx, r.URL, resp, func() error { return p.Limiter.Wait(ctx, u.Hostname()) })
|
||||
}
|
||||
|
||||
// escalate retries a bot check in headless Chrome once wait allows it.
|
||||
func (p *Pipeline) escalate(ctx context.Context, rawURL string, resp *fetch.Response, wait func() error) (*fetch.Response, error) {
|
||||
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 }
|
||||
if err := wait(); err != nil { return nil, err }
|
||||
|
||||
cr, err := p.Chrome.Fetch(ctx, rawURL)
|
||||
|
||||
|
||||
Reference in new issue
Block a user