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
+36
-11
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
http "github.com/bogdanfinn/fhttp"
|
||||
@@ -83,24 +84,48 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header {
|
||||
}
|
||||
}
|
||||
|
||||
// secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE
|
||||
// brand and the brand order from its major version (GenerateBrandVersionList
|
||||
// in Chromium's user_agent_utils.cc), so a fixed string would stand out after
|
||||
// an update.
|
||||
func secCHUA(major int) string {
|
||||
// Brand is one entry of Chrome's brand list, which sec-ch-ua and
|
||||
// navigator.userAgentData report.
|
||||
type Brand struct {
|
||||
Name string
|
||||
Version string
|
||||
}
|
||||
|
||||
// Brands is Chrome's brand list. Chrome derives the GREASE brand and the
|
||||
// brand order from its major version (GenerateBrandVersionList in
|
||||
// Chromium's user_agent_utils.cc), so a fixed list would stand out after an
|
||||
// update.
|
||||
func (b Browser) Brands() []Brand {
|
||||
return brands(b.Major)
|
||||
}
|
||||
|
||||
func brands(major int) []Brand {
|
||||
chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"}
|
||||
versions := []string{"8", "99", "24"}
|
||||
orders := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
|
||||
|
||||
grease := fmt.Sprintf(`"Not%sA%sBrand";v="%s"`, chars[major%len(chars)], chars[(major+1)%len(chars)], versions[major%len(versions)])
|
||||
grease := Brand{"Not" + chars[major%len(chars)] + "A" + chars[(major+1)%len(chars)] + "Brand", versions[major%len(versions)]}
|
||||
order := orders[major%len(orders)]
|
||||
|
||||
var brands [3]string
|
||||
brands[order[0]] = grease
|
||||
brands[order[1]] = fmt.Sprintf(`"Chromium";v="%d"`, major)
|
||||
brands[order[2]] = fmt.Sprintf(`"Google Chrome";v="%d"`, major)
|
||||
var out [3]Brand
|
||||
out[order[0]] = grease
|
||||
out[order[1]] = Brand{"Chromium", strconv.Itoa(major)}
|
||||
out[order[2]] = Brand{"Google Chrome", strconv.Itoa(major)}
|
||||
|
||||
return strings.Join(brands[:], ", ")
|
||||
return out[:]
|
||||
}
|
||||
|
||||
func secCHUA(major int) string {
|
||||
var parts []string
|
||||
for _, b := range brands(major) { parts = append(parts, fmt.Sprintf(`"%s";v="%s"`, b.Name, b.Version)) }
|
||||
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// AcceptLanguage is the Accept-Language a local shopper's browser would
|
||||
// send to host.
|
||||
func AcceptLanguage(host string) string {
|
||||
return acceptLanguage(host)
|
||||
}
|
||||
|
||||
// languages maps a public suffix to the Accept-Language a local shopper's
|
||||
|
||||
@@ -21,6 +21,9 @@ const (
|
||||
Blocked
|
||||
// HTTPError is any other non-2xx status.
|
||||
HTTPError
|
||||
// NeedsHuman is a bot check that headless Chrome could not clear either,
|
||||
// such as a captcha. classify never returns it.
|
||||
NeedsHuman
|
||||
)
|
||||
|
||||
func (v Verdict) String() string {
|
||||
@@ -35,6 +38,8 @@ func (v Verdict) String() string {
|
||||
return "blocked"
|
||||
case HTTPError:
|
||||
return "http-error"
|
||||
case NeedsHuman:
|
||||
return "needs-human"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
@@ -172,6 +172,42 @@ func TestJarSaveLoad(t *testing.T) {
|
||||
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) }
|
||||
}
|
||||
|
||||
// noLimit lets tests talk to their local server without the host floor.
|
||||
type noLimit struct{}
|
||||
|
||||
|
||||
+64
-21
@@ -30,17 +30,26 @@ type Cookie struct {
|
||||
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
|
||||
Secure bool `json:"secure,omitempty"`
|
||||
HTTPOnly bool `json:"http_only,omitempty"`
|
||||
// Set is when the cookie was last set. When dibs processes share a
|
||||
// cookie file, the newest version of each cookie wins.
|
||||
Set time.Time `json:"set,omitzero"`
|
||||
}
|
||||
|
||||
func (c Cookie) expired(now time.Time) bool {
|
||||
return !c.Expires.IsZero() && !c.Expires.After(now)
|
||||
}
|
||||
|
||||
// forgetDeleted is how long a deleted cookie is remembered, so that saving
|
||||
// does not bring back the copy another process still has on file.
|
||||
const forgetDeleted = 24 * time.Hour
|
||||
|
||||
// Jar is an RFC 6265 cookie jar that remembers every cookie by the host that
|
||||
// set it, so the cookies can be saved, restored and exported per host.
|
||||
type Jar struct {
|
||||
mu sync.Mutex
|
||||
jar *cookiejar.Jar
|
||||
mu sync.Mutex
|
||||
jar *cookiejar.Jar
|
||||
// cookies keeps deleted and expired cookies too, until forgetDeleted
|
||||
// has passed.
|
||||
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
|
||||
now func() time.Time
|
||||
}
|
||||
@@ -115,16 +124,19 @@ func (j *Jar) Export() map[string][]Cookie {
|
||||
return out
|
||||
}
|
||||
|
||||
// Import adds cookies as if host had set them. Expired cookies are skipped.
|
||||
// Import adds cookies as if host had set them, unless the jar has a newer
|
||||
// version. A cookie without a Set time loses to any version in the jar.
|
||||
func (j *Jar) Import(host string, cookies []Cookie) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
host = strings.ToLower(host)
|
||||
now := j.now()
|
||||
j.importLocked(strings.ToLower(host), cookies, j.now())
|
||||
}
|
||||
|
||||
// importLocked is Import. Callers hold mu.
|
||||
func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) {
|
||||
for _, c := range cookies {
|
||||
if c.expired(now) { continue }
|
||||
if have, ok := j.cookies[host][key(c)]; ok && !c.Set.After(have.Set) { continue }
|
||||
|
||||
hc := &http.Cookie{
|
||||
Name: c.Name,
|
||||
@@ -135,28 +147,52 @@ func (j *Jar) Import(host string, cookies []Cookie) {
|
||||
HttpOnly: c.HTTPOnly,
|
||||
}
|
||||
if !c.HostOnly { hc.Domain = c.Domain }
|
||||
if c.expired(now) { hc.MaxAge = -1 }
|
||||
|
||||
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
|
||||
j.store(host, c, now)
|
||||
}
|
||||
}
|
||||
|
||||
// store records c for host, or forgets it when it has expired. Callers hold mu.
|
||||
func (j *Jar) store(host string, c Cookie, now time.Time) {
|
||||
key := c.Domain + "|" + c.Path + "|" + c.Name
|
||||
func key(c Cookie) string { return c.Domain + "|" + c.Path + "|" + c.Name }
|
||||
|
||||
if c.expired(now) {
|
||||
delete(j.cookies[host], key)
|
||||
return
|
||||
}
|
||||
// store records c for host. Callers hold mu.
|
||||
func (j *Jar) store(host string, c Cookie, now time.Time) {
|
||||
if c.Set.IsZero() { c.Set = now }
|
||||
|
||||
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
|
||||
j.cookies[host][key] = c
|
||||
j.cookies[host][key(c)] = c
|
||||
}
|
||||
|
||||
// Save writes the live cookies to path, readable only by the user.
|
||||
// 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 {
|
||||
data, err := json.MarshalIndent(j.Export(), "", " ")
|
||||
unlock, err := fsutil.Lock(path + ".lock")
|
||||
if err != nil { return err }
|
||||
defer unlock()
|
||||
|
||||
saved, err := readCookies(path)
|
||||
if err != nil { return err }
|
||||
|
||||
j.mu.Lock()
|
||||
now := j.now()
|
||||
for host, cookies := range saved { j.importLocked(host, cookies, now) }
|
||||
|
||||
out := map[string][]Cookie{}
|
||||
for host, byKey := range j.cookies {
|
||||
for _, k := range slices.Sorted(maps.Keys(byKey)) {
|
||||
c := byKey[k]
|
||||
if c.expired(now) && now.Sub(c.Set) > forgetDeleted {
|
||||
delete(byKey, k)
|
||||
continue
|
||||
}
|
||||
|
||||
out[host] = append(out[host], c)
|
||||
}
|
||||
}
|
||||
j.mu.Unlock()
|
||||
|
||||
data, err := json.MarshalIndent(out, "", " ")
|
||||
if err != nil { return err }
|
||||
|
||||
return fsutil.WriteFileAtomic(path, data, 0o600)
|
||||
@@ -164,18 +200,25 @@ func (j *Jar) Save(path string) error {
|
||||
|
||||
// Load imports the cookies saved at path. A missing file is not an error.
|
||||
func (j *Jar) Load(path string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) { return nil }
|
||||
saved, err := readCookies(path)
|
||||
if err != nil { return err }
|
||||
|
||||
var saved map[string][]Cookie
|
||||
if err := json.Unmarshal(data, &saved); err != nil { return err }
|
||||
|
||||
for host, cookies := range saved { j.Import(host, cookies) }
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readCookies(path string) (map[string][]Cookie, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) { return nil, nil }
|
||||
if err != nil { return nil, err }
|
||||
|
||||
var saved map[string][]Cookie
|
||||
if err := json.Unmarshal(data, &saved); err != nil { return nil, err }
|
||||
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
// defaultPath is the RFC 6265 default-path of a request path.
|
||||
func defaultPath(p string) string {
|
||||
if p == "" || p[0] != '/' { return "/" }
|
||||
|
||||
Reference in new issue
Block a user