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>
213 lines
5.1 KiB
Go
213 lines
5.1 KiB
Go
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)
|
|
}
|