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
@@ -48,17 +48,18 @@ func DefaultBrowser() Browser {
|
||||
}
|
||||
}
|
||||
|
||||
// navigationHeaders are the headers Chrome sends when the user opens u by
|
||||
// typing it or from a bookmark, in Chrome's order.
|
||||
func (b Browser) navigationHeaders(u *url.URL) http.Header {
|
||||
return http.Header{
|
||||
// navigationHeaders are the headers Chrome sends when the user opens u, in
|
||||
// Chrome's order. Without a referer, u was typed in or opened from a
|
||||
// bookmark. A content type makes it the submission of a form on referer.
|
||||
func (b Browser) navigationHeaders(u, referer *url.URL, contentType string) http.Header {
|
||||
h := http.Header{
|
||||
"sec-ch-ua": {secCHUA(b.Major)},
|
||||
"sec-ch-ua-mobile": {"?0"},
|
||||
"sec-ch-ua-platform": {`"` + b.Platform + `"`},
|
||||
"upgrade-insecure-requests": {"1"},
|
||||
"user-agent": {b.UserAgent},
|
||||
"accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},
|
||||
"sec-fetch-site": {"none"},
|
||||
"sec-fetch-site": {fetchSite(u, referer)},
|
||||
"sec-fetch-mode": {"navigate"},
|
||||
"sec-fetch-user": {"?1"},
|
||||
"sec-fetch-dest": {"document"},
|
||||
@@ -66,9 +67,13 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header {
|
||||
"accept-language": {acceptLanguage(u.Hostname())},
|
||||
"priority": {"u=0, i"},
|
||||
http.HeaderOrderKey: {
|
||||
"content-length",
|
||||
"cache-control",
|
||||
"sec-ch-ua",
|
||||
"sec-ch-ua-mobile",
|
||||
"sec-ch-ua-platform",
|
||||
"origin",
|
||||
"content-type",
|
||||
"upgrade-insecure-requests",
|
||||
"user-agent",
|
||||
"accept",
|
||||
@@ -76,12 +81,56 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header {
|
||||
"sec-fetch-mode",
|
||||
"sec-fetch-user",
|
||||
"sec-fetch-dest",
|
||||
"referer",
|
||||
"accept-encoding",
|
||||
"accept-language",
|
||||
"cookie",
|
||||
"priority",
|
||||
},
|
||||
}
|
||||
|
||||
if referer != nil {
|
||||
// Chrome's default referrer policy leaves out the path on requests
|
||||
// to other origins.
|
||||
ref := referer.Scheme + "://" + referer.Host + "/"
|
||||
if sameOrigin(u, referer) { ref = (&url.URL{Scheme: referer.Scheme, Host: referer.Host, Path: referer.Path, RawPath: referer.RawPath, RawQuery: referer.RawQuery}).String() }
|
||||
|
||||
h.Set("referer", ref)
|
||||
}
|
||||
|
||||
if contentType != "" {
|
||||
h.Set("cache-control", "max-age=0")
|
||||
h.Set("content-type", contentType)
|
||||
if referer != nil { h.Set("origin", referer.Scheme+"://"+referer.Host) } else { h.Set("origin", "null") }
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// fetchSite is the Sec-Fetch-Site of a navigation to u from referer.
|
||||
func fetchSite(u, referer *url.URL) string {
|
||||
switch {
|
||||
case referer == nil:
|
||||
return "none"
|
||||
case sameOrigin(u, referer):
|
||||
return "same-origin"
|
||||
case u.Scheme == referer.Scheme && site(u.Hostname()) == site(referer.Hostname()):
|
||||
return "same-site"
|
||||
default:
|
||||
return "cross-site"
|
||||
}
|
||||
}
|
||||
|
||||
func sameOrigin(a, b *url.URL) bool {
|
||||
return a.Scheme == b.Scheme && strings.EqualFold(a.Host, b.Host)
|
||||
}
|
||||
|
||||
// site is the registrable domain of host, such as amazon.co.uk.
|
||||
func site(host string) string {
|
||||
s, err := publicsuffix.EffectiveTLDPlusOne(strings.ToLower(host))
|
||||
if err != nil { return strings.ToLower(host) }
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Brand is one entry of Chrome's brand list, which sec-ch-ua and
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
stdhttp "net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
http "github.com/bogdanfinn/fhttp"
|
||||
@@ -27,7 +29,10 @@ var ErrBodyTooLarge = errors.New("response body too large")
|
||||
|
||||
// Limiter decides when a page may be fetched. Every request waits for it.
|
||||
type Limiter interface {
|
||||
// WaitCheck is for checks of a page, which Get makes.
|
||||
WaitCheck(ctx context.Context, url string) error
|
||||
// Wait is for other requests to host, which Do makes.
|
||||
Wait(ctx context.Context, host string) error
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
@@ -93,16 +98,85 @@ func (c *Client) Jar() *Jar { return c.jar }
|
||||
// a check of it. A response with a bad status is not an error; its Verdict
|
||||
// says what it is.
|
||||
func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
u, err := parseURL(rawURL)
|
||||
if err != nil { return nil, err }
|
||||
if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) }
|
||||
|
||||
if err := c.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err }
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||
if err != nil { return nil, err }
|
||||
req.Header = c.browser.navigationHeaders(u)
|
||||
req.Header = c.browser.navigationHeaders(u, nil, "")
|
||||
|
||||
return c.send(req, rawURL)
|
||||
}
|
||||
|
||||
// Request is a request made for the user in session mode, such as
|
||||
// submitting a sign-in form.
|
||||
type Request struct {
|
||||
// Method is GET or POST.
|
||||
Method string
|
||||
URL string
|
||||
// Form is the body of a POST, sent as a submitted HTML form. Body and
|
||||
// ContentType replace it for other bodies.
|
||||
Form url.Values
|
||||
Body []byte
|
||||
ContentType string
|
||||
// Referer is the page the request comes from. Without one, the request
|
||||
// looks typed in.
|
||||
Referer string
|
||||
// Header adds or replaces headers.
|
||||
Header map[string]string
|
||||
}
|
||||
|
||||
// Do sends r the way Chrome follows a link or submits a form, once the
|
||||
// limiter allows a request to the host. Unlike Get, it is not a check of the
|
||||
// page, so the URL floor does not apply.
|
||||
func (c *Client) Do(ctx context.Context, r Request) (*Response, error) {
|
||||
u, err := parseURL(r.URL)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
var ref *url.URL
|
||||
if r.Referer != "" {
|
||||
if ref, err = parseURL(r.Referer); err != nil { return nil, fmt.Errorf("referer: %w", err) }
|
||||
}
|
||||
|
||||
var body io.Reader
|
||||
contentType := r.ContentType
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && (r.Form != nil || r.Body != nil):
|
||||
return nil, errors.New("a GET request has no body")
|
||||
case r.Method == http.MethodGet:
|
||||
case r.Method == http.MethodPost && r.Body == nil:
|
||||
body, contentType = strings.NewReader(r.Form.Encode()), "application/x-www-form-urlencoded"
|
||||
case r.Method == http.MethodPost && contentType == "":
|
||||
return nil, errors.New("a POST body needs a content type")
|
||||
case r.Method == http.MethodPost:
|
||||
body = bytes.NewReader(r.Body)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported method %q", r.Method)
|
||||
}
|
||||
|
||||
if err := c.limiter.Wait(ctx, u.Hostname()); err != nil { return nil, err }
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, r.Method, u.String(), body)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
req.Header = c.browser.navigationHeaders(u, ref, contentType)
|
||||
for k, v := range r.Header { req.Header.Set(strings.ToLower(k), v) }
|
||||
|
||||
return c.send(req, r.URL)
|
||||
}
|
||||
|
||||
func parseURL(rawURL string) (*url.URL, error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil { return nil, err }
|
||||
if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) }
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (c *Client) send(req *http.Request, rawURL string) (*Response, error) {
|
||||
start := time.Now()
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil { return nil, err }
|
||||
@@ -138,3 +212,20 @@ func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, bod
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// RecordOutcome tells the limiter how a request to host went: bot checks,
|
||||
// refusals and failed requests back the host off, anything else clears its
|
||||
// backoff. It returns the backoff, or 0.
|
||||
func RecordOutcome(l *ratelimit.Limiter, host string, resp *Response, err error) time.Duration {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
return 0
|
||||
case err != nil:
|
||||
return l.Failure(host)
|
||||
case resp.Verdict == Challenge || resp.Verdict == NeedsHuman || resp.Verdict == Blocked || resp.Verdict == HTTPError:
|
||||
return l.Failure(host)
|
||||
default:
|
||||
l.Success(host)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -206,12 +206,23 @@ func TestJarShared(t *testing.T) {
|
||||
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()
|
||||
@@ -279,6 +290,78 @@ func TestClientGet(t *testing.T) {
|
||||
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)))
|
||||
|
||||
+50
-3
@@ -154,6 +154,28 @@ func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
// Clear deletes every cookie. The deletions are saved like any other
|
||||
// change, so other processes sharing the file drop the cookies too.
|
||||
func (j *Jar) Clear() {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
now := j.now()
|
||||
|
||||
for host, byKey := range j.cookies {
|
||||
for _, c := range byKey {
|
||||
if c.expired(now) { continue }
|
||||
|
||||
hc := &http.Cookie{Name: c.Name, Path: c.Path, MaxAge: -1}
|
||||
if !c.HostOnly { hc.Domain = c.Domain }
|
||||
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
|
||||
|
||||
c.Expires, c.Set = now, now
|
||||
j.store(host, c, now)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func key(c Cookie) string { return c.Domain + "|" + c.Path + "|" + c.Name }
|
||||
|
||||
// store records c for host. Callers hold mu.
|
||||
@@ -164,14 +186,26 @@ func (j *Jar) store(host string, c Cookie, now time.Time) {
|
||||
j.cookies[host][key(c)] = c
|
||||
}
|
||||
|
||||
// Codec turns the cookie file's JSON into what is stored on disk and back,
|
||||
// such as to encrypt it.
|
||||
type Codec interface {
|
||||
Encode(data []byte) ([]byte, error)
|
||||
Decode(data []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return j.SaveWith(path, nil)
|
||||
}
|
||||
|
||||
// SaveWith is Save through codec, which may be nil.
|
||||
func (j *Jar) SaveWith(path string, codec Codec) error {
|
||||
unlock, err := fsutil.Lock(path + ".lock")
|
||||
if err != nil { return err }
|
||||
defer unlock()
|
||||
|
||||
saved, err := readCookies(path)
|
||||
saved, err := readCookies(path, codec)
|
||||
if err != nil { return err }
|
||||
|
||||
j.mu.Lock()
|
||||
@@ -195,12 +229,21 @@ func (j *Jar) Save(path string) error {
|
||||
data, err := json.MarshalIndent(out, "", " ")
|
||||
if err != nil { return err }
|
||||
|
||||
if codec != nil {
|
||||
if data, err = codec.Encode(data); err != nil { return err }
|
||||
}
|
||||
|
||||
return fsutil.WriteFileAtomic(path, data, 0o600)
|
||||
}
|
||||
|
||||
// Load imports the cookies saved at path. A missing file is not an error.
|
||||
func (j *Jar) Load(path string) error {
|
||||
saved, err := readCookies(path)
|
||||
return j.LoadWith(path, nil)
|
||||
}
|
||||
|
||||
// LoadWith is Load through codec, which may be nil.
|
||||
func (j *Jar) LoadWith(path string, codec Codec) error {
|
||||
saved, err := readCookies(path, codec)
|
||||
if err != nil { return err }
|
||||
|
||||
for host, cookies := range saved { j.Import(host, cookies) }
|
||||
@@ -208,11 +251,15 @@ func (j *Jar) Load(path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func readCookies(path string) (map[string][]Cookie, error) {
|
||||
func readCookies(path string, codec Codec) (map[string][]Cookie, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) { return nil, nil }
|
||||
if err != nil { return nil, err }
|
||||
|
||||
if codec != nil {
|
||||
if data, err = codec.Decode(data); err != nil { return nil, err }
|
||||
}
|
||||
|
||||
var saved map[string][]Cookie
|
||||
if err := json.Unmarshal(data, &saved); err != nil { return nil, err }
|
||||
|
||||
|
||||
Reference in new issue
Block a user