Add tls-client fetch pipeline.
Add Chrome 152 fingerprint and navigation headers, Accept-Language by TLD, challenge/block classification, and a cookie jar that can be saved and exported per host. Bumps x/net, x/text, x/crypto and circl for govulncheck findings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
94bfc87e9d
commit
f90ef18f90
8 files changed
+906
-4
No files matched your search
@@ -2,4 +2,25 @@ module git.security-command.org/Overlord/dibs
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require github.com/pelletier/go-toml/v2 v2.4.3
|
||||
require (
|
||||
github.com/bogdanfinn/fhttp v0.6.9
|
||||
github.com/bogdanfinn/tls-client v1.16.0
|
||||
github.com/pelletier/go-toml/v2 v2.4.3
|
||||
golang.org/x/net v0.60.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/bdandy/go-errors v1.2.2 // indirect
|
||||
github.com/bdandy/go-socks4 v1.2.3 // indirect
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect
|
||||
github.com/bogdanfinn/utls v1.7.8-barnius // indirect
|
||||
github.com/bogdanfinn/websocket v1.5.6-barnius // indirect
|
||||
github.com/cloudflare/circl v1.6.5 // indirect
|
||||
github.com/klauspost/compress v1.18.2 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
@@ -1,2 +1,52 @@
|
||||
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q=
|
||||
github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM=
|
||||
github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic=
|
||||
github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI=
|
||||
github.com/bogdanfinn/fhttp v0.6.9 h1:F9MsWR1K6JMRlXN4Q/MfjYmptr29nCdycQo+OPBG5U0=
|
||||
github.com/bogdanfinn/fhttp v0.6.9/go.mod h1:7phoj3f/q54WuiTnCTlAhEoaVcdlruKkSzCSD47LzHk=
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.10-utls h1:oZN+J3OKMmWaVbI/sx4ULvHiAXbWJKVcvEFW4fkybMU=
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.10-utls/go.mod h1:bBLJ2Vy68Q7y6VfbG9czd825rTcQua7n+y12RM9Q588=
|
||||
github.com/bogdanfinn/tls-client v1.16.0 h1:km3YLI6CMRLZnfrC+hGStePPryIicd3hoxFQvHB1itY=
|
||||
github.com/bogdanfinn/tls-client v1.16.0/go.mod h1:TxbiXlpZhNN5xmxzsr3KhNAeqoEEPJafwgBbyp26Phc=
|
||||
github.com/bogdanfinn/utls v1.7.8-barnius h1:wRT83mP4hmuMM1/lIpLKKhzaEuyEKjux7VSj7XHFXdg=
|
||||
github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw=
|
||||
github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I=
|
||||
github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA=
|
||||
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
|
||||
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -22,6 +22,7 @@ func indexPositions(doc []byte) positions {
|
||||
// A parse error stops the index early. The decoder reports it.
|
||||
for p.NextExpression() {
|
||||
e := p.Expression()
|
||||
if e == nil { continue }
|
||||
|
||||
switch e.Kind {
|
||||
case unstable.Table, unstable.ArrayTable:
|
||||
@@ -36,6 +37,8 @@ func indexPositions(doc []byte) positions {
|
||||
ps.add(&p, path, first)
|
||||
case unstable.KeyValue:
|
||||
ps.keyValue(&p, prefix, e)
|
||||
default:
|
||||
// Comments and other expressions have no key to record.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,10 +70,10 @@ func (ps positions) value(p *unstable.Parser, path string, v *unstable.Node) {
|
||||
case unstable.InlineTable:
|
||||
it := v.Children()
|
||||
for it.Next() {
|
||||
if kv := it.Node(); kv.Kind == unstable.KeyValue {
|
||||
ps.keyValue(p, path, kv)
|
||||
}
|
||||
if kv := it.Node(); kv.Kind == unstable.KeyValue { ps.keyValue(p, path, kv) }
|
||||
}
|
||||
default:
|
||||
// Scalars have no nested keys.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
http "github.com/bogdanfinn/fhttp"
|
||||
"github.com/bogdanfinn/tls-client/profiles"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come
|
||||
// from the profile, the headers from the version. Bump both together when
|
||||
// updating tls-client.
|
||||
const chromeMajor = 152
|
||||
|
||||
var chromeProfile = profiles.Chrome_152
|
||||
|
||||
// Browser is the browser that requests claim to come from.
|
||||
type Browser struct {
|
||||
Profile profiles.ClientProfile
|
||||
Major int
|
||||
UserAgent string
|
||||
Platform string // sec-ch-ua-platform, without quotes
|
||||
}
|
||||
|
||||
// DefaultBrowser returns desktop Chrome on the current OS, so that cookies
|
||||
// a real browser on this machine obtains later stay valid for us.
|
||||
func DefaultBrowser() Browser {
|
||||
ua, platform := "Windows NT 10.0; Win64; x64", "Windows"
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
ua, platform = "Macintosh; Intel Mac OS X 10_15_7", "macOS"
|
||||
case "linux":
|
||||
ua, platform = "X11; Linux x86_64", "Linux"
|
||||
default:
|
||||
// Windows, and anything else, which Chrome supports no better.
|
||||
}
|
||||
|
||||
return Browser{
|
||||
Profile: chromeProfile,
|
||||
Major: chromeMajor,
|
||||
UserAgent: fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.0.0 Safari/537.36", ua, chromeMajor),
|
||||
Platform: platform,
|
||||
}
|
||||
}
|
||||
|
||||
// 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{
|
||||
"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-mode": {"navigate"},
|
||||
"sec-fetch-user": {"?1"},
|
||||
"sec-fetch-dest": {"document"},
|
||||
"accept-encoding": {"gzip, deflate, br, zstd"},
|
||||
"accept-language": {acceptLanguage(u.Hostname())},
|
||||
"priority": {"u=0, i"},
|
||||
http.HeaderOrderKey: {
|
||||
"sec-ch-ua",
|
||||
"sec-ch-ua-mobile",
|
||||
"sec-ch-ua-platform",
|
||||
"upgrade-insecure-requests",
|
||||
"user-agent",
|
||||
"accept",
|
||||
"sec-fetch-site",
|
||||
"sec-fetch-mode",
|
||||
"sec-fetch-user",
|
||||
"sec-fetch-dest",
|
||||
"accept-encoding",
|
||||
"accept-language",
|
||||
"cookie",
|
||||
"priority",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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 give us away
|
||||
// after an update.
|
||||
func secCHUA(major int) string {
|
||||
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)])
|
||||
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)
|
||||
|
||||
return strings.Join(brands[:], ", ")
|
||||
}
|
||||
|
||||
// languages maps a public suffix to the Accept-Language a local shopper's
|
||||
// browser would send.
|
||||
var languages = map[string]string{
|
||||
"de": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"at": "de-AT,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"ch": "de-CH,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"co.uk": "en-GB,en;q=0.9",
|
||||
"uk": "en-GB,en;q=0.9",
|
||||
"ie": "en-IE,en;q=0.9",
|
||||
"fr": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"be": "nl-BE,nl;q=0.9,fr-BE;q=0.8,fr;q=0.7,en;q=0.6",
|
||||
"it": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"es": "es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"nl": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"pl": "pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"se": "sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"com": "en-US,en;q=0.9",
|
||||
}
|
||||
|
||||
func acceptLanguage(host string) string {
|
||||
suffix, _ := publicsuffix.PublicSuffix(strings.ToLower(host))
|
||||
if lang, ok := languages[suffix]; ok { return lang }
|
||||
|
||||
return languages["com"]
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
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", "<title>Just a moment...</title>"},
|
||||
{"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 ""
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// 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 (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
stdhttp "net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
http "github.com/bogdanfinn/fhttp"
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
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")
|
||||
|
||||
type Options struct {
|
||||
// Browser to impersonate. Defaults to DefaultBrowser().
|
||||
Browser *Browser
|
||||
// Jar holds the cookies. Defaults to a new, empty jar.
|
||||
Jar *Jar
|
||||
// Timeout per request, including redirects. Defaults to DefaultTimeout.
|
||||
Timeout time.Duration
|
||||
// MaxBody is the largest body read, after decompression. Defaults to
|
||||
// DefaultMaxBody.
|
||||
MaxBody int64
|
||||
}
|
||||
|
||||
// Client fetches pages. It is safe for concurrent use.
|
||||
type Client struct {
|
||||
http tlsclient.HttpClient
|
||||
browser Browser
|
||||
jar *Jar
|
||||
maxBody int64
|
||||
}
|
||||
|
||||
// Response is a fetched page.
|
||||
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.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, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil
|
||||
}
|
||||
|
||||
// Jar returns the client's cookie jar.
|
||||
func (c *Client) Jar() *Jar { return c.jar }
|
||||
|
||||
// Get fetches rawURL the way Chrome opens a bookmark. A response with a bad
|
||||
// status is not an error: check Verdict.
|
||||
func (c *Client) Get(ctx context.Context, rawURL string) (*Response, 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) }
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||
if err != nil { return nil, err }
|
||||
req.Header = c.browser.navigationHeaders(u)
|
||||
|
||||
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 := &Response{
|
||||
URL: rawURL,
|
||||
FinalURL: resp.Request.URL.String(),
|
||||
Status: resp.StatusCode,
|
||||
Header: stdhttp.Header(resp.Header),
|
||||
Body: data,
|
||||
Elapsed: time.Since(start),
|
||||
}
|
||||
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
|
||||
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
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) }
|
||||
}
|
||||
|
||||
func newTestClient(t *testing.T, opts Options) *Client {
|
||||
t.Helper()
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
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://") }
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
http "github.com/bogdanfinn/fhttp"
|
||||
"github.com/bogdanfinn/fhttp/cookiejar"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// Cookie is a stored cookie, in a form that survives a restart and can be
|
||||
// handed to and from a browser.
|
||||
type Cookie struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Domain string `json:"domain"` // the host for host-only cookies
|
||||
HostOnly bool `json:"host_only,omitempty"`
|
||||
Path string `json:"path"`
|
||||
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
|
||||
Secure bool `json:"secure,omitempty"`
|
||||
HTTPOnly bool `json:"http_only,omitempty"`
|
||||
}
|
||||
|
||||
func (c Cookie) expired(now time.Time) bool {
|
||||
return !c.Expires.IsZero() && !c.Expires.After(now)
|
||||
}
|
||||
|
||||
// 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
|
||||
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewJar() *Jar {
|
||||
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
||||
|
||||
return &Jar{
|
||||
jar: jar,
|
||||
cookies: map[string]map[string]Cookie{},
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// SetCookies implements http.CookieJar.
|
||||
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
j.jar.SetCookies(u, cookies)
|
||||
|
||||
host := strings.ToLower(u.Hostname())
|
||||
now := j.now()
|
||||
|
||||
for _, hc := range cookies {
|
||||
c := Cookie{
|
||||
Name: hc.Name,
|
||||
Value: hc.Value,
|
||||
Domain: strings.TrimPrefix(strings.ToLower(hc.Domain), "."),
|
||||
Path: hc.Path,
|
||||
Expires: hc.Expires,
|
||||
Secure: hc.Secure,
|
||||
HTTPOnly: hc.HttpOnly,
|
||||
}
|
||||
|
||||
if c.Domain == "" { c.Domain, c.HostOnly = host, true }
|
||||
if c.Path == "" || !strings.HasPrefix(c.Path, "/") { c.Path = defaultPath(u.Path) }
|
||||
|
||||
switch {
|
||||
case hc.MaxAge < 0:
|
||||
c.Expires = now
|
||||
case hc.MaxAge > 0:
|
||||
c.Expires = now.Add(time.Duration(hc.MaxAge) * time.Second)
|
||||
default:
|
||||
// No Max-Age: Expires decides.
|
||||
}
|
||||
|
||||
j.store(host, c, now)
|
||||
}
|
||||
}
|
||||
|
||||
// Cookies implements http.CookieJar.
|
||||
func (j *Jar) Cookies(u *url.URL) []*http.Cookie {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
return j.jar.Cookies(u)
|
||||
}
|
||||
|
||||
// Export returns the live cookies of every host, sorted by name.
|
||||
func (j *Jar) Export() map[string][]Cookie {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
now := j.now()
|
||||
out := map[string][]Cookie{}
|
||||
|
||||
for host, byKey := range j.cookies {
|
||||
for _, key := range slices.Sorted(maps.Keys(byKey)) {
|
||||
if c := byKey[key]; !c.expired(now) { out[host] = append(out[host], c) }
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// Import adds cookies as if host had set them. Expired cookies are skipped.
|
||||
func (j *Jar) Import(host string, cookies []Cookie) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
|
||||
host = strings.ToLower(host)
|
||||
now := j.now()
|
||||
|
||||
for _, c := range cookies {
|
||||
if c.expired(now) { continue }
|
||||
|
||||
hc := &http.Cookie{
|
||||
Name: c.Name,
|
||||
Value: c.Value,
|
||||
Path: c.Path,
|
||||
Expires: c.Expires,
|
||||
Secure: c.Secure,
|
||||
HttpOnly: c.HTTPOnly,
|
||||
}
|
||||
if !c.HostOnly { hc.Domain = c.Domain }
|
||||
|
||||
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
|
||||
|
||||
if c.expired(now) {
|
||||
delete(j.cookies[host], key)
|
||||
return
|
||||
}
|
||||
|
||||
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
|
||||
j.cookies[host][key] = c
|
||||
}
|
||||
|
||||
// Save writes the live cookies to path, readable only by the user.
|
||||
func (j *Jar) Save(path string) error {
|
||||
data, err := json.MarshalIndent(j.Export(), "", " ")
|
||||
if err != nil { return err }
|
||||
|
||||
return 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 {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) { return nil }
|
||||
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
|
||||
}
|
||||
|
||||
// defaultPath is the RFC 6265 default-path of a request path.
|
||||
func defaultPath(p string) string {
|
||||
if p == "" || p[0] != '/' { return "/" }
|
||||
|
||||
i := strings.LastIndex(p, "/")
|
||||
if i == 0 { return "/" }
|
||||
|
||||
return p[:i]
|
||||
}
|
||||
|
||||
// writeFileAtomic replaces path with data, so a crash never leaves a
|
||||
// half-written file behind.
|
||||
func writeFileAtomic(path string, data []byte, perm fs.FileMode) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err }
|
||||
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
|
||||
if err != nil { return err }
|
||||
defer func() { _ = os.Remove(tmp.Name()) }()
|
||||
|
||||
if err := tmp.Chmod(perm); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tmp.Close(); err != nil { return err }
|
||||
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
Reference in new issue
Block a user