Files
dibs/internal/fetch/client.go
T
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

232 lines
7.2 KiB
Go

// Package fetch downloads product pages with a browser-like TLS and HTTP/2
// fingerprint and tells real pages apart from bot checks.
package fetch
import (
"bytes"
"context"
"errors"
"fmt"
"io"
stdhttp "net/http"
"net/url"
"strings"
"time"
http "github.com/bogdanfinn/fhttp"
tlsclient "github.com/bogdanfinn/tls-client"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
)
const (
DefaultTimeout = 30 * time.Second
DefaultMaxBody = 16 << 20
)
// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody.
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 {
// Limiter defaults to a new in-memory ratelimit.Limiter, so requests are
// never unlimited.
Limiter Limiter
// Browser defaults to DefaultBrowser().
Browser *Browser
// Jar defaults to a new, empty jar.
Jar *Jar
// Timeout covers a request and its redirects. It defaults to
// DefaultTimeout.
Timeout time.Duration
// MaxBody limits the body after decompression. It defaults to
// DefaultMaxBody.
MaxBody int64
}
// Client fetches pages. It is safe for concurrent use.
type Client struct {
http tlsclient.HttpClient
limiter Limiter
browser Browser
jar *Jar
maxBody int64
}
type Response struct {
URL string // as requested
FinalURL string // after redirects
Status int
Header stdhttp.Header
Body []byte
Verdict Verdict
// Challenge names the bot check found, such as "cloudflare", when
// Verdict is Challenge.
Challenge string
Elapsed time.Duration
}
func New(opts Options) (*Client, error) {
browser := DefaultBrowser()
if opts.Browser != nil { browser = *opts.Browser }
if opts.Limiter == nil { opts.Limiter = ratelimit.New(nil) }
if opts.Jar == nil { opts.Jar = NewJar() }
if opts.Timeout == 0 { opts.Timeout = DefaultTimeout }
if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody }
hc, err := tlsclient.NewHttpClient(nil,
tlsclient.WithClientProfile(browser.Profile),
tlsclient.WithRandomTLSExtensionOrder(),
tlsclient.WithCookieJar(opts.Jar),
tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)),
)
if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) }
return &Client{http: hc, limiter: opts.Limiter, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil
}
func (c *Client) Jar() *Jar { return c.jar }
// Get fetches rawURL the way Chrome opens a bookmark, once the limiter allows
// 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 := parseURL(rawURL)
if err != nil { return nil, err }
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, 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 }
// fhttp's decompressing readers close the raw body with them.
body := resp.Body
if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) }
defer func() { _ = body.Close() }()
data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1))
if err != nil { return nil, fmt.Errorf("reading body: %w", err) }
if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) }
r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data)
r.Elapsed = time.Since(start)
return r, nil
}
// NewResponse builds and classifies a Response for a page obtained another
// way, such as a saved fixture or the browser fallback.
func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response {
if header == nil { header = stdhttp.Header{} }
r := &Response{
URL: rawURL,
FinalURL: finalURL,
Status: status,
Header: header,
Body: body,
}
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
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
}
}