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 and the iPhone, Edge on macOS and Windows, Brave on macOS, Windows and Linux, Chrome and Firefox on Windows and Linux (profiles.ChromeLinux, profiles.EdgeWindows, profiles.BraveMacOS, ...). 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 Bytes
- type CORSError
- type CertPin
- type CertRole
- type ClientHintStore
- type CloseError
- type Config
- type Credentials
- type CrossOrigin
- type Header
- type HintDelegation
- type Kind
- type Lines
- type MemoryClientHintStore
- type MessageType
- type Override
- type Peer
- type Pin
- type PinError
- type Place
- type Plan
- type Priority
- type ProxyError
- type Request
- type TicketCache
- type Traffic
- type TrafficMeter
- type TrafficOptions
- 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 ErrBlocked = errors.New("mimicry: the profile's browser blocks this request")
ErrBlocked reports a request the profile's browser blocks and never sends: a cross-site Beacon where its profile says so (Brave's Shields, profile.Context.BlocksCrossSiteBeacons). RoundTrip returns it wrapped, with nothing sent. Test for it with errors.Is.
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>
Example (RawTarget) ¶
Send a request target exactly as written, as a security test may: a browser resolves "/../" and encodes "'", so mimicry does too, unless the URL's Opaque holds the target (as with net/http). Its path and query go out untouched; the host still picks the connection.
shop := startShop(func(_ http.ResponseWriter, r *http.Request) {
fmt.Println("server:", r.RequestURI)
})
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)
}
for _, raw := range []bool{false, true} {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://www.shop.test/static/../admin?q='x", nil)
if err != nil {
panic(err)
}
if raw {
req.URL.Opaque = "/static/../admin"
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
_ = resp.Body.Close()
}
Output: server: /admin?q=%27x server: /static/../admin?q='x
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 and connections stay each Transport's, and session tickets too unless Config.Tickets shares them (TicketCache). 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 Bytes ¶ added in v0.7.0
type Bytes struct {
Sent, Received int64
}
Bytes is what was sent and received.
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 ClientHintStore ¶ added in v0.4.0
type ClientHintStore interface {
// ClientHints returns the hints origin ("https://example.com", with
// its port unless the scheme's default) opted in to, lowercase; nil
// when none.
ClientHints(origin string) []string
// SetClientHints replaces origin's hints; none forgets origin.
SetClientHints(origin string, hints []string)
}
ClientHintStore keeps which client hints each origin opted in to: the Accept-CH of its last navigation response, as a browser keeps it until the site replaces or clears it. Like the cookie jar, it belongs to one identity: save it with the jar to resume that identity later. Implementations must be safe for concurrent use.
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.
// HTTP/3's UDP sockets never go through it: bind them with LocalAddrs.
// With DialContext set and no Resolver with a Dial of its own, no DNS
// HTTPS record is looked up, and every server gets the GREASE ECH
// extension, as through a proxy: the lookup would bypass it. For the
// same reason a socks4 proxy's target host name is then refused (use
// socks4a, or such a Resolver).
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// LocalAddrs are the local addresses mimicry's connections leave from,
// at most one IPv4 and one IPv6: TCP (unless DialContext opens it),
// HTTP/3's UDP sockets and SOCKS5 UDP relays, so a multi-address host
// sends one identity's TCP and QUIC from the same address, as a
// browser does. A server only reachable over a family with none is an
// error. With both, IPv6 and IPv4 race as without LocalAddrs (Happy
// Eyeballs), each from its own address. Nil, the default, leaves the
// choice to the system. NewTransport rejects two of one
// family, or an address that is not a host's (unspecified, multicast).
LocalAddrs []netip.Addr
// 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.
// A profile that sends real ECH (tls.realEch) also looks up the DNS
// HTTPS record of each host it connects to directly: through
// Resolver's Dial when it has one (to the system's nameserver
// address), otherwise over UDP and TCP to the system's nameservers
// (/etc/resolv.conf; on Windows, the adapters' DNS servers); with
// DialContext set, only through Resolver's Dial.
Resolver *net.Resolver
// Proxy picks the proxy for each request, as in http.Transport. Nil,
// the default, connects directly. Supported schemes are "http",
// "https" (TLS to the proxy with the profile's hello, CONNECT over
// the HTTP/2 or HTTP/1.1 it picks; https:// requests only, and
// profiles without proxy.https, Safari's among them, refuse it),
// "socks5", "socks5h", "socks4" (the host looked up here, as the
// browser does, with Resolver, which needs a Dial of its own when
// DialContext is set; not for Safari profiles, whose browser never
// does) and "socks4a" (the host name sent; not for Chrome, Edge or
// Brave profiles); profiles without proxy.socks4 refuse socks4 and
// socks4a. A failed proxy returns a *ProxyError; a target SOCKS4
// cannot carry, or a socks4 lookup that fails or would bypass
// DialContext, does not (no proxy was asked). RootCAs, Pins,
// VerifyConnection and KeyLogWriter apply to an https proxy's TLS too,
// for its host; GetClientCertificate does not. 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
// ClientHintStore keeps the client hints each origin opted in to
// (Accept-CH), which later requests then send as the browser does, a
// Critical-CH restart included. Nil, the default, keeps one per
// Transport. Set it, as Cookies, to share or save an identity's
// (NewClientHintStore). Profiles of browsers that ignore the opt-in
// (Firefox, Safari) never use it. See docs/concepts/client-hints.md.
ClientHintStore ClientHintStore
// ClientHints is the machine the client hints describe once a site
// opts in: its system version, CPU, screen and preferences. Nil, the
// default, is the profile's captured machine; profiles.Machines and
// profiles.RandomMachine give the other captured ones. Keep one per
// identity: a machine that changes is a tell. NewTransport rejects an
// invalid one with a *profile.ValidationError; profiles that send no
// opted-in hints ignore it.
ClientHints *profile.Machine
// 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 (LocalAddrs binds it). 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
// Tickets keeps TLS session tickets, shared by every Transport given
// the same cache, like a browser's tabs. Save and load it to carry an
// identity's sessions to another process, so its first connections
// resume; see TicketCache for what that models. A cache belongs to one
// browser: NewTransport refuses a profile of another. Proxies swept
// as MaxIdleProxies says lose their tickets from it too. Nil, the
// default, keeps one per Transport, lost with it.
Tickets *TicketCache
// Traffic, if set, counts the bytes this Transport's sockets send and
// receive, by protocol (and by host with TrafficOptions.ByHost),
// traffic mimicry makes beyond the caller's requests included. Several
// Transports may share one meter. Nil, the default, counts nothing.
// See docs/concepts/traffic.md.
Traffic *TrafficMeter
// 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
// ConnectUDPProxy lets requests through an http:// or https:// proxy
// use HTTP/3, carried by CONNECT-UDP (RFC 9298, MASQUE). It is given
// such a request's proxy and returns the CONNECT-UDP proxy for it: an
// https:// URL (port 443 by default) reached over HTTP/3, its
// credentials (as user:password) given as the proxy's are. Return the
// provider's MASQUE endpoint (https://user:pass@masque.oxylabs.io:50000
// beside http://user:pass@pr.oxylabs.io:7777), the proxy itself where it
// also serves HTTP/3, or nil to keep that proxy's requests on TCP; it
// must not change its argument. Browsers never use HTTP/3 through a
// proxy, so by default (nil) those requests stay on TCP. A CONNECT-UDP
// proxy that refuses it keeps them on TCP, as do Safari profiles (their
// HTTP/3 has no datagrams). See docs/concepts/proxies.md.
ConnectUDPProxy func(proxy *url.URL) (*url.URL, error)
// 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. The
// state's ServerName is the request's host, also when the profile
// sends no SNI for it (tls.trailingDotSni omit). An error fails the
// request before anything is sent. Default: none.
VerifyConnection func(tls.ConnectionState) error
// GetClientCertificate, when set, answers a server that asks for a
// client certificate (mutual TLS) on a connection to host, as
// crypto/tls's GetClientCertificate does: a nil certificate, or one
// with no chain, sends none. req.Context() is nil. Browsers send their
// certificate alone, without its CA; mimicry sends the chain given.
// It is signed as the profile's browser signs (tls.clientAuth), and a
// session it was sent in is resumed only where the browser resumes
// one. Where the browser drops the connection on which a host and port
// first asks and sends the request again on a new one (Chrome, Edge),
// so does the Transport, once per host and port, and
// GetClientCertificate is called for the new one. A connection that
// carries a certificate, sent or resumed, takes no other host's
// requests (no HTTP/2 coalescing). A profile without tls.clientAuth,
// a key type it did not measure, or a server whose request does not
// allow the browser's signature scheme makes a certificate
// ErrNotMeasured. A server asking over HTTP/3 makes that request, and
// the origin's later ones, go over TCP, where the certificate is sent
// as measured; it is not asked for over HTTP/3. Default: none, and a
// server asking gets an empty certificate list, as from a browser
// with none. See docs/concepts/client-certificates.md.
GetClientCertificate func(host string, req *tls.CertificateRequestInfo) (*tls.Certificate, error)
// KeyLogWriter, when set, receives the TLS secrets of every connection
// (TCP and QUIC, WebSockets included) in NSS key log format, so a
// packet capture can be decrypted in Wireshark, as Chrome and Firefox
// write them to SSLKEYLOGFILE. Nothing on the wire changes. Anyone
// with the log can read the traffic: use it for debugging only.
// mimicry never reads SSLKEYLOGFILE itself. Default: none.
KeyLogWriter io.Writer
// contains filtered or unexported fields
}
Config configures a Transport.
Example (ClientHints) ¶
Chrome profiles answer a site's client hints opt-in as Chrome does: a navigation's Accept-CH is kept for its origin (Config.ClientHintStore), and later requests send the hints it asked for, with one machine's values (Config.ClientHints; profiles.Machines lists the captured ones). A Critical-CH hint the navigation lacked makes the client send it again. See docs/concepts/client-hints.md.
shop := startShop(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("server: %s arch=%s platform-version=%s model=%s\n", r.URL.Path,
r.Header.Get("Sec-CH-UA-Arch"), r.Header.Get("Sec-CH-UA-Platform-Version"), r.Header.Get("Sec-CH-UA-Model"))
switch r.URL.Path {
case "/":
w.Header().Set("Accept-CH", "Sec-CH-UA-Arch, Sec-CH-UA-Platform-Version")
case "/checkout":
// The page needs Model to render: Chrome asks again at once.
w.Header().Set("Accept-CH", "Sec-CH-UA-Arch, Sec-CH-UA-Platform-Version, Sec-CH-UA-Model")
w.Header().Set("Critical-CH", "Sec-CH-UA-Model")
}
})
defer shop.Close()
// One of the captured Windows machines, picked once for this identity.
machine, ok := profiles.RandomMachine("windows")
if !ok {
panic("no captured Windows machine")
}
store := mimicry.NewClientHintStore()
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeWindows(),
ClientHints: &machine,
ClientHintStore: store,
// 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(path string, r mimicry.Request) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://www.shop.test"+path, nil)
if err != nil {
panic(err)
}
resp, err := client.Do(mimicry.With(req, r))
if err != nil {
panic(err)
}
_ = resp.Body.Close()
}
get("/", mimicry.Request{})
// The page's fetch() carries what its origin opted in to.
get("/api/cart", mimicry.Request{
Kind: mimicry.Fetch,
})
get("/checkout", mimicry.Request{})
// Saved beside the cookie jar, to resume this identity later
// (ReadJSON).
var saved bytes.Buffer
if err := store.WriteJSON(&saved); err != nil {
panic(err)
}
fmt.Print("saved: ", saved.String())
Output: server: / arch= platform-version= model= server: /api/cart arch="x86" platform-version="10.0.0" model= server: /checkout arch="x86" platform-version="10.0.0" model= server: /checkout arch="x86" platform-version="10.0.0" model="" saved: {"https://www.shop.test":["sec-ch-ua-arch","sec-ch-ua-platform-version","sec-ch-ua-model"]}
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, or ConnectUDPProxy a CONNECT-UDP proxy an HTTP proxy's.)
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 HintDelegation ¶ added in v0.4.0
type HintDelegation int
HintDelegation is whether a page shares the client hints its origin opted in to (Accept-CH) with a request to another origin. A browser decides it from the page's Permissions-Policy and Delegate-CH meta tag, which mimicry does not read: the caller says (decision 0055).
const ( // HintsDefault: a request to the page's own origin sends every hint // that origin opted in to; one to another origin (a subdomain // included) only the low-entropy sec-ch-ua, sec-ch-ua-mobile and // sec-ch-ua-platform. HintsDefault HintDelegation = iota // HintsDelegated: the page delegates its hints to the request's origin // (Permissions-Policy: ch-ua-arch=(self "https://cdn.example"), or a // <meta http-equiv="Delegate-CH">), which then gets them all. HintsDelegated // HintsWithheld: the page's Permissions-Policy names its own allowlist // for the hints (ch-ua=(self ...)) and leaves the request's origin out: // it gets no client hints at all, not even sec-ch-ua. HintsWithheld )
Delegations. Whatever the page decides, a request to another site's frame, image or fetch() never gets hints the page's origin did not opt in to.
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 MemoryClientHintStore ¶ added in v0.4.0
type MemoryClientHintStore struct {
// contains filtered or unexported fields
}
MemoryClientHintStore is the ClientHintStore NewClientHintStore returns: in memory, safe for concurrent use, saved and loaded as JSON with WriteJSON and ReadJSON. Its zero value is an empty store.
func NewClientHintStore ¶ added in v0.4.0
func NewClientHintStore() *MemoryClientHintStore
NewClientHintStore returns an empty MemoryClientHintStore.
func (*MemoryClientHintStore) ClientHints ¶ added in v0.4.0
func (s *MemoryClientHintStore) ClientHints(origin string) []string
ClientHints implements ClientHintStore.
func (*MemoryClientHintStore) ReadJSON ¶ added in v0.4.0
func (s *MemoryClientHintStore) ReadJSON(r io.Reader) error
ReadJSON adds the origins of a JSON object WriteJSON wrote, replacing those already held; hint names are lowercased, and an origin with none is forgotten. A malformed object fails it before anything is added.
func (*MemoryClientHintStore) SetClientHints ¶ added in v0.4.0
func (s *MemoryClientHintStore) SetClientHints(origin string, hints []string)
SetClientHints implements ClientHintStore.
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 Peer ¶ added in v0.7.0
type Peer struct {
Host, Proxy string
}
Peer is where connections went: the host they were dialed for and the proxy they went through, its scheme, host and port without credentials ("" for none). An https proxy's HTTP/2 connection, carrying tunnels to many hosts, has no Host; a DNS lookup's Host is the nameserver.
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 SOCKS 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 failed TLS handshake with an https proxy (its certificate, Pins or VerifyConnection; the cause stays wrapped), a non-2xx CONNECT answer, a failed SOCKS5 handshake or login, a SOCKS4 refusal, 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; nor is a target a SOCKS4 proxy cannot be asked for (an IPv6 address), or a socks4 lookup that fails: no proxy was asked, and another would do no better.
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
// ClientHints is whether the page shares the client hints its origin
// opted in to with this request, when it goes to another origin; the
// page's own origin always gets them. A navigation takes none: it
// sends what its own origin opted in to.
ClientHints HintDelegation
}
Request describes how a page makes a request, for With. The zero value is a typed-URL navigation.
type TicketCache ¶ added in v0.5.0
type TicketCache struct {
// contains filtered or unexported fields
}
TicketCache keeps the TLS session tickets, over TCP and QUIC, of the Transports given it in Config.Tickets, as one browser keeps them for all its tabs. Save it (WriteJSON) and load it into a new process (ReadJSON) to carry an identity's sessions over, so its first connections resume, with 0-RTT where the profile's browser uses it, instead of starting with full handshakes.
What that models depends on the browser (decision 0062). Chrome 156 and Firefox 159 keep tickets in memory only: relaunched, they start with full handshakes, so a loaded cache models one that stayed open. Safari 27 resumes its QUIC sessions, with 0-RTT, after a relaunch too (it never resumes over TCP).
A cache belongs to one browser: the first Transport given it (or the first file ReadJSON reads) decides which, and NewTransport refuses a profile of another browser, as ReadJSON refuses another browser's tickets; other versions of the same browser are allowed. A ticket links the connections that use it, as a cookie would, so share a cache only between Transports of one identity.
Tickets are kept per origin, connection partition and proxy, and used as the profile's browser uses them: a TLS 1.3 ticket once. A ticket saved and loaded into two processes would be used twice, which no browser does: load a saved cache into one process only. Through a proxy, a ticket is filed under a hash of the proxy's URL, credentials included, never the URL itself: it resumes only through the same proxy URL.
Create one with NewTicketCache; it is safe for concurrent use.
Example ¶
A TicketCache carries an identity's TLS sessions to another process: a worker that picks the identity up resumes its first connection, as the browser that stayed open would, instead of a full handshake. Save it with the cookie jar; load it into one process only.
shop := startShop(func(http.ResponseWriter, *http.Request) {})
defer shop.Close()
get := func(tickets *mimicry.TicketCache) {
client, err := mimicry.NewClient(mimicry.Config{
Profile: profiles.ChromeMacOS(),
Tickets: tickets,
// Only to reach the local stand-in shop; nil for real sites.
RootCAs: shop.RootCAs,
DialContext: shop.DialContext,
})
if err != nil {
panic(err)
}
defer client.CloseIdleConnections()
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)
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
fmt.Println(resp.Proto, "resumed:", resp.TLS.DidResume)
}
tickets := mimicry.NewTicketCache()
get(tickets)
// Saved by the first process (a file kept like a password, in a real
// program)...
var saved bytes.Buffer
if err := tickets.WriteJSON(&saved); err != nil {
panic(err)
}
// ...and loaded by the next.
restored := mimicry.NewTicketCache()
if err := restored.ReadJSON(&saved); err != nil {
panic(err)
}
get(restored)
Output: HTTP/2.0 resumed: false HTTP/2.0 resumed: true
func NewTicketCache ¶ added in v0.5.0
func NewTicketCache() *TicketCache
NewTicketCache returns an empty cache.
func (*TicketCache) Clear ¶ added in v0.5.0
func (c *TicketCache) Clear()
Clear forgets every ticket. Transports sharing the cache keep the connections they have.
func (*TicketCache) ReadJSON ¶ added in v0.5.0
func (c *TicketCache) ReadJSON(r io.Reader) error
ReadJSON adds the tickets of a JSON array WriteJSON wrote, replacing those of the same origin, partition, proxy and protocol. Expired ones are skipped; a malformed entry fails it before anything is added. A file written by another version of mimicry may not be read.
Read only files you wrote: a resumed connection is authenticated by the ticket's secret alone, not the server's certificate, so whoever can write the file can stand in for every server it names.
func (*TicketCache) WriteJSON ¶ added in v0.5.0
func (c *TicketCache) WriteJSON(w io.Writer) error
WriteJSON writes the usable tickets as a JSON array, each with its origin ("https://host:port"), partition and proxy hash (when not the default), whether it is for HTTP/3, its expiry and the session itself: what ReadJSON reads back. The session holds the secrets that resumed connections use: keep the output as you would a password.
type Traffic ¶ added in v0.7.0
type Traffic struct {
// HTTP1 is TCP connections that carried HTTP/1.1 (plain http://
// included).
HTTP1 Bytes
// HTTP2 is TCP connections that negotiated HTTP/2, an https proxy's
// HTTP/2 connection included, whatever its tunnels carry.
HTTP2 Bytes
// HTTP3 is QUIC connections, attempts that lost the race to TCP and
// connections to CONNECT-UDP and SOCKS5 proxies included.
HTTP3 Bytes
// WebSocket is the HTTP/1.1 connections WebSockets opened of their own,
// their handshakes included. A WebSocket over HTTP/2 is in HTTP2.
WebSocket Bytes
// DNS is the lookups mimicry sends itself: ECH's HTTPS records.
DNS Bytes
// Other is connections that ended before their protocol was known (a
// TCP connection that lost a race before its TLS handshake ended).
Other Bytes
// ByHost is the counts per host and proxy, with TrafficOptions.ByHost;
// nil otherwise. A connection counts under the host it was dialed
// for: an HTTP/2 connection other hosts coalesced onto counts under
// its first (Config.DisableCoalescing gives each host its own).
ByHost map[Peer]Bytes
}
Traffic is a TrafficMeter's counts, by what the connections carried.
type TrafficMeter ¶ added in v0.7.0
type TrafficMeter struct {
// contains filtered or unexported fields
}
TrafficMeter counts the bytes sent and received on the sockets of every Transport given it (Config.Traffic): TLS and QUIC overhead, handshakes, retransmitted QUIC packets, CORS preflights, redirect hops, Alt-Svc QUIC attempts and ECH's DNS lookups included. Counts are payload bytes, as the sockets read and write them: IP, TCP and UDP headers and the kernel's TCP retransmissions are not counted, nor are lookups through the system's resolver. Each socket counts on its own, so the cost is one uncontended atomic add per read or write. It is safe for concurrent use.
func NewTrafficMeter ¶ added in v0.7.0
func NewTrafficMeter(opts TrafficOptions) *TrafficMeter
NewTrafficMeter returns a meter counting from zero.
func (*TrafficMeter) Reset ¶ added in v0.7.0
func (m *TrafficMeter) Reset() Traffic
Reset returns the counts so far, as Snapshot, and starts again from zero.
func (*TrafficMeter) Snapshot ¶ added in v0.7.0
func (m *TrafficMeter) Snapshot() Traffic
Snapshot returns the counts so far: closed connections' and the open ones' bytes until now.
type TrafficOptions ¶ added in v0.7.0
type TrafficOptions struct {
// ByHost also keeps a total per Peer: one entry for each host and
// proxy reached, kept until Reset.
ByHost bool
}
TrafficOptions configures a TrafficMeter.
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.
A navigation's response records its origin's client hints opt-in (Config.ClientHintStore) where the browser does; one whose Critical-CH names a hint the navigation did not send is sent again with it, once, as Chrome restarts it, and only the second response is returned.
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
|
|
|
mimicry-core
command
Command mimicry-core serves mimicry to the Python and Node SDKs (decision 0069): each host process starts it as a child and speaks the protocol of internal/rpc/wire and proto/ over its stdin and stdout, reading stdin and writing stdout: one inherited socket as both (one end of a socketpair) or a socket each (Node's 'pipe' stdio) on Linux and macOS, pipes on Windows.
|
Command mimicry-core serves mimicry to the Python and Node SDKs (decision 0069): each host process starts it as a child and speaks the protocol of internal/rpc/wire and proto/ over its stdin and stdout, reading stdin and writing stdout: one inherited socket as both (one end of a socketpair) or a socket each (Node's 'pipe' stdio) on Linux and macOS, pipes on Windows. |
|
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, HTTPS, SOCKS5 or SOCKS4 proxy (the TLS to an https proxy and its HTTP/2 streams are the engine's, through ProxyTLS and TunnelH2), and to a UDP socket for QUIC, directly, through a SOCKS5 UDP association, or as a CONNECT-UDP stream of the engine's HTTP/3 connection to a proxy (ConnectUDP).
|
Package dial is the single path from an address to a connected socket, directly or through an HTTP, HTTPS, SOCKS5 or SOCKS4 proxy (the TLS to an https proxy and its HTTP/2 streams are the engine's, through ProxyTLS and TunnelH2), and to a UDP socket for QUIC, directly, through a SOCKS5 UDP association, or as a CONNECT-UDP stream of the engine's HTTP/3 connection to a proxy (ConnectUDP). |
|
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. |
|
httpsrr
Package httpsrr looks up the DNS HTTPS records (RFC 9460) of the origins mimicry connects to, for the ECH configurations (RFC 9849) and ALPN they carry, as Chrome and Firefox do.
|
Package httpsrr looks up the DNS HTTPS records (RFC 9460) of the origins mimicry connects to, for the ECH configurations (RFC 9849) and ALPN they carry, as Chrome and Firefox do. |
|
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 profiles share a browser's network stack, so that a profile may inherit captures from the other's: Safari on iOS from Safari on macOS (decision 0051), Chrome and Firefox on iOS from Safari of their WebKit (decision 0053).
|
Package platform says which profiles share a browser's network stack, so that a profile may inherit captures from the other's: Safari on iOS from Safari on macOS (decision 0051), Chrome and Firefox on iOS from Safari of their WebKit (decision 0053). |
|
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, SOCKS4 and HTTP CONNECT proxies, bounded by the caller's context, and carries UDP datagrams through SOCKS5 UDP associations (Association).
|
Package proxy connects through SOCKS5, SOCKS4 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. |
|
rpc/client
Package client is a Go client of mimicry-core's protocol (decision 0069), as an SDK speaks it: Hello first, calls on streams of their own, bodies and WebSocket messages as DATA, VerifyConnection answered, the core's notices handed off without blocking the reader.
|
Package client is a Go client of mimicry-core's protocol (decision 0069), as an SDK speaks it: Hello first, calls on streams of their own, bodies and WebSocket messages as DATA, VerifyConnection answered, the core's notices handed off without blocking the reader. |
|
rpc/convert
Package convert turns mimicry-core's protocol messages (internal/rpc/pb) into mimicry's public types and back (decision 0069): a Config with its callbacks as data, a request and its options, a response, a plan, a connection's TLS state, cookies, a traffic meter's counts, errors as codes, and the framing of a WebSocket's messages inside DATA.
|
Package convert turns mimicry-core's protocol messages (internal/rpc/pb) into mimicry's public types and back (decision 0069): a Config with its callbacks as data, a request and its options, a response, a plan, a connection's TLS state, cookies, a traffic meter's counts, errors as codes, and the framing of a WebSocket's messages inside DATA. |
|
rpc/pb
Package pb is the Go code protoc-gen-go generates from the schema in proto/mimicry/v1 (decision 0069): the messages of mimicry-core's protocol.
|
Package pb is the Go code protoc-gen-go generates from the schema in proto/mimicry/v1 (decision 0069): the messages of mimicry-core's protocol. |
|
rpc/server
Package server is mimicry-core's server (decision 0069): it answers one SDK's calls on one connection of the wire protocol (internal/rpc/wire), their messages those of internal/rpc/pb, through mimicry's public API.
|
Package server is mimicry-core's server (decision 0069): it answers one SDK's calls on one connection of the wire protocol (internal/rpc/wire), their messages those of internal/rpc/pb, through mimicry's public API. |
|
rpc/wire
Package wire is the framed, multiplexed protocol between mimicry-core and the language SDKs (decision 0069): frames, streams, per-stream credit, RESET and EVENT over any io.ReadWriteCloser.
|
Package wire is the framed, multiplexed protocol between mimicry-core and the language SDKs (decision 0069): frames, streams, per-stream credit, RESET and EVENT over any io.ReadWriteCloser. |
|
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; and the ASCII form of a host name (ASCII), in which browsers send and match it.
|
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; and the ASCII form of a host name (ASCII), in which browsers send and match it. |
|
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. |
|
traffic
Package traffic counts the bytes mimicry's sockets send and receive (Config.Traffic, decision 0070).
|
Package traffic counts the bytes mimicry's sockets send and receive (Config.Traffic, decision 0070). |
|
weburl
Package weburl holds what mimicry shares about URLs as browsers send them (the WHATWG URL standard, as the urls capture measures it): the percent-encode sets every browser measured applies, and a URL's path serialized as mimicry's canonical form leaves it, where Go's own (url.URL.EscapedPath) would encode characters a browser sends as they are ('|' for Firefox and Safari).
|
Package weburl holds what mimicry shares about URLs as browsers send them (the WHATWG URL standard, as the urls capture measures it): the percent-encode sets every browser measured applies, and a URL's path serialized as mimicry's canonical form leaves it, where Go's own (url.URL.EscapedPath) would encode characters a browser sends as they are ('|' for Firefox and Safari). |
|
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. |