package fetch import ( "bytes" "net/http" "strings" ) // Verdict says what a response means for the watcher. type Verdict int const ( // OK is a page the plugin can parse. OK Verdict = iota // NotFound (404, 410) means the item is not available, never an error. NotFound // Challenge is a bot check that a real browser may clear. Challenge // Blocked is a refusal without a recognisable challenge, e.g. a plain 403 // or 429. Back off and retry later. Blocked // HTTPError is any other non-2xx status. HTTPError ) func (v Verdict) String() string { switch v { case OK: return "ok" case NotFound: return "not-found" case Challenge: return "challenge" case Blocked: return "blocked" case HTTPError: return "http-error" default: return "unknown" } } type marker struct { name string needle string } // strongMarkers only appear on bot check pages, so they count whatever the // status. Amazon answers its captcha with a 200, for example. var strongMarkers = []marker{ {"cloudflare", "window._cf_chl_opt"}, {"amazon-captcha", `action="/errors/validateCaptcha"`}, {"datadome", "geo.captcha-delivery.com"}, {"perimeterx", `id="px-captcha"`}, } // weakMarkers also show up on normal pages (Cloudflare injects its // challenge-platform script, shops embed Turnstile in forms), so they only // count on a refusal status. var weakMarkers = []marker{ {"cloudflare", "Just a moment..."}, {"cloudflare", "/cdn-cgi/challenge-platform/"}, {"turnstile", "challenges.cloudflare.com/turnstile"}, {"recaptcha", "www.google.com/recaptcha/"}, {"hcaptcha", "hcaptcha.com/1/api.js"}, {"captcha", "captcha"}, } // classify decides the verdict for a response. For Challenge it also names // the bot check found. func classify(status int, header http.Header, finalURL string, body []byte) (Verdict, string) { lower := bytes.ToLower(body) if header.Get("cf-mitigated") == "challenge" { return Challenge, "cloudflare" } if strings.Contains(finalURL, "/errors/validateCaptcha") { return Challenge, "amazon-captcha" } if name := findMarker(lower, strongMarkers); name != "" { return Challenge, name } switch { case status >= 200 && status < 300: return OK, "" case status == http.StatusNotFound || status == http.StatusGone: return NotFound, "" case status == http.StatusForbidden || status == http.StatusTooManyRequests || status == http.StatusServiceUnavailable: if name := findMarker(lower, weakMarkers); name != "" { return Challenge, name } return Blocked, "" default: return HTTPError, "" } } // findMarker returns the name of the first marker in the lowercased body. func findMarker(lower []byte, markers []marker) string { for _, m := range markers { if bytes.Contains(lower, []byte(strings.ToLower(m.needle))) { return m.name } } return "" }