Files
OverlordandClaude Bot 15a34e1f84 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>
2026-10-14 17:26:26 +02:00

397 lines
15 KiB
Go

package fetch
import (
"compress/gzip"
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
fhttp "github.com/bogdanfinn/fhttp"
)
func TestSecCHUA(t *testing.T) {
// Real values, from tls-client's examples.
for major, want := range map[int]string{
105: `"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"`,
107: `"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"`,
} {
if got := secCHUA(major); got != want { t.Errorf("secCHUA(%d) = %s, want %s", major, got, want) }
}
}
func TestAcceptLanguage(t *testing.T) {
for host, want := range map[string]string{
"www.amazon.de": "de-DE,",
"www.Amazon.co.uk": "en-GB,",
"www.amazon.fr": "fr-FR,",
"www.amazon.it": "it-IT,",
"www.amazon.es": "es-ES,",
"www.amazon.nl": "nl-NL,",
"www.amazon.com": "en-US,",
"www.amazon.co.jp": "en-US,",
"127.0.0.1": "en-US,",
} {
if got := acceptLanguage(host); !strings.HasPrefix(got, want) { t.Errorf("acceptLanguage(%q) = %q, want prefix %q", host, got, want) }
}
}
func TestDefaultBrowserMatchesProfile(t *testing.T) {
b := DefaultBrowser()
if !strings.Contains(b.UserAgent, "Chrome/152.0.0.0") { t.Errorf("user agent %q does not match Chrome %d", b.UserAgent, b.Major) }
want := map[string]string{"windows": "Windows", "darwin": "macOS", "linux": "Linux"}[runtime.GOOS]
if want != "" && b.Platform != want { t.Errorf("platform = %q, want %q", b.Platform, want) }
}
func TestClassify(t *testing.T) {
cf := http.Header{"Cf-Mitigated": {"challenge"}}
for name, tc := range map[string]struct {
status int
header http.Header
finalURL string
body string
verdict Verdict
challenge string
}{
"product page": {200, nil, "https://www.amazon.de/dp/X", "<title>Metro</title>", OK, ""},
"cf script on normal page": {200, nil, "", `<script src="/cdn-cgi/challenge-platform/scripts/jsd/main.js">`, OK, ""},
"turnstile in a form": {200, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, OK, ""},
"not found": {404, nil, "", "<title>Page not found</title>", NotFound, ""},
"gone": {410, nil, "", "", NotFound, ""},
"cf header": {403, cf, "", "", Challenge, "cloudflare"},
"cf js challenge": {503, nil, "", "<script>window._cf_chl_opt={}</script>", Challenge, "cloudflare"},
"cf title": {403, nil, "", "<title>Just a moment...</title>", Challenge, "cloudflare"},
"amazon captcha 200": {200, nil, "", `<form method="get" action="/errors/validateCaptcha">`, Challenge, "amazon-captcha"},
"amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"},
"datadome": {403, nil, "", `<iframe src="https://geo.captcha-delivery.com/captcha/">`, Challenge, "datadome"},
"turnstile on 403": {403, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, Challenge, "turnstile"},
"plain 403": {403, nil, "", "Access Denied", Blocked, ""},
"429": {429, nil, "", "slow down", Blocked, ""},
"amazon 503 dog": {503, nil, "", "Sorry! Something went wrong!", Blocked, ""},
"500": {500, nil, "", "", HTTPError, ""},
} {
t.Run(name, func(t *testing.T) {
header := tc.header
if header == nil { header = http.Header{} }
v, c := classify(tc.status, header, tc.finalURL, []byte(tc.body))
if v != tc.verdict || c != tc.challenge { t.Errorf("got %s/%q, want %s/%q", v, c, tc.verdict, tc.challenge) }
})
}
}
func mustURL(t *testing.T, raw string) *url.URL {
t.Helper()
u, err := url.Parse(raw)
if err != nil { t.Fatal(err) }
return u
}
func cookieNames(cs []*fhttp.Cookie) string {
names := make([]string, len(cs))
for i, c := range cs { names[i] = c.Name + "=" + c.Value }
return strings.Join(names, " ")
}
func TestJarExportImport(t *testing.T) {
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
j := NewJar()
j.now = func() time.Time { return now }
j.SetCookies(mustURL(t, "https://www.amazon.de/dp/X"), []*fhttp.Cookie{
{Name: "session-id", Value: "1", Domain: ".amazon.de", Path: "/"},
{Name: "host", Value: "2"},
{Name: "short", Value: "3", MaxAge: 60},
{Name: "old", Value: "4", Expires: now.Add(-time.Hour)},
})
exported := j.Export()
got := exported["www.amazon.de"]
if len(got) != 3 { t.Fatalf("exported %d cookies, want 3: %+v", len(got), got) }
byName := map[string]Cookie{}
for _, c := range got { byName[c.Name] = c }
if c := byName["host"]; !c.HostOnly || c.Domain != "www.amazon.de" || c.Path != "/dp" { t.Errorf("host-only cookie: %+v", c) }
if c := byName["session-id"]; c.HostOnly || c.Domain != "amazon.de" { t.Errorf("domain cookie: %+v", c) }
if c := byName["short"]; !c.Expires.Equal(now.Add(time.Minute)) { t.Errorf("max-age cookie expires %v", c.Expires) }
// A new jar gets the same cookies, scoped the same way.
k := NewJar()
k.now = j.now
for host, cs := range exported { k.Import(host, cs) }
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.de/dp/Y"))); !strings.Contains(got, "host=2") || !strings.Contains(got, "session-id=1") {
t.Errorf("www.amazon.de/dp cookies after import: %s", got)
}
if got := cookieNames(k.Cookies(mustURL(t, "https://smile.amazon.de/"))); got != "session-id=1" { t.Errorf("smile.amazon.de cookies: %q, want only the domain cookie", got) }
// The server deletes a cookie.
j.SetCookies(mustURL(t, "https://www.amazon.de/"), []*fhttp.Cookie{{Name: "session-id", Domain: ".amazon.de", Path: "/", MaxAge: -1}})
for _, c := range j.Export()["www.amazon.de"] {
if c.Name == "session-id" { t.Errorf("deleted cookie still exported") }
}
// Later the max-age cookie runs out.
now = now.Add(2 * time.Minute)
for _, c := range j.Export()["www.amazon.de"] {
if c.Name == "short" { t.Errorf("expired cookie still exported") }
}
}
func TestJarSaveLoad(t *testing.T) {
path := filepath.Join(t.TempDir(), "sub", "cookies.json")
j := NewJar()
j.SetCookies(mustURL(t, "https://www.amazon.co.uk/"), []*fhttp.Cookie{{Name: "a", Value: "1", Path: "/", Expires: time.Now().Add(time.Hour)}})
if err := j.Save(path); err != nil { t.Fatal(err) }
if runtime.GOOS != "windows" {
info, err := os.Stat(path)
if err != nil { t.Fatal(err) }
if perm := info.Mode().Perm(); perm != 0o600 { t.Errorf("cookie file mode %o, want 600", perm) }
}
k := NewJar()
if err := k.Load(path); err != nil { t.Fatal(err) }
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.co.uk/x"))); got != "a=1" { t.Errorf("loaded cookies: %q", got) }
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) }
// Logging out in another process clears the watcher's copy as well.
fresh.now = func() time.Time { return now.Add(3 * time.Minute) }
fresh.Clear()
if got := cookieNames(fresh.Cookies(u)); got != "" { t.Errorf("after Clear: %q", got) }
if err := fresh.Save(path); err != nil { t.Fatal(err) }
watcher.now = func() time.Time { return now.Add(4 * time.Minute) }
if err := watcher.Save(path); err != nil { t.Fatal(err) }
if got := cookieNames(watcher.Cookies(u)); got != "" { t.Errorf("watcher after another process cleared the jar: %q", got) }
}
// noLimit lets tests talk to their local server without the host floor.
type noLimit struct{}
func (noLimit) WaitCheck(context.Context, string) error { return nil }
func (noLimit) Wait(context.Context, string) error { return nil }
func newTestClient(t *testing.T, opts Options) *Client {
t.Helper()
if opts.Limiter == nil { opts.Limiter = noLimit{} }
c, err := New(opts)
if err != nil { t.Fatal(err) }
return c
}
func TestClientGet(t *testing.T) {
var seen []*http.Request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, r)
switch r.URL.Path {
case "/start":
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "abc", Path: "/"})
http.Redirect(w, r, "/product", http.StatusFound)
case "/product":
w.Header().Set("Content-Encoding", "gzip")
zw := gzip.NewWriter(w)
_, _ = zw.Write([]byte("<title>Metro 2039</title>"))
_ = zw.Close()
case "/missing":
http.NotFound(w, r)
default:
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer srv.Close()
c := newTestClient(t, Options{})
resp, err := c.Get(context.Background(), srv.URL+"/start")
if err != nil { t.Fatal(err) }
if resp.Verdict != OK || resp.Status != 200 { t.Errorf("verdict %s, status %d", resp.Verdict, resp.Status) }
if resp.FinalURL != srv.URL+"/product" { t.Errorf("final URL %q", resp.FinalURL) }
if string(resp.Body) != "<title>Metro 2039</title>" { t.Errorf("body %q, want it decompressed", resp.Body) }
if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) }
first := seen[0]
for name, want := range map[string]string{
"User-Agent": "Chrome/152.0.0.0",
"Sec-Ch-Ua": `"Google Chrome";v="152"`,
"Sec-Ch-Ua-Platform": `"`,
"Sec-Fetch-Mode": "navigate",
"Accept-Language": "en-US",
"Accept-Encoding": "gzip",
} {
if got := first.Header.Get(name); !strings.Contains(got, want) { t.Errorf("%s = %q, want it to contain %q", name, got, want) }
}
if got := seen[1].Header.Get("Cookie"); got != "sid=abc" { t.Errorf("cookie on redirect = %q, want sid=abc", got) }
resp, err = c.Get(context.Background(), srv.URL+"/missing")
if err != nil { t.Fatal(err) }
if resp.Verdict != NotFound { t.Errorf("404 verdict %s", resp.Verdict) }
if got := c.Jar().Export()["127.0.0.1"]; len(got) != 1 || got[0].Name != "sid" { t.Errorf("jar after requests: %+v", got) }
}
// countingLimiter records which kind of wait each request made.
type countingLimiter struct{ checks, waits []string }
func (l *countingLimiter) WaitCheck(_ context.Context, u string) error {
l.checks = append(l.checks, u)
return nil
}
func (l *countingLimiter) Wait(_ context.Context, host string) error {
l.waits = append(l.waits, host)
return nil
}
func TestClientDo(t *testing.T) {
var seen []*http.Request
var forms []url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
seen = append(seen, r)
forms = append(forms, r.PostForm)
if r.URL.Path == "/signin" { http.Redirect(w, r, "/home", http.StatusFound) }
}))
defer srv.Close()
limiter := &countingLimiter{}
c := newTestClient(t, Options{Limiter: limiter})
resp, err := c.Do(context.Background(), Request{
Method: "POST",
URL: srv.URL + "/signin",
Form: url.Values{"email": {"me@example.com"}, "password": {"p&ss word"}},
Referer: srv.URL + "/ap/signin?x=1",
})
if err != nil { t.Fatal(err) }
if resp.FinalURL != srv.URL+"/home" { t.Errorf("final URL %q, want the redirect followed", resp.FinalURL) }
if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) }
post := seen[0]
if post.Method != "POST" || forms[0].Get("password") != "p&ss word" { t.Errorf("first request %s with form %v", post.Method, forms[0]) }
for name, want := range map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Origin": srv.URL,
"Referer": srv.URL + "/ap/signin?x=1",
"Sec-Fetch-Site": "same-origin",
"Cache-Control": "max-age=0",
} {
if got := post.Header.Get(name); got != want { t.Errorf("%s = %q, want %q", name, got, want) }
}
if len(limiter.checks) != 0 || len(limiter.waits) != 1 { t.Errorf("limiter saw checks %v and waits %v, want one host wait", limiter.checks, limiter.waits) }
// A link from another site sends only that site's origin.
if _, err := c.Do(context.Background(), Request{Method: "GET", URL: srv.URL + "/cart", Referer: "https://www.example.com/a/b"}); err != nil { t.Fatal(err) }
get := seen[len(seen)-1]
if got := get.Header.Get("Referer"); got != "https://www.example.com/" { t.Errorf("cross-site referer %q", got) }
if got := get.Header.Get("Sec-Fetch-Site"); got != "cross-site" { t.Errorf("cross-site Sec-Fetch-Site %q", got) }
if got := get.Header.Get("Origin"); got != "" { t.Errorf("GET sent Origin %q", got) }
for _, bad := range []Request{
{Method: "GET", URL: srv.URL, Form: url.Values{"a": {"b"}}},
{Method: "POST", URL: srv.URL, Body: []byte("{}")},
{Method: "DELETE", URL: srv.URL},
} {
if _, err := c.Do(context.Background(), bad); err == nil { t.Errorf("%s with form %v and body %q: want an error", bad.Method, bad.Form, bad.Body) }
}
}
func TestClientBodyLimit(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strings.Repeat("x", 2048)))
}))
defer srv.Close()
_, err := newTestClient(t, Options{MaxBody: 1024}).Get(context.Background(), srv.URL)
if !errors.Is(err, ErrBodyTooLarge) { t.Errorf("got %v, want ErrBodyTooLarge", err) }
}
func TestClientContextCancel(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
}))
defer srv.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
start := time.Now()
if _, err := newTestClient(t, Options{}).Get(ctx, srv.URL); err == nil { t.Fatal("want an error from a cancelled request") }
if elapsed := time.Since(start); elapsed > 5*time.Second { t.Errorf("cancel took %s", elapsed) }
}
func TestClientRejectsOtherSchemes(t *testing.T) {
if _, err := newTestClient(t, Options{}).Get(context.Background(), "file:///etc/passwd"); err == nil { t.Error("want an error for file://") }
}