Documentation
¶
Overview ¶
Package mimicry is an HTTP client that looks like a real browser on the network: the same TLS handshake, HTTP/2 and HTTP/3 settings, and headers in the same order. Use it to automate user actions on sites that check them.
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
})
if err != nil {
return err
}
resp, err := client.Get("https://shop.example/") // a page load
A request is a page load, as if typed into the address bar, unless you say otherwise. To send it as a script on the last page would (fetch, XHR, an image), wrap it with As or With:
req, _ := http.NewRequest("GET", "https://shop.example/api/cart", nil)
resp, err = client.Do(mimicry.As(req, mimicry.Fetch))
Defaults match the browser; Config fields that change that say so. A profile holds only what was recorded from the real browser: asking for anything else fails with ErrNotMeasured instead of guessing. Built-in profiles are in package profiles: Chrome, Firefox and Safari on macOS, Chrome and Firefox on Windows (profiles.ChromeWindows, profiles.FirefoxWindows). Guides are in the repository's docs directory.
Index ¶
- Constants
- Variables
- func As(req *http.Request, k Kind) *http.Request
- func Exact(req *http.Request) *http.Request
- func NewClient(cfg Config) (*http.Client, error)
- func With(req *http.Request, r Request) *http.Request
- type AltSvcCache
- type CORSError
- type CertPin
- type CertRole
- type CloseError
- type Config
- type Credentials
- type CrossOrigin
- type Header
- type Kind
- type Lines
- type MessageType
- type Override
- type Pin
- type PinError
- type Place
- type Plan
- type Priority
- type ProxyError
- type Request
- type Transport
- func (t *Transport) CloseIdleConnections()
- func (t *Transport) Cookies() *cookies.Jar
- func (t *Transport) DialWebSocket(ctx context.Context, rawURL string, opts WebSocketOptions) (*WebSocket, *http.Response, error)
- func (t *Transport) Plan(req *http.Request) (*Plan, error)
- func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)
- type WebSocket
- func (w *WebSocket) Close(code int, reason string) error
- func (w *WebSocket) Extensions() string
- func (w *WebSocket) Protocol() string
- func (w *WebSocket) ReadMessage(ctx context.Context) (MessageType, []byte, error)
- func (w *WebSocket) WriteMessage(ctx context.Context, typ MessageType, data []byte) error
- type WebSocketOptions
Examples ¶
Constants ¶
const HeaderOrderKey = headerorder.Key
HeaderOrderKey is a pseudo request header whose values are header names, in the order to send them; it is never sent itself. It replaces the profile's order, so profile defaults it does not name are not sent; the request's own unnamed headers follow the named ones. It overrides Config.HeaderPlacement; use a Place to move one header instead.
Variables ¶
var ErrNotMeasured = headerorder.ErrNotMeasured
ErrNotMeasured reports a request the profile cannot describe: one its browser was never captured making. RoundTrip returns it (wrapped, with what is missing) rather than guess. Test for it with errors.Is.
var ErrPlacement = headerorder.ErrPlacement
ErrPlacement reports a header placement that cannot be applied: an invalid Place, a header or anchor the request does not send, or Request.HeaderPlacement on a request with its own order (Exact, HeaderOrderKey). Test for it with errors.Is.
Functions ¶
func As ¶
As returns req, made as kind k by the page the transport last navigated to: With(req, Request{Kind: k}). The last navigation is the transport's, whichever goroutine made it; parallel tasks browsing different pages use a Transport each, or set Request.From.
Example ¶
Load a product page, then call the shop's API from it as the page's script would, with fetch().
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("server: %s %s sec-fetch-mode=%s referer=%q cookie=%q\n", r.Method, r.URL.Path,
r.Header.Get("Sec-Fetch-Mode"), r.Header.Get("Referer"), r.Header.Get("Cookie"))
switch r.URL.Path {
case "/p/42":
w.Header().Set("Set-Cookie", "session=s1; Path=/; Secure; HttpOnly")
_, _ = io.WriteString(w, "<title>Kettle</title>")
case "/api/stock/42":
_, _ = io.WriteString(w, `{"sku":42,"inStock":true}`)
}
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
ctx := context.Background()
page, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/p/42", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(page)
if err != nil {
panic(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
// The API call is a fetch() from the page the client last navigated
// to: sec-fetch-*, Referer, Origin and cookies follow from that page.
api, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/api/stock/42", nil)
if err != nil {
panic(err)
}
resp, err = client.Do(mimicry.As(api, mimicry.Fetch))
if err != nil {
panic(err)
}
var stock struct {
SKU int `json:"sku"`
InStock bool `json:"inStock"`
}
err = json.NewDecoder(resp.Body).Decode(&stock)
_ = resp.Body.Close()
if err != nil {
panic(err)
}
fmt.Printf("sku %d in stock: %v\n", stock.SKU, stock.InStock)
Output: server: GET /p/42 sec-fetch-mode=navigate referer="" cookie="" server: GET /api/stock/42 sec-fetch-mode=cors referer="https://www.shop.test/p/42" cookie="session=s1" sku 42 in stock: true
Example (AddToCart) ¶
Add to cart: a JSON POST from the product page, carrying the CSRF token the page holds.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/p/42":
_, _ = io.WriteString(w, `<meta name="csrf-token" content="t0k3n">`)
case "/api/cart":
body, _ := io.ReadAll(r.Body)
fmt.Println("server:", r.Method, r.URL.Path, string(body))
fmt.Println("server: origin:", r.Header.Get("Origin"), "content-type:", r.Header.Get("Content-Type"),
"x-csrf-token:", r.Header.Get("X-CSRF-Token"))
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"items":1}`)
}
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
ctx := context.Background()
page, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/p/42", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(page)
if err != nil {
panic(err)
}
html, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
panic(err)
}
token := regexp.MustCompile(`name="csrf-token" content="([^"]+)"`).FindSubmatch(html)[1]
// Headers the page's script sets go on the request; the profile adds
// the browser's own around them, in the browser's order, and Origin
// for a POST. Same-origin, so no CORS preflight.
add, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://www.shop.test/api/cart", strings.NewReader(`{"sku":42,"qty":1}`))
if err != nil {
panic(err)
}
add.Header.Set("Content-Type", "application/json")
add.Header.Set("X-CSRF-Token", string(token))
resp, err = client.Do(mimicry.As(add, mimicry.Fetch))
if err != nil {
panic(err)
}
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
panic(err)
}
fmt.Println(resp.Status, string(body))
Output: server: POST /api/cart {"sku":42,"qty":1} server: origin: https://www.shop.test content-type: application/json x-csrf-token: t0k3n 200 OK {"items":1}
func Exact ¶
Exact returns a shallow copy of req that sends exactly its own headers, in its own order (HeaderOrderKey) or sorted by name, plus Config.Header: no profile headers and nothing computed. TLS, HTTP/2 and the cookie jar still follow the profile.
func NewClient ¶
NewClient returns an *http.Client using a new Transport and, unless cfg.Cookies is set, a new jar with the profile's cookie rules (see Transport.Cookies). The jar is the transport's, not the client's Jar, because it needs the page, kind and redirects. The client follows redirects as far as the browser does (20, or the profile's redirects.navigationLimit for navigations); a custom CheckRedirect sees hops as http.Client built them. Its Timeout is Config.Timeout's (30 s by default). It costs what NewTransport does: build one per identity or proxy and reuse it.
Example ¶
Create a client for a browser profile and load a page.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("server:", r.Proto, r.Method, r.URL.Path)
fmt.Println("server: user-agent:", r.Header.Get("User-Agent"))
fmt.Println("server: sec-fetch-mode:", r.Header.Get("Sec-Fetch-Mode"), "sec-fetch-site:", r.Header.Get("Sec-Fetch-Site"))
_, _ = io.WriteString(w, "<title>Shop</title>")
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.Chrome155MacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
// NewClient sets a 30 s deadline for the whole exchange
// (Config.Timeout; or the request's context). Config.DialTimeout
// bounds connecting alone.
// A request with no kind is a navigation: the URL typed into the
// address bar, with the browser's headers, in its order.
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://www.shop.test/", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
body, err := io.ReadAll(resp.Body) // decompressed, as the browser would
_ = resp.Body.Close()
if err != nil {
panic(err)
}
fmt.Println(resp.Proto, resp.Status, string(body))
Output: server: HTTP/2.0 GET / server: user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 server: sec-fetch-mode: navigate sec-fetch-site: none HTTP/2.0 200 OK <title>Shop</title>
func With ¶
With returns a shallow copy of req made as r describes.
Example ¶
Check out: a form POST navigation from the cart page, answered with a 303 to the order page, and the redirect chain it took.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("server: %s %s sec-fetch-site=%s origin=%q referer=%q\n", r.Method, r.URL.Path,
r.Header.Get("Sec-Fetch-Site"), r.Header.Get("Origin"), r.Header.Get("Referer"))
switch r.URL.Path {
case "/cart":
_, _ = io.WriteString(w, `<form method="post" action="/checkout">`)
case "/checkout":
_ = r.ParseForm()
fmt.Println("server: form:", r.PostForm.Encode())
http.Redirect(w, r, "/orders/1001", http.StatusSeeOther)
case "/orders/1001":
_, _ = io.WriteString(w, "<title>Order 1001</title>")
}
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
ctx := context.Background()
cart, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/cart", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(cart)
if err != nil {
panic(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
// A form POST is a navigation from the page holding the form: From is
// that page. Its Content-Type is the request's, as the form's enctype.
form := url.Values{
"shipping": {"standard"},
"agree": {"on"},
}
checkout, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://www.shop.test/checkout", strings.NewReader(form.Encode()))
if err != nil {
panic(err)
}
checkout.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err = client.Do(mimicry.With(checkout, mimicry.Request{
Kind: mimicry.Navigate,
From: cart.URL,
}))
if err != nil {
panic(err)
}
_ = resp.Body.Close()
// The client followed the 303 with a GET, as the browser does. Each
// hop's request links to the response that redirected to it. (To stop
// at the 303 instead, set client.CheckRedirect to return
// http.ErrUseLastResponse.)
var chain []string
for r := resp.Request; r != nil; {
chain = append(chain, r.Method+" "+r.URL.Path)
if r.Response == nil {
break
}
chain = append(chain, r.Response.Status)
r = r.Response.Request
}
for _, c := range slices.Backward(chain) {
fmt.Println(c)
}
fmt.Println("now on", resp.Request.URL)
Output: server: GET /cart sec-fetch-site=none origin="" referer="" server: POST /checkout sec-fetch-site=same-origin origin="https://www.shop.test" referer="https://www.shop.test/cart" server: form: agree=on&shipping=standard server: GET /orders/1001 sec-fetch-site=same-origin origin="" referer="https://www.shop.test/cart" POST /checkout 303 See Other GET /orders/1001 now on https://www.shop.test/orders/1001
Types ¶
type AltSvcCache ¶
type AltSvcCache struct {
// contains filtered or unexported fields
}
AltSvcCache keeps the HTTP/3 alternatives servers advertise (Alt-Svc, RFC 7838) for the Transports given it in Config.AltSvc, as a browser keeps one for all its tabs and, saved to disk, across restarts (Chrome's HTTP server properties, Firefox's alternate services). A Transport finding an origin's alternative in it moves to HTTP/3 as its browser does once it knows one, so a new Transport's first request to an origin a previous Transport learnt can go over HTTP/3 (docs/concepts/http3.md says per browser).
An entry lives until its ma (max-age; 24 hours without one) or a "clear" from its origin. Only the alternatives are shared: which origins failed over QUIC, connections and session tickets stay each Transport's. Entries are kept per connection partition (anonymous requests and cross-site frames apart), not per top-level site: browsers partition them by top-level site too, which mimicry does not model. Create one with NewAltSvcCache; it is safe for concurrent use.
Example ¶
A browser keeps the HTTP/3 alternatives sites advertise (Alt-Svc) for all its tabs and across restarts, so a returning browser's first request to a site can go straight to HTTP/3. Config.AltSvc shares one AltSvcCache between Transports; WriteJSON and ReadJSON keep it between runs.
shop := startShop(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Alt-Svc", `h3=":443"; ma=86400`)
})
defer shop.Close()
cache := mimicry.NewAltSvcCache()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
AltSvc: cache,
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://www.shop.test/", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
_ = resp.Body.Close()
fmt.Println(resp.Proto, "advertising", resp.Header.Get("Alt-Svc"))
// Saved when the program exits (a file, in a real program)...
var saved bytes.Buffer
if err := cache.WriteJSON(&saved); err != nil {
panic(err)
}
var entries []struct {
Origin string `json:"origin"`
Port int `json:"port"`
}
if err := json.Unmarshal(saved.Bytes(), &entries); err != nil {
panic(err)
}
for _, e := range entries {
fmt.Println("saved:", e.Origin, "h3 on port", e.Port)
}
// ...and loaded when it starts again: every Transport given the cache
// starts www.shop.test on HTTP/3 as Chrome would, until the entry's
// max-age runs out.
restored := mimicry.NewAltSvcCache()
if err := restored.ReadJSON(&saved); err != nil {
panic(err)
}
Output: HTTP/2.0 advertising h3=":443"; ma=86400 saved: https://www.shop.test:443 h3 on port 443
func (*AltSvcCache) Clear ¶
func (c *AltSvcCache) Clear()
Clear forgets every alternative. Transports sharing the cache keep the QUIC connections they have.
func (*AltSvcCache) ReadJSON ¶
func (c *AltSvcCache) ReadJSON(r io.Reader) error
ReadJSON adds the alternatives of a JSON array WriteJSON wrote, replacing those of the same origin and partition. Expired ones are skipped; a malformed entry fails it before anything is added.
func (*AltSvcCache) WriteJSON ¶
func (c *AltSvcCache) WriteJSON(w io.Writer) error
WriteJSON writes the unexpired alternatives as a JSON array, each with its origin ("https://host:port"), partition (when not the default), port and expiry: what ReadJSON reads back.
type CORSError ¶
type CORSError struct {
// URL is the refused request's: the preflighted URL, or the one that
// answered with the redirect.
URL *url.URL
// Redirect is true when the refused response is URL's redirect, not
// its preflight's answer.
Redirect bool
// Reason is the CORS rule the response breaks.
Reason string
// Status and Header are the refused response's.
Status int
Header http.Header
}
CORSError is a request the browser would not send: its CORS preflight's answer does not allow it, or it follows a redirect that fails the CORS check (Redirect). RoundTrip did not send it (Request.IgnoreCORS sends it anyway).
type CertPin ¶
type CertPin struct {
Role CertRole
Subject string
Issuer string
NotAfter time.Time
// SPKI is the SHA-256 of its SubjectPublicKeyInfo as
// "sha256/<base64>"; SPKIHex the same hash in hex. They survive a
// certificate's renewal with the same key.
SPKI string
SPKIHex string
// Fingerprint is the SHA-256 of the whole certificate, hex bytes
// joined by colons; it changes with every renewal.
Fingerprint string
}
CertPin is a certificate of a site's verified chain, and the values that pin it (Pin.SPKI takes any of the three).
type CertRole ¶
type CertRole int
CertRole is a certificate's place in a verified chain.
A chain runs from the server's certificate (the leaf) through intermediates to the root that verified it. A leaf that is itself trusted (a chain of one) is a leaf.
type CloseError ¶
CloseError is what ReadMessage returns once the socket has closed with a close handshake: the server's close frame (its code and reason, which the socket echoed) or its echo of the socket's own. Code is 1005 when the frame had none.
func (*CloseError) Error ¶
func (e *CloseError) Error() string
type Config ¶
type Config struct {
// Profile is the browser to impersonate, such as profiles.ChromeMacOS(), or
// an edited copy of one (Profile.With). Required. A Profile is
// checked once and read-only, so building a Transport from one copies
// nothing: reuse it for every Transport. An edit With found invalid is
// NewTransport's error, a *profile.ValidationError.
Profile profile.Profile
// RootCAs verifies servers. Nil, the default, uses the system roots.
RootCAs *x509.CertPool
// DialTimeout bounds each TCP connect and TLS handshake. Zero means
// 30 seconds.
DialTimeout time.Duration
// Timeout is the Timeout of the client NewClient returns. It covers the
// whole request, redirects and body included. Zero means 30 seconds;
// negative means none. Raise it for large downloads or slow proxies.
// NewTransport ignores it: set your own http.Client's Timeout instead.
Timeout time.Duration
// DialContext opens TCP connections, to the proxy if there is one, as
// in http.Transport. TLS stays the browser's. Nil uses net.Dialer.
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// Resolver looks up host names. Nil uses net.DefaultResolver. Set it
// alongside DialContext when DialContext sends hosts to addresses DNS
// does not give, so connection sharing between hosts stays correct.
Resolver *net.Resolver
// Proxy picks the proxy for each request, as in http.Transport. Nil,
// the default, connects directly. Supported schemes are "http",
// "socks5" and "socks5h"; a failed proxy returns a *ProxyError. See
// docs/concepts/proxies.md.
Proxy func(*http.Request) (*url.URL, error)
// Header holds your own headers, such as an API key, added to every
// request where the browser places headers a page sets. They override
// the browser's defaults; the request's own headers override them. A
// key with no values removes a default. Content-Length, Connection and
// Transfer-Encoding are built from the request, except that
// Connection: close is honoured over HTTP/1.1. Default: none. Headers
// that differ between the clients of one profile (an Accept-Language,
// a user agent) belong here, not in a profile edited per client. A
// User-Agent set here does not reach an HTTP proxy, whose CONNECT
// carries the profile's; edit the profile (Profile.With) to change
// both.
Header http.Header
// HeaderPlacement moves headers within the browser's order on every
// request you send, redirect hops included. CORS preflights and
// WebSocket handshakes keep the browser's order; Exact and
// HeaderOrderKey requests keep their own. Default: none. NewTransport rejects an invalid Place with ErrPlacement.
HeaderPlacement []Place
// Cookies is the cookie jar requests use. When nil, NewClient creates
// one and NewTransport sends no cookies. Set it to share or seed
// cookies.
Cookies *cookies.Jar
// DisableDecompression returns bodies exactly as the server sent them.
// By default gzip, deflate, br and zstd bodies are decoded, and
// Content-Encoding and Content-Length removed. Other or stacked
// encodings always come back raw.
DisableDecompression bool
// DisableHTTP3 keeps every request on TCP. By default a request moves
// to HTTP/3 when the browser would, falling back to TCP if QUIC fails.
// Note that QUIC ignores DialContext. See docs/concepts/http3.md.
DisableHTTP3 bool
// AltSvc stores the HTTP/3 servers have advertised, shared by every
// Transport given the same cache, like a browser's tabs. Save and load
// it to keep it across runs. Nil, the default, keeps one per Transport.
AltSvc *AltSvcCache
// BrowserQUICFallback copies the browser's slow fallback when QUIC
// stalls or fails: requests wait as long as the browser's do. By
// default they move to TCP after the browser's race delay, or at once
// on failure. Connections that work are the same either way.
BrowserQUICFallback bool
// BrowserDialDelay holds a new QUIC connection a request waits for
// back before its first packet, as the browser does: Safari's 3–10 ms
// (resumed 5–11, rarely more), Firefox's resumed 4–9 ms. By default it
// starts at once; the packets are the same, only sent sooner.
BrowserDialDelay bool
// BrowserProxyAuth sends an http proxy the URL's credentials only after
// it answers 407, as browsers do. By default the first request sends
// them, saving a round trip per new proxy. Only the proxy sees the
// difference. A profile that did not measure the 407 flow
// (safari-27-ios: the iPhone never answers one) makes a request
// through a proxy with credentials ErrNotMeasured.
BrowserProxyAuth bool
// DisableCoalescing gives every host its own HTTP/2 connection. By
// default a host shares another host's connection when the browser
// would. Sharing is faster on clean networks; set this on lossy ones.
DisableCoalescing bool
// MaxConnsPerHost limits open HTTP/1.1 connections to one host; extra
// requests wait their turn. Zero means the browser's limit, 6. A higher
// value does not look like a browser. Negative is an error.
MaxConnsPerHost int
// IdleConnTimeout is how long an unused connection stays open. Zero
// means 90 seconds; negative means mimicry never closes idle
// connections itself. Longer reuses more connections at the cost of
// memory.
IdleConnTimeout time.Duration
// MaxIdleProxies is how many recently used proxies keep their idle
// connections. Zero means the 16 most recent, plus any used in the last
// 10 seconds; what mimicry learned through a proxy (its TLS sessions,
// a 407, a refused UDP relay) is then kept for the 1,024 most recent.
// Set 1 to close a proxy's connections as soon as you switch away from
// it: with a count, a proxy pushed out loses its connections and what
// it taught at once, and used again starts like a new proxy. Negative
// is an error.
MaxIdleProxies int
// HTTP3OverSOCKS5 lets requests through a SOCKS5 proxy use HTTP/3.
// Browsers never use HTTP/3 through a proxy, so by default those
// requests stay on TCP. A proxy that refuses UDP keeps them on TCP.
HTTP3OverSOCKS5 bool
// HTTP3ReadBufferSize is the receive buffer, in bytes, each HTTP/3
// connection asks the OS for. Zero asks for 1 MB, as Chrome does;
// negative keeps the OS default. The OS may grant less. Raise it for
// fast, long or lossy paths; nothing changes on the wire.
HTTP3ReadBufferSize int
// HTTP3ACKEvery acknowledges every Nth QUIC packet instead of the
// browser's rate, such as Chrome's every 10th. Zero, the default, keeps
// the browser's. It must be between the browser's rate and 64. Fewer
// ACKs help a busy server, but the server can see the difference.
HTTP3ACKEvery int
// Pins pins hosts to public keys: a request to a pinned host fails
// with a *PinError unless the certificate chain matches. Default: none.
// FetchPins lists a site's pins.
Pins []Pin
// VerifyConnection, when set, checks each connection after certificate
// verification and Pins, as crypto/tls's VerifyConnection does. An
// error fails the request before anything is sent. Default: none.
VerifyConnection func(tls.ConnectionState) error
// contains filtered or unexported fields
}
Config configures a Transport.
Example (Cookies) ¶
Cookies live in the Transport's jar: read them, seed some obtained elsewhere, delete one, and save the site's as a string.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("server: %s cookie=%q\n", r.URL.Path, r.Header.Get("Cookie"))
if r.URL.Path == "/" {
w.Header().Add("Set-Cookie", "session=s1; Path=/; Secure; HttpOnly")
w.Header().Add("Set-Cookie", "region=eu; Path=/; Max-Age=3600")
}
})
defer shop.Close()
// NewClient makes a jar with the profile's rules; Transport.Cookies
// returns it. Pass Config.Cookies to share one between Transports.
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
tr, ok := client.Transport.(*mimicry.Transport)
if !ok {
panic("NewClient's Transport is a *mimicry.Transport")
}
jar := tr.Cookies()
get := func(rawURL string) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}
get("https://www.shop.test/")
for _, c := range jar.All() {
fmt.Printf("jar: %s=%s domain=%s secure=%v session=%v\n", c.Name, c.Value, c.Domain, c.Secure, c.Expires.IsZero())
}
// Cookies from elsewhere (another tool, a saved session) as a Cookie
// header string, for shop.test and every name under it.
if err := jar.SetString("shop.test", "consent=yes"); err != nil {
panic(err)
}
get("https://www.shop.test/cart")
jar.Delete(func(c *cookies.Cookie) bool {
return c.Name == "region"
})
get("https://www.shop.test/cart")
fmt.Printf("saved: %q\n", jar.String("shop.test"))
Output: server: / cookie="" jar: session=s1 domain=www.shop.test secure=true session=true jar: region=eu domain=www.shop.test secure=false session=false server: /cart cookie="session=s1; region=eu; consent=yes" server: /cart cookie="session=s1; consent=yes" saved: "session=s1; consent=yes"
Example (DisableHTTP3) ¶
HTTP/3 is on by default: once a site advertises it (Alt-Svc), requests move to it as the profile's browser moves them. DisableHTTP3 keeps everything on TCP, for networks that block UDP. (Requests through a proxy stay on TCP unless HTTP3OverSOCKS5 lets a SOCKS5 proxy carry it.)
shop := startShop(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Alt-Svc", `h3=":443"; ma=86400`)
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
DisableHTTP3: true,
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
for range 3 {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://www.shop.test/", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
_ = resp.Body.Close()
fmt.Println(resp.Proto)
}
Output: HTTP/2.0 HTTP/2.0 HTTP/2.0
Example (HeaderPlacement) ¶
Header placement: the browser's order with one deliberate change. Config.HeaderPlacement applies to every request, Request.HeaderPlacement to one, after Config's. The shop speaks HTTP/1.1 so its handler can print lines in arrival order.
shop := startShopHTTP1(func(_ http.ResponseWriter, r *http.Request) {
lines := headerLines(r)
if r.URL.Path == "/" {
return
}
fmt.Println("server:", r.Method, r.URL.Path)
for _, line := range lines {
fmt.Println("server: ", line)
}
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.Chrome155MacOS(),
Header: http.Header{
"X-Api-Key": {"k3y"},
},
// Without it the key would go where Chrome puts a page's own
// headers; with it, directly after User-Agent, on every request.
HeaderPlacement: []mimicry.Place{
{
Header: "X-Api-Key",
After: "User-Agent",
},
},
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
newRequest := func(rawURL string) *http.Request {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil)
if err != nil {
panic(err)
}
req.Header.Set("X-CSRF-Token", "t0k3n")
return req
}
send := func(req *http.Request) error {
resp, err := client.Do(req)
if err != nil {
return err
}
return resp.Body.Close()
}
if err := send(newRequest("https://www.shop.test/")); err != nil {
panic(err)
}
// The page's own header where Chrome puts it.
if err := send(mimicry.As(newRequest("https://www.shop.test/api/cart"), mimicry.Fetch)); err != nil {
panic(err)
}
// The same request with its token moved to just before Accept.
if err := send(mimicry.With(newRequest("https://www.shop.test/api/cart"), mimicry.Request{
Kind: mimicry.Fetch,
HeaderPlacement: []mimicry.Place{
{
Header: "X-CSRF-Token",
Before: "Accept",
},
},
})); err != nil {
panic(err)
}
// An anchor the request does not send (this shop set no cookies) is
// an error, and nothing is sent.
err = send(mimicry.With(newRequest("https://www.shop.test/api/cart"), mimicry.Request{
Kind: mimicry.Fetch,
HeaderPlacement: []mimicry.Place{
{
Header: "X-CSRF-Token",
After: "Cookie",
},
},
}))
fmt.Println("placement error:", errors.Is(err, mimicry.ErrPlacement))
Output: server: GET /api/cart server: Host: www.shop.test server: Connection: keep-alive server: sec-ch-ua-platform: "macOS" server: x-csrf-token: t0k3n server: User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 server: x-api-key: k3y server: sec-ch-ua: "Google Chrome";v="155", "Chromium";v="155", "Not(A:Brand";v="24" server: sec-ch-ua-mobile: ?0 server: Accept: */* server: Sec-Fetch-Site: same-origin server: Sec-Fetch-Mode: cors server: Sec-Fetch-Dest: empty server: Referer: https://www.shop.test/ server: Accept-Encoding: gzip, deflate, br, zstd server: Accept-Language: en-US,en;q=0.9 server: GET /api/cart server: Host: www.shop.test server: Connection: keep-alive server: sec-ch-ua-platform: "macOS" server: User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 server: x-api-key: k3y server: sec-ch-ua: "Google Chrome";v="155", "Chromium";v="155", "Not(A:Brand";v="24" server: sec-ch-ua-mobile: ?0 server: x-csrf-token: t0k3n server: Accept: */* server: Sec-Fetch-Site: same-origin server: Sec-Fetch-Mode: cors server: Sec-Fetch-Dest: empty server: Referer: https://www.shop.test/ server: Accept-Encoding: gzip, deflate, br, zstd server: Accept-Language: en-US,en;q=0.9 placement error: true
Example (Pins) ¶
Certificate pinning: FetchPins lists a site's verified chain, and Config.Pins pins a host to keys from it (usually the intermediate's). A connection matching none fails with a *PinError before anything is sent.
shop := startShop(func(http.ResponseWriter, *http.Request) {})
defer shop.Close()
cfg := mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
chain, err := mimicry.FetchPins(ctx, cfg, "https://www.shop.test/")
if err != nil {
panic(err)
}
var intermediate string
for _, c := range chain {
fmt.Println(c.Role, c.Subject)
if c.Role == mimicry.CertIntermediate {
intermediate = c.SPKI // "sha256/<base64>"
}
}
get := func(pin string) {
cfg.Pins = []mimicry.Pin{
{
Host: "shop.test",
IncludeSubdomains: true,
SPKI: []string{
pin,
},
},
}
client, err := mimicry.NewClient(cfg)
if err != nil {
panic(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if pe, ok := errors.AsType[*mimicry.PinError](err); ok {
fmt.Println("refused:", pe.Host, "presented", len(pe.Presented), "keys")
return
}
if err != nil {
panic(err)
}
_ = resp.Body.Close()
fmt.Println(resp.Status, "over", resp.TLS.NegotiatedProtocol, "from", resp.TLS.VerifiedChains[0][1].Subject.CommonName)
}
get(intermediate)
get("sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") // someone else's key
Output: leaf CN=shop.test intermediate CN=Shop Test Issuing CA root CN=Shop Test Root CA 200 OK over h2 from Shop Test Issuing CA refused: www.shop.test presented 3 keys
Example (Proxy) ¶
Proxies: Config.Proxy picks one per request, so rotating is changing what it returns. A *ProxyError means the proxy failed, not the site: take the next one. Cookies and the last page stay the Transport's.
shop := startShop(func(_ http.ResponseWriter, r *http.Request) {
fmt.Println("server:", r.URL.Path)
})
defer shop.Close()
first := startProxy(shop, "alice", "secret")
defer first.Close()
second := startProxy(shop, "", "")
defer second.Close()
// The first proxy again, with a password it no longer takes.
expired := *first.URL
expired.User = url.UserPassword("alice", "expired")
proxies := []*url.URL{&expired, first.URL, second.URL}
var current atomic.Pointer[url.URL]
current.Store(proxies[0])
rotate := func() {
proxies = proxies[1:]
current.Store(proxies[0])
}
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
Proxy: func(*http.Request) (*url.URL, error) {
return current.Load(), nil
},
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
get := func(rawURL string) {
for {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if pe, ok := errors.AsType[*mimicry.ProxyError](err); ok {
fmt.Printf("proxy failed: %d as %s (password in the error: %t)\n",
pe.StatusCode, pe.Proxy.User.Username(), strings.Contains(err.Error(), "expired"))
rotate()
continue
}
if err != nil {
panic(err)
}
_ = resp.Body.Close()
return
}
}
// The credentials go with the first CONNECT (Config.BrowserProxyAuth
// waits for the proxy's 407, as Chrome does: a round trip more).
get("https://www.shop.test/")
get("https://www.shop.test/cart") // the same tunnel
rotate() // say, after a 403 from the site
get("https://www.shop.test/cart") // a new tunnel, through the second proxy
for _, line := range first.Log() {
fmt.Println("first proxy:", line)
}
for _, line := range second.Log() {
fmt.Println("second proxy:", line)
}
Output: proxy failed: 407 as alice (password in the error: false) server: / server: /cart server: /cart first proxy: CONNECT www.shop.test:443 as alice: 407 first proxy: CONNECT www.shop.test:443 as alice: 200 second proxy: CONNECT www.shop.test:443 without credentials: 200
type Credentials ¶
type Credentials int
Credentials is a fetch() or XHR request's credentials mode: whether it carries cookies.
const ( CredentialsSameOrigin Credentials = iota CredentialsInclude // credentials: "include", withCredentials = true CredentialsOmit // credentials: "omit" )
Credentials modes. CredentialsSameOrigin is fetch()'s default and XHR's without withCredentials.
type CrossOrigin ¶
type CrossOrigin int
CrossOrigin is an element's crossorigin attribute, which makes its request a CORS request.
const ( CrossOriginNone CrossOrigin = iota CrossOriginAnonymous // crossorigin, crossorigin="anonymous" CrossOriginUseCredentials // crossorigin="use-credentials" )
CrossOrigin values. CrossOriginNone is no attribute: the element's own mode.
type Kind ¶
type Kind int
Kind is how a page makes a request, named after the HTML or JavaScript that makes it. Browsers send each kind with headers, an order and a priority of its own; a request's kind picks the profile's description of it.
const ( Frame // <iframe src> Script // <script src> in the HTML: blocking AsyncScript // <script async src> DeferScript // <script defer src> InjectedScript // a script element created by script PreloadScript // <link rel=preload as=script> Style // <link rel=stylesheet> Image // <img src> in the HTML InjectedImage // new Image() Font // a web font from CSS @font-face PreloadFont // <link rel=preload as=font crossorigin> Fetch // fetch() XHR // XMLHttpRequest Beacon // navigator.sendBeacon )
Request kinds. Navigate, the default, is a user's top-level navigation (typed URL, link, submit button) with the profile's Sec-Fetch-User; a script's navigation suppresses it with a nil Sec-Fetch-User header.
const Preflight Kind = -1
Preflight is the kind of a CORS preflight, the OPTIONS request the transport sends before a request that needs one. It appears only in plans (the Kind of Plan.Preflight): the transport makes preflights itself, and a request sent As or With Preflight fails.
type Lines ¶
type Lines struct {
// RequestLine is HTTP/1.1's ("GET /path HTTP/1.1"); empty over
// HTTP/2 and HTTP/3, whose pseudo-headers carry it.
RequestLine string
// Headers are the header lines in order: pseudo-headers first and
// lowercase over HTTP/2 and HTTP/3; over HTTP/1.1 as the browser
// spells them, Host, Connection and framing included. Cookie is the
// jar's current value.
Headers []Header
// Err is why the request cannot use this protocol (Headers is then
// empty): the error RoundTrip would return, or why it never goes
// there (plain http:// over HTTP/2 and HTTP/3, proxies over HTTP/3).
Err error
}
Lines is a request's head over one protocol, as it would go on the wire.
type MessageType ¶
type MessageType int
MessageType is a WebSocket message's type: what a page's send() makes of a string (text) or an ArrayBuffer or Blob (binary).
const ( TextMessage MessageType = 1 BinaryMessage MessageType = 2 )
Message types, as their opcodes (RFC 6455, section 5.2).
type Override ¶
type Override struct {
// Name is lowercase.
Name string
// Mimicry is the value the profile or mimicry would have sent (for
// Cookie, the jar's line).
Mimicry string
// Caller are the values sent instead; none when the caller suppressed
// the header (a key with no values).
Caller []string
}
Override is a header the caller set in place of mimicry's value.
type Pin ¶
type Pin struct {
// Host is a host name ("www.example.com") or IP address, in any case;
// no scheme, port or wildcard.
Host string
// IncludeSubdomains extends the pin to every host under Host. A Pin
// for the request's own host wins over one for a parent, and the
// nearest parent over others.
IncludeSubdomains bool
// SPKI are the accepted keys, any of which matches, each one of:
// - "sha256/<base64>": the SHA-256 of a certificate's
// SubjectPublicKeyInfo, base64 (HPKP's form, and CertPin.SPKI);
// - that hash in hex (CertPin.SPKIHex);
// - a certificate's SHA-256 fingerprint in hex, colons optional
// (CertPin.Fingerprint, as browsers show it).
// Hex values match either form. At least one is required.
SPKI []string
}
Pin pins a host (and, with IncludeSubdomains, its subdomains) to public keys: the verified chain (leaf, intermediate or trusted root) must contain a certificate matching one of SPKI. Pinning the intermediate is usual: it outlives leaf renewals. FetchPins lists a site's chain.
type PinError ¶
type PinError struct {
// Host is the request's host.
Host string
// Presented are the chain's keys as "sha256/<base64>" pins, leaf
// first.
Presented []string
}
PinError is a connection to a pinned host whose verified chain matched none of its pins. Nothing was sent on it.
type Place ¶
type Place struct {
// Header is the header to move.
Header string
// After puts Header directly after this header.
After string
// Before puts Header directly before this header.
Before string
}
Place moves one header directly after or before another, after the profile has ordered the request's headers: a deliberate deviation for a server that expects a header elsewhere. Set exactly one of After and Before; names match in any case.
Placements apply in order to the lines the connection writes: over HTTP/1.1 including Host, Connection and framing headers (not Proxy-Authorization); over HTTP/2 and HTTP/3 only the fields after the pseudo-headers. A header set more than once moves as one run. If the request does not send both the header and its anchor, RoundTrip returns an error wrapping ErrPlacement without sending it.
type Plan ¶
type Plan struct {
// Method and URL are the request's as sent: a redirect's hop as the
// browser sends it (a PUT answered 301 stays a PUT).
Method string
URL *url.URL
// Kind is the request's kind: Navigate by default; Preflight in
// Plan.Preflight's plan.
Kind Kind
// Variant is the JSON path of the profile lists the request takes:
// "headers", "variants[2]", "kinds.fetch.headers" or
// "kinds.fetch.variants[4]"; empty for an Exact request.
Variant string
// Condition is what picks the variant, in profile.Variant's JSON
// names: "method PUT", "site cross-site", then each flag that holds
// ("corsChecked", "redirected", ...). Compare it with Variant to see
// whether an exact variant was found. Empty for an Exact request.
Condition []string
// Protocol is the protocol the request would use now, as a response's
// Proto ("HTTP/2.0", "HTTP/1.1", "HTTP/3.0"). Empty when only
// connecting decides it (ALPN, a QUIC attempt, coalescing by DNS).
Protocol string
// HTTP2, HTTP1 and HTTP3 are the request's lines over each protocol,
// whichever it goes over. HTTP3 is nil when the Transport speaks no
// HTTP/3 (the profile has no http3 section, or Config.DisableHTTP3).
HTTP2 Lines
HTTP1 Lines
HTTP3 *Lines
// Preflight is the CORS preflight RoundTrip would send first, planned
// as a request of its own; nil when the request needs none or a
// cached answer allows it. Whether its answer allows the request
// only the server can say.
Preflight *Plan
// Overrides are the headers the request or Config.Header set in
// place of a value the profile or mimicry would have sent: a default,
// a computed header (Referer, Origin, sec-fetch-*), or the jar's
// cookies. A Connection: close (or req.Close) is one over HTTP/1.1
// only: HTTP/2 and HTTP/3 send no Connection.
Overrides []Override
// Dropped are the headers the profile would have sent that the
// request's HeaderOrderKey does not name, so are not sent; lowercase.
Dropped []string
// contains filtered or unexported fields
}
Plan is what RoundTrip would send for a request, worked out without sending it (Transport.Plan): the profile's list it takes, its header lines over each protocol, the protocol it would go over, its CORS preflight, and the headers the caller set in place of the browser's.
type ProxyError ¶
type ProxyError struct {
// Proxy is the proxy's URL with its password removed (the username
// stays).
Proxy *url.URL
// StatusCode is the proxy's answer to CONNECT (or to the plain-HTTP
// request), or 0 for a SOCKS5 proxy or when it gave none.
StatusCode int
// Header is that answer's header, or nil.
Header http.Header
// Err is the cause.
Err error
}
ProxyError reports that a request never reached the server because of its proxy: unreachable, a non-2xx CONNECT answer, a failed SOCKS5 handshake or login, or the deadline passing on the way. For a plain-HTTP request sent to an HTTP proxy whole, only a final 407 counts; other answers are the response. Failures inside an open tunnel are the server's, not a ProxyError.
A proxy-rotation loop tests for it with errors.As (see docs/concepts/proxies.md). It wraps the cause, so errors.Is(err, context.DeadlineExceeded) works.
func (*ProxyError) Error ¶
func (e *ProxyError) Error() string
func (*ProxyError) Unwrap ¶
func (e *ProxyError) Unwrap() error
type Request ¶
type Request struct {
// Kind is the kind of request the page makes (Navigate, Fetch, Image,
// ...): it picks the profile's headers, their order and values.
Kind Kind
// From is the page making the request: it decides sec-fetch-site,
// Origin and Referer. Nil means none for a navigation (a typed URL),
// and for other kinds the transport's last navigation, else the
// request's own origin.
From *url.URL
// Priority is the request's fetchpriority. RoundTrip fails if the
// profile never measured PriorityHigh or PriorityLow for the kind.
Priority Priority
// CrossOrigin is an element kind's crossorigin attribute.
CrossOrigin CrossOrigin
// Credentials is a Fetch or XHR request's credentials mode.
Credentials Credentials
// NoCORS is fetch()'s mode: "no-cors".
NoCORS bool
// Stylesheet is the stylesheet loading a Font or Image. Browsers that
// refer such requests to it (profile.Context.StylesheetReferrer) send
// its URL as Referer; sec-fetch-site and Origin stay From's.
Stylesheet *url.URL
// IgnoreCORS sends a request whose CORS preflight answer forbids it,
// which a browser never does; otherwise RoundTrip returns a
// *CORSError. The preflight is still sent.
IgnoreCORS bool
// HeaderPlacement moves this request's headers, on every redirect hop
// but not its preflight, after Config.HeaderPlacement. An invalid Place,
// or any Place on a request with its own order (Exact, HeaderOrderKey),
// is an error wrapping ErrPlacement.
HeaderPlacement []Place
}
Request describes how a page makes a request, for With. The zero value is a typed-URL navigation.
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport is an http.RoundTripper that sends requests as the profile's browser. It is safe for concurrent use.
A Transport is one browsing entity, like a browser tab: non-navigation requests come from its last navigation unless they set Request.From. Parallel tasks should each use their own Transport, or set Request.From.
Call CloseIdleConnections when you discard a Transport, or the client built on it. Otherwise idle connections close after Config.IdleConnTimeout, and those of an unreachable Transport close when it is garbage collected. A proxy no longer used loses its idle connections early; see Config.MaxIdleProxies.
func NewTransport ¶
NewTransport builds a Transport from cfg. It shares the profile and copies nothing of it, about a microsecond; but a Transport is one browsing entity, with its own connections, sessions and cookies: build one per identity or proxy and reuse it, rather than one per request.
func (*Transport) CloseIdleConnections ¶
func (t *Transport) CloseIdleConnections()
CloseIdleConnections closes connections with no requests in flight.
func (*Transport) Cookies ¶
Cookies returns the transport's cookie jar: Config.Cookies, or the one NewClient made; nil when it has none.
func (*Transport) DialWebSocket ¶
func (t *Transport) DialWebSocket(ctx context.Context, rawURL string, opts WebSocketOptions) (*WebSocket, *http.Response, error)
DialWebSocket opens a WebSocket to rawURL (ws:// or wss://) as the profile's browser opens one from opts.From, with the profile's websocket kind for the handshake. A wss:// socket uses an extended CONNECT stream (RFC 8441) on an existing HTTP/2 connection that allows it, else its own HTTP/1.1 connection; ws:// always gets its own connection, and is refused from an https:// page (mixed content). Through Config.Proxy it follows the profile's proxy.websocket; proxy failures are *ProxyError.
The server's response is returned too: its headers on success, or its status and the start of its body on a failed handshake. Anything the profile never measured (no websocket section, an unmeasured proxy path, subprotocols its list cannot place) returns ErrNotMeasured. See docs/concepts/websockets.md.
Example ¶
A WebSocket from the page, opened as the browser opens one: its handshake, cookies and frames.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/live" {
fmt.Println("server: websocket from", r.Header.Get("Origin"), "cookie:", r.Header.Get("Cookie"))
echoWebSocket(w, r)
return
}
w.Header().Set("Set-Cookie", "session=s1; Path=/; Secure")
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/queue", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
_ = resp.Body.Close()
// The socket goes through the client's Transport, from its last page.
tr, ok := client.Transport.(*mimicry.Transport)
if !ok {
panic("NewClient's Transport is a *mimicry.Transport")
}
ws, _, err := tr.DialWebSocket(ctx, "wss://www.shop.test/live", mimicry.WebSocketOptions{})
if err != nil {
panic(err)
}
if err := ws.WriteMessage(ctx, mimicry.TextMessage, []byte("position?")); err != nil {
panic(err)
}
_, msg, err := ws.ReadMessage(ctx)
if err != nil {
panic(err)
}
fmt.Println(string(msg))
if err := ws.Close(1000, ""); err != nil {
panic(err)
}
Output: server: websocket from https://www.shop.test cookie: session=s1 echo: position?
func (*Transport) Plan ¶
Plan returns what RoundTrip would send for req now, without sending anything, opening connections, resolving names, or changing any Transport state. It takes RoundTrip's own path, so the lines match what RoundTrip writes as long as nothing changes in between. Pass req as RoundTrip gets it (As, With or Exact; a redirect hop with its Response); its body is never read.
Plan returns the errors RoundTrip would return before sending (ErrNotMeasured, ErrPlacement, ...); per-protocol errors go in Lines. It never returns a *CORSError, which needs the server's answer.
Example ¶
Debugging a fetch() ported from tls-client: Plan shows what a request would send, line by line, over the protocol it would take, without sending it, and catches the header literals the port copied over the browser's own values. (Plan.String prints all of it for a log.)
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("server:", r.Method, r.URL.Path, "sec-fetch-site:", r.Header.Get("Sec-Fetch-Site"))
if r.URL.Path == "/p/42" {
w.Header().Set("Set-Cookie", "session=s1; Path=/; Secure; HttpOnly")
}
})
defer shop.Close()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.Chrome155MacOS(),
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
tr, ok := client.Transport.(*mimicry.Transport)
if !ok {
panic("NewClient's Transport is a *mimicry.Transport")
}
ctx := context.Background()
page, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/p/42", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(page)
if err != nil {
panic(err)
}
_ = resp.Body.Close()
// The stock API call as ported, with a header literal of the old
// code's left in.
api, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.shop.test/api/stock/42", nil)
if err != nil {
panic(err)
}
api.Header.Set("Sec-Fetch-Site", "none")
plan, err := tr.Plan(mimicry.As(api, mimicry.Fetch))
if err != nil {
panic(err)
}
fmt.Println("variant:", plan.Variant, plan.Condition)
for _, o := range plan.Overrides {
fmt.Printf("override: %s: %q replaced by %q\n", o.Name, o.Mimicry, o.Caller)
}
// Drop it, look again, and send what was planned.
api.Header.Del("Sec-Fetch-Site")
plan, err = tr.Plan(mimicry.As(api, mimicry.Fetch))
if err != nil {
panic(err)
}
fmt.Println("overrides:", len(plan.Overrides), "protocol:", plan.Protocol)
for _, h := range plan.HTTP2.Headers {
fmt.Printf(" %s: %s\n", h.Name, h.Value)
}
resp, err = client.Do(mimicry.As(api, mimicry.Fetch))
if err != nil {
panic(err)
}
_ = resp.Body.Close()
Output: server: GET /p/42 sec-fetch-site: none variant: kinds.fetch.headers [method GET site same-origin] override: sec-fetch-site: "same-origin" replaced by ["none"] overrides: 0 protocol: HTTP/2.0 :method: GET :authority: www.shop.test :scheme: https :path: /api/stock/42 sec-ch-ua-platform: "macOS" user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 sec-ch-ua: "Google Chrome";v="155", "Chromium";v="155", "Not(A:Brand";v="24" sec-ch-ua-mobile: ?0 accept: */* sec-fetch-site: same-origin sec-fetch-mode: cors sec-fetch-dest: empty referer: https://www.shop.test/p/42 accept-encoding: gzip, deflate, br, zstd accept-language: en-US,en;q=0.9 cookie: session=s1 priority: u=1, i server: GET /api/stock/42 sec-fetch-site: same-origin
func (*Transport) RoundTrip ¶
RoundTrip implements http.RoundTripper. It sends req as its kind (As, With; a navigation by default) from its page, with Config.Header added. A gzip, deflate, br or zstd body is decoded and Content-Encoding and Content-Length removed, unless Config.DisableDecompression. Response.TLS is the connection's state.
Redirects go out as the browser sends them: 301/302 keep a PUT, DELETE or PATCH method and body, and chains stop after the browser's limit. A cross-origin CORS request whose redirect does not allow its origin returns a *CORSError instead, unless Request.IgnoreCORS.
type WebSocket ¶
type WebSocket struct {
// contains filtered or unexported fields
}
WebSocket is an open WebSocket that frames, compresses, answers pings and closes as the profile's browser does. ReadMessage, WriteMessage and Close are safe for concurrent use.
func (*WebSocket) Close ¶
Close closes the socket with code (1000, or 3000 to 4999) and reason (at most 123 bytes). It returns once the close handshake is done and the connection or stream has ended as the browser ends it:
- Chrome closes HTTP/1.1 2 s later, and over HTTP/2 waits for the server's END_STREAM (reset after 10 s);
- Safari closes the connection or resets the stream at once;
- Firefox leaves it to the server, ending it 10 s later, after Close returns.
A server that never answers the close is cut off after 10 s. If the server closed first, Close only waits for that end.
func (*WebSocket) Extensions ¶
Extensions is the server's Sec-WebSocket-Extensions answer, its parameters included, or "". (A page's extensions attribute is this in Chrome and Safari; Firefox's names the extension alone.)
func (*WebSocket) ReadMessage ¶
ReadMessage returns the next message the server sent. Once the socket has closed it returns a *CloseError after a close handshake, or the error that ended it.
func (*WebSocket) WriteMessage ¶
WriteMessage sends data as one unfragmented message of type typ, compressed as the profile's browser compresses it; text must be UTF-8. With permessage-deflate, a message the browser was never seen compressing (any, for Firefox) returns ErrNotMeasured and is not sent.
type WebSocketOptions ¶
type WebSocketOptions struct {
// From is the page opening the socket: it decides Origin,
// sec-fetch-site and which cookies go. Nil is the transport's last
// navigation, or else the socket's own origin (as for other request
// kinds).
From *url.URL
// Protocols are the subprotocols asked for (Sec-WebSocket-Protocol),
// in order; none sends no header.
Protocols []string
// Header holds extra headers for this handshake only, added after the
// profile's and Config.Header (which apply to every request, this
// handshake included). After the handshake, a WebSocket carries frames,
// not headers. A key with no values suppresses a profile default.
Header http.Header
}
WebSocketOptions are what a page passes to new WebSocket(), and its own headers.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pins
command
Command pins prints the verified certificate chain a site presents to a profile's browser, with each certificate's pins, and marks the one to pin (mimicry.FetchPins; no request is sent):
|
Command pins prints the verified certificate chain a site presents to a profile's browser, with each certificate's pins, and marks the one to pin (mimicry.FetchPins; no request is sent): |
|
profilegen
command
Command profilegen generates profiles/profiles.gen.go from profiles/data/*.json: accessors per profile and per browser's newest version on each platform (ChromeMacOS, ChromeWindows; decision 0047), and the name lists.
|
Command profilegen generates profiles/profiles.gen.go from profiles/data/*.json: accessors per profile and per browser's newest version on each platform (ChromeMacOS, ChromeWindows; decision 0047), and the name lists. |
|
Package cookies is a cookie jar that keeps and sends cookies as a given browser does: SameSite, third-party and partitioned cookies, redirects, order, and byte-for-byte values, by the rules in a profile's cookies section (profile.Cookies) on top of RFC 6265bis.
|
Package cookies is a cookie jar that keeps and sends cookies as a given browser does: SameSite, third-party and partitioned cookies, redirects, order, and byte-for-byte values, by the rules in a profile's cookies section (profile.Cookies) on top of RFC 6265bis. |
|
internal
|
|
|
altsvc
Package altsvc keeps origins' HTTP/3 alternatives, learnt from Alt-Svc response headers (RFC 7838): one engine's alone, or shared by every engine given the same Cache, as a browser's tabs share one, and saved and loaded as JSON, as browsers keep it across restarts.
|
Package altsvc keeps origins' HTTP/3 alternatives, learnt from Alt-Svc response headers (RFC 7838): one engine's alone, or shared by every engine given the same Cache, as a browser's tabs share one, and saved and loaded as JSON, as browsers keep it across restarts. |
|
checked
Package checked hands the root package the Spec inside a profile.Profile, which package profile keeps unexported so that no caller can change a profile clients were built from.
|
Package checked hands the root package the Spec inside a profile.Profile, which package profile keeps unexported so that no caller can change a profile clients were built from. |
|
cors
Package cors is the Fetch standard's CORS protocol as browsers apply it: when a cross-origin fetch() or XHR needs a preflight, whether a preflight's answer or a redirect allows the request, and the preflight cache.
|
Package cors is the Fetch standard's CORS protocol as browsers apply it: when a cross-origin fetch() or XHR needs a preflight, whether a preflight's answer or a redirect allows the request, and the preflight cache. |
|
dial
Package dial is the single path from an address to a connected socket, directly or through an HTTP or SOCKS5 proxy, and to a UDP socket for QUIC, directly or through a SOCKS5 UDP association.
|
Package dial is the single path from an address to a connected socket, directly or through an HTTP or SOCKS5 proxy, and to a UDP socket for QUIC, directly or through a SOCKS5 UDP association. |
|
engine/native
Package native is the pure-Go engine: the one place that assembles the request path (pool, dial, handshake, then h1 or h2 by ALPN, or h3 over QUIC), routing each request to its pool key and retrying on another connection a request nothing of which was sent.
|
Package native is the pure-Go engine: the one place that assembles the request path (pool, dial, handshake, then h1 or h2 by ALPN, or h3 over QUIC), routing each request to its pool key and retrying on another connection a request nothing of which was sent. |
|
fingerprint
Package fingerprint compiles a profile once into an immutable plan, then fills in per-connection randomness (GREASE, extension shuffle, key shares) to produce each connection's ClientHello.
|
Package fingerprint compiles a profile once into an immutable plan, then fills in per-connection randomness (GREASE, extension shuffle, key shares) to produce each connection's ClientHello. |
|
h1
Package h1 speaks HTTP/1.1 over an established connection, writing each request head as the profile's browser does.
|
Package h1 speaks HTTP/1.1 over an established connection, writing each request head as the profile's browser does. |
|
h2
Package h2 is mimicry's HTTP/2 client.
|
Package h2 is mimicry's HTTP/2 client. |
|
h3
Package h3 is mimicry's HTTP/3 client (RFC 9114) on internal/quic, with field sections encoded by internal/qpack.
|
Package h3 is mimicry's HTTP/3 client (RFC 9114) on internal/quic, with field sections encoded by internal/qpack. |
|
handshake
Package handshake performs the TLS handshake and ALPN from a fingerprint plan and keeps session tickets for resumption.
|
Package handshake performs the TLS handshake and ALPN from a fingerprint plan and keeps session tickets for resumption. |
|
headerorder
Package headerorder merges a request's headers with a profile's defaults and puts them in the profile's order.
|
Package headerorder merges a request's headers with a profile's defaults and puts them in the profile's order. |
|
hpack
Package hpack is an HPACK encoder whose choices follow a browser's (profile.HPACK): which fields enter the dynamic table, which entry a literal's name refers to, and when strings are Huffman-coded.
|
Package hpack is an HPACK encoder whose choices follow a browser's (profile.HPACK): which fields enter the dynamic table, which entry a literal's name refers to, and when strings are Huffman-coded. |
|
pins
Package pins checks connections against the root package's Config.Pins (decision 0032): it parses the pins, finds the one covering a host, matches it against a verified chain, and lists a chain's pins for FetchPins.
|
Package pins checks connections against the root package's Config.Pins (decision 0032): it parses the pins, finds the one covering a host, matches it against a verified chain, and lists a chain's pins for FetchPins. |
|
platform
Package platform says which profile platforms share a browser's network stack, so that a profile on one may inherit captures from the other's (decision 0051).
|
Package platform says which profile platforms share a browser's network stack, so that a profile on one may inherit captures from the other's (decision 0051). |
|
pool
Package pool keeps connections by key (scheme, host and port, partition, proxy): one shared HTTP/2 or HTTP/3 connection, idle HTTP/1.1 ones, the dial in progress and the requests waiting for a slot under Config.MaxExclusive.
|
Package pool keeps connections by key (scheme, host and port, partition, proxy): one shared HTTP/2 or HTTP/3 connection, idle HTTP/1.1 ones, the dial in progress and the requests waiting for a slot under Config.MaxExclusive. |
|
proxy
Package proxy connects through SOCKS5 and HTTP CONNECT proxies, bounded by the caller's context, and carries UDP datagrams through SOCKS5 UDP associations (Association).
|
Package proxy connects through SOCKS5 and HTTP CONNECT proxies, bounded by the caller's context, and carries UDP datagrams through SOCKS5 UDP associations (Association). |
|
qpack
Package qpack is a QPACK (RFC 9204) encoder whose dynamic table use and Huffman rule follow a browser's, and a decoder for the peer's field sections and encoder stream.
|
Package qpack is a QPACK (RFC 9204) encoder whose dynamic table use and Huffman rule follow a browser's, and a decoder for the peer's field sections and encoder stream. |
|
quic
Package quic implements the QUIC protocol.
|
Package quic implements the QUIC protocol. |
|
quic/qlog
Package qlog serializes qlog events.
|
Package qlog serializes qlog events. |
|
quic/quicwire
Package quicwire encodes and decode QUIC/HTTP3 wire encoding types, particularly variable-length integers.
|
Package quicwire encodes and decode QUIC/HTTP3 wire encoding types, particularly variable-length integers. |
|
quic/testcert
Package testcert contains a test-only localhost certificate.
|
Package testcert contains a test-only localhost certificate. |
|
site
Package site computes what browsers call a site: a scheme and a registrable domain (public suffix list), the unit of SameSite cookies, sec-fetch-site and cookie partitions.
|
Package site computes what browsers call a site: a scheme and a registrable domain (public suffix list), the unit of SameSite cookies, sec-fetch-site and cookie partitions. |
|
testutil
Package testutil holds test certificates and helpers shared by mimicry's tests.
|
Package testutil holds test certificates and helpers shared by mimicry's tests. |
|
ws
Package ws is the WebSocket protocol (RFC 6455) after the handshake, as the profile's browser speaks it: framing, permessage-deflate through internal/zdeflate, HTTP/2 DATA packing, pings and the close handshake.
|
Package ws is the WebSocket protocol (RFC 6455) after the handshake, as the profile's browser speaks it: framing, permessage-deflate through internal/zdeflate, HTTP/2 DATA packing, pings and the close handshake. |
|
zdeflate
Package zdeflate is permessage-deflate (RFC 7692) as the browsers write it.
|
Package zdeflate is permessage-deflate (RFC 7692) as the browsers write it. |
|
Package profile defines a browser profile.
|
Package profile defines a browser profile. |
|
Package profiles holds the built-in browser profiles, one embedded JSON file per browser version and platform, taken from captures of the real browser.
|
Package profiles holds the built-in browser profiles, one embedded JSON file per browser version and platform, taken from captures of the real browser. |