unblock

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

unblock

A Go HTTP client that looks like a browser at the network layer, and knows when it has been blocked.

c := unblock.New(unblock.Options{})
resp, err := c.Get(ctx, "https://example.com")
if b := resp.Blocked(); b != nil {
    fmt.Println(b.Kind, b.Provider, b.Hint) // CF_CHALLENGE / CF_BLOCK_1020 / WAF_GENERIC / ...
}

Three things are handled, and one deliberately is not.

1. TLS/JA3 and HTTP/2 fingerprints

net/http, requests, and httpx all share a recognisable fingerprint. On an HTTPS connection the client sends a TLS ClientHello carrying cipher suites, extension order, elliptic curves, and ALPN — WAFs hash that into JA3/JA4. On top of it sits the HTTP/2 fingerprint: SETTINGS values, WINDOW_UPDATE, pseudo-header order.

unblock uses bogdanfinn/tls-client (ClientHello via uTLS, h2 via fhttp) so the fingerprint matches a real Chrome, Safari, or Firefox:

c := unblock.New(unblock.Options{
    Profile: "chrome_133", // empty = newest supported Chrome profile
})

Conceptually the same as curl_cffi in Python, without a separate process.

2. Headers follow the fingerprint and fetch mode

tls-client fingerprints the handshake and the HTTP/2 frames, but it leaves the headers alone. A bare client therefore sends Go-http-client/2.0 with a Chrome TLS fingerprint — a mismatch any WAF will flag, and the kind of thing you only notice by looking at what the server actually receives.

unblock derives a consistent header set and wire header order (Header-Order: and HTTP/2 PHeader-Order:) from the profile and the request's fetch mode (FetchModeNavigate for GET/HEAD, FetchModeCORS for Post and API payloads):

Header navigate (GET/HEAD) cors (Post / subresource API)
user-agent profile's browser and version same
sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform same version, Chromium-family only same
accept navigation text/html,... */*
sec-fetch-dest / sec-fetch-mode document / navigate empty / cors
sec-fetch-site none (same-origin / cross-site with Referer) same-origin (cross-site when Referer/Origin differs)
sec-fetch-user, upgrade-insecure-requests ?1 (except iOS), 1 omitted

For per-request headers (Authorization, If-None-Match), Referer, or explicit FetchMode overrides without creating a new Client, use DoRequest:

resp, err := c.DoRequest(ctx, unblock.Request{
    Method:      http.MethodPost,
    URL:         "https://example.com/api/graphql",
    Referer:     "https://example.com/app",
    Headers:     map[string]string{"x-csrf-token": token},
    ContentType: "application/json",
    Body:        payload,
})

unblock.DefaultHeaders("chrome_133") returns the navigation defaults if you need the raw map (DefaultHeadersForPlatform or Options.Platform — PlatformAuto, PlatformLinux, PlatformMacOS, PlatformWindows — lets the UA and Sec-CH-UA-Platform match your Linux/macOS host instead of defaulting to Windows). Override through Options.Headers or Request.Headers only when the value stays consistent with the profile.

Standard net/http.RoundTripper and Challenge Escalation

Both *Client and *Ladder implement http.RoundTripper, so unblock can drop straight into &http.Client{Transport: ...} or any standard http.RoundTripper middleware chain without coupling your packages to unblock.Response. Wrap it with NewEscalate to fall back to cdp.Transport (or harvest clearance cookies back into Client) only when a request hits a JS/captcha challenge:

l := unblock.NewLadder(unblock.Options{
    Platform:         unblock.PlatformAuto,
    DisableRedirects: true, // let http.Client own redirects and cookies when desired
    DisableCookies:   true,
})
esc := unblock.NewEscalate(unblock.EscalateOptions{
    Primary:  l,
    Fallback: cdpTr, // only called on Block.Challenge()
})
hc := &http.Client{Transport: esc}
resp, err := hc.Get("https://example.com")

3. Automatic HTTP/1.1 fallback, body guards, and cookies

Some servers reject HTTP/2 negotiation with RST_STREAM (stream ID 1; INTERNAL_ERROR) even though TLS succeeded. unblock detects that error shape and retries once over HTTP/1.1 with the same TLS fingerprint and the same cookie jar.

The first attempt only gets half the time budget, so the retry is not starved by a hanging first try. Response.Attempts and Response.HTTP1 report which path was used.

resp, _ := c.Get(ctx, url)
fmt.Println(resp.Attempts, resp.Truncated) // Attempts: 1 or 2; Truncated: true if body exceeded MaxBody
  • Body caps & media types: Options.MaxBody caps read bytes (5 MiB default) and sets Response.Truncated = true when sliced. Options.AllowedContentTypes (e.g. []string{"text/*", "application/json", "*+json"}) closes unwanted binary streams (video/mp4, archives) before reading the body (ErrDisallowedContentType), while still allowing text/html, text/plain, and untyped/empty-body responses on 202/403/405/429/503 (capped at 64 KiB) so WAF block classification continues to work.
  • Redirects: Options.DisableRedirects returns 3xx responses directly; Options.MaxRedirects caps hops (ErrTooManyRedirects).
  • Cookies: Enabled by default and shared across HTTP/2, HTTP/3, and HTTP/1.1 fallback (c.Cookies(url), c.SetCookies(url, cookies)). Set Options.DisableCookies: true for stateless fetching.
  • Force HTTP/1.1: Set Options.ForceHTTP1: true when a host consistently tarpits HTTP/2.

4. HTTP/3 protocol racing

Rules that block the HTTP/2 fingerprint usually do not apply to HTTP/3, which has its own fingerprint surface. ProtocolRacing starts QUIC and TCP in parallel and keeps whichever connects first, then reuses it per host:

c := unblock.New(unblock.Options{ProtocolRacing: true})

Measured on a Cloudflare-protected page where every recent profile was blocked over HTTP/2 (403), protocol racing returned 200 over HTTP/3 — with chrome_133 and with chrome_150. It is the single strongest lever here: stronger than changing profiles, and stronger than forcing HTTP/1.1.

Needs UDP egress. If QUIC is blocked, the client falls back to TCP; Response.Proto reports what actually answered (HTTP/3.0, HTTP/2.0, HTTP/1.1).

On Linux, quic-go warns about a small UDP receive buffer. Raise it for stable throughput:

sysctl -w net.core.rmem_max=7500000 net.core.wmem_max=7500000
HTTP/3 cannot travel through a proxy

HTTP CONNECT tunnels TCP. QUIC runs on UDP, so a racing rung with ProxyURL set does not degrade to h2 over the proxy — it connects directly and leaves your real exit IP exposed.

unblock therefore ignores ProtocolRacing when a proxy is configured, and a ladder records such rungs as skipped instead of running them.

Need h3 and an egress? The tunnel has to carry UDP: WireGuard, SOCKS5 UDP ASSOCIATE, or MASQUE (CONNECT-UDP). An HTTP proxy cannot do it, no matter how it is configured.

5. The ladder: one call, several attempts

A single fetch is a gamble on one fingerprint. Ladder walks an ordered list of attempts and stops at the first rung that gets an answer:

l := unblock.NewLadder(unblock.Options{Timeout: 20 * time.Second}).
    WithMaxAttempts(4).
    WithWinnerTTL(time.Hour).
    WithCooldown(unblock.NewCooldown(6 * time.Hour))

resp, err := l.Get(ctx, url)
resp, err = l.Post(ctx, apiURL, "application/json", body) // read-only APIs only
resp, err = l.DoRequest(ctx, unblock.Request{URL: apiURL, Referer: url, Headers: hdrs})

for _, a := range resp.Trail {        // concurrency-safe trail for this call
    fmt.Println(a.String(), a.Proto, a.HTTPStatus, a.BlockKind)
}

Default order (DefaultAttempts): chrome_133 over HTTP/2 → the same profile racing HTTP/3 → the same profile over HTTP/1.1 → firefox_123 over HTTP/1.1.

Rules that make it predictable:

  • A fingerprint-sensitive WAF block (CF_CHALLENGE, CF_BLOCK_1010, CF_BLOCK_1020, WAF_GENERIC, ...) means "try the next rung".
  • An IP-bound block (CF_BLOCK_1009 country block, CF_BLOCK_1015 or WAF_RATE_LIMIT rate limit) stops the walk immediately — switching profiles on the same IP cannot help and only extends the block.
  • Any answer from the origin — 200, 404, even 500 — ends the walk. Changing fingerprints cannot fix a page that does not exist.
  • Per-host winner memory (DefaultWinnerTTL = 1h, disable with WithWinnerTTL(0)) starts follow-up requests to the same host at the last winning rung, and falls back to the remaining rungs if it stops working.
  • Response.Trail carries the per-call rung trail safely across goroutines; WinnerFor(host) returns that host's cached winner (Last() and Winner() still report the most recent walk).
  • All tried rungs blocked → *BlockedError (wraps ErrBlocked) carrying the last block and the full trail. The ladder never invents a verdict.
  • WithCooldown parks a host after a block (honoring Block.RetryAfter when the WAF sends Retry-After); the next call returns *CooldownError instead of hammering.
  • WithFetcherFactory swaps how a rung is served (tests). Custom fetchers can implement Poster and Requester.
  • Post and DoRequest walk the same rungs and share winner memory and cooldown. Use them only for requests that are safe to repeat.

Cost: a healthy site costs 1 request; a WAF-protected one costs 2 on the first visit (HTTP/3 wins) and 1 on follow-up visits while winner memory is warm.

6. Block classification

Different situations hide behind HTTP 403, 429, and 503, and each needs a different action. Classify tells them apart from headers and body, with no extra requests:

Kind Marker What to do
CF_CHALLENGE cf-mitigated: challenge, _cf_chl_opt, Just a moment needs a browser that executes JS
CF_BLOCK_1010 Error 1010 / error code: 1010 browser signature banned: use a TLS profile, not a spoofed UA
CF_BLOCK_1009 Error 1009 / error code: 1009 country block: needs a local proxy
CF_BLOCK_1015 Error 1015 / error code: 1015 / CF 429 rate limited: add a cooldown (RetryAfter when sent)
CF_BLOCK_1020 Error 1020 / error code: 1020 firewall rule rejected the ASN/datacenter
WAF_CHALLENGE x-vercel-mitigated: challenge, x-amzn-waf-action: challenge/captcha, DataDome/PerimeterX captcha third-party JS/captcha challenge (b.Provider names the vendor)
WAF_RATE_LIMIT 429 with third-party WAF headers (x-datadome, x-sucuri-id, ...) third-party WAF rate limit (b.RateLimited() == true)
WAF_GENERIC 403/503 with x-sucuri-id, x-datadome, x-akamai-request-id, x-iinfo, x-amzn-waf-action: block, x-vercel-mitigated third-party WAF block (b.Provider names the vendor)

Note that a block is a statement about this request: same URL, same profile, different protocol can answer 200. Before concluding a host is unreachable, try ProtocolRacing (HTTP/3) and ForceHTTP1.

b := unblock.Classify(resp)
if b != nil {
    log.Printf("blocked: %s (%s, ray %s) — %s", b.Kind, b.Provider, b.RayID, b.Hint)
}
if b.Challenge() {
    // managed JS/captcha challenge (Cloudflare or third-party WAF)
}
if b.RateLimited() {
    // back off for b.RetryAfter or a host cooldown window
}

Plain origin 403 and 429 responses (a normal "forbidden" page, a login wall, or an application JSON quota error behind Cloudflare CDN) are intentionally not treated as WAF blocks.

If you already use net/http or another HTTP client and only want WAF block classification without pulling in tls-client or quic-go, import the zero-dependency github.com/nyelonong/unblock/classify subpackage (standard library only):

if b := classify.Classify(resp.StatusCode, resp.Header, body); b != nil {
    log.Printf("blocked: %s (%s)", b.Kind, b.Hint)
}

Per-host cooldown

Cloudflare blocks are sticky: hammering the same host within a short window tends to escalate the block. Cooldown buys distance, and MarkFor honors upstream Retry-After durations when available:

cd := unblock.NewCooldown(6 * time.Hour)
host := unblock.HostOf(url)

if !cd.Allow(host) {
    return fmt.Errorf("host %s is cooling down for %s", host, cd.Remaining(host))
}
resp, err := c.Get(ctx, url)
if b := resp.Blocked(); b != nil {
    cd.MarkFor(host, b.RetryAfter) // falls back to 6h when RetryAfter is 0
}

Fetching URLs your users typed

A server that fetches a user-supplied URL must not let it reach internal addresses (SSRF). PublicDialer() refuses loopback, RFC 1918 private networks, link-local/cloud metadata (169.254.169.254), CGNAT (100.64.0.0/10), IPv4-mapped IPv6, NAT64, 6to4, multicast, and reserved ranges after DNS resolution on every TCP connection, redirects included:

c := unblock.New(unblock.Options{
    Dialer:              unblock.PublicDialer(),
    AllowedContentTypes: []string{"text/*", "application/json", "*+json", "*+xml"},
    MaxRedirects:        5,
})

QUIC does not go through the dialer, so a Dialer disables HTTP/3: the client ignores ProtocolRacing, and a ladder records racing rungs as skipped.

With ProxyURL set, Control sees only the proxy's address. The proxy resolves and connects to the target itself, so the guard has to live in the proxy.

What this does NOT do

It does not execute JavaScript. A managed Cloudflare challenge (Turnstile, the "Checking your browser" page that computes a token) still cannot be bypassed — fingerprints only win against rules that are purely TLS/h2 based.

The package tells you that this is what happened (CF_CHALLENGE) instead of pretending to solve it. For JS-rendered pages or managed challenges, use the zero-dependency github.com/nyelonong/unblock/cdp subpackage (an http.RoundTripper over raw Chrome DevTools Protocol) against a local or Docker Chromium instance:

# On a Linux VPS, run Chromium bound to localhost only:
docker run -d --name chrome --shm-size=1g -p 127.0.0.1:9222:9222 chromedp/headless-shell:latest
tr := cdp.New(cdp.Options{
    DebugURL:       "http://127.0.0.1:9222",
    BlockResources: cdp.DefaultBlockedResources(), // abort images/media/fonts/css
    IsolateContext: true,
})
defer tr.Close()

// 1) Rendered DOM via standard http.Client:
hc := &http.Client{Transport: tr}
resp, err := hc.Get("https://example.com")

// 2) Or intercept a JS-signed XHR JSON response directly:
ctx = cdp.WithConfig(ctx, cdp.RequestConfig{InterceptURLContains: "/api/v4/search/search_items"})
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://shopee.co.id/search?keyword=keyboard", nil)
apiResp, err := hc.Do(req)

// 3) Or solve a challenge once and hand cookies + UA back to unblock.Client:
hr, err := tr.Harvest(ctx, "https://example.com")
client.SetCookies(hr.FinalURL, hr.Cookies)

Also out of scope: IP reputation and behaviour. A datacenter IP is often blocked even with a perfect fingerprint — use Options.ProxyURL to leave that IP behind.

Install

go get github.com/nyelonong/unblock

Requires Go 1.25+ (tls-client v1.16.0 or newer).

API

func New(opts Options) *Client
func (c *Client) Get(ctx context.Context, url string) (*Response, error)
func (c *Client) Head(ctx context.Context, url string) (*Response, error)
func (c *Client) Do(ctx context.Context, method, url string) (*Response, error)
func (c *Client) Post(ctx context.Context, url, contentType string, body []byte) (*Response, error)
func (c *Client) DoRequest(ctx context.Context, r Request) (*Response, error)
func (c *Client) RoundTrip(req *http.Request) (*http.Response, error)
func (c *Client) Cookies(rawURL string) []*http.Cookie
func (c *Client) SetCookies(rawURL string, cookies []*http.Cookie)
func (c *Client) CloseIdleConnections()

func DefaultHeaders(profile string) map[string]string
func DefaultHeadersForPlatform(profile, platform string) map[string]string
func NewEscalate(opts EscalateOptions) *Escalate
func (e *Escalate) RoundTrip(req *http.Request) (*http.Response, error)
func PublicDialer() *net.Dialer
func Classify(r *Response) *Block
func (b *Block) Challenge() bool
func (b *Block) RateLimited() bool
func (b *Block) IPBound() bool
func HostOf(rawURL string) string
func NewCooldown(window time.Duration) *Cooldown
func (c *Cooldown) Mark(host string)
func (c *Cooldown) MarkFor(host string, d time.Duration)

func NewLadder(base Options, attempts ...Attempt) *Ladder
func DefaultAttempts() []Attempt
func (l *Ladder) WithMaxAttempts(n int) *Ladder
func (l *Ladder) WithWinnerTTL(d time.Duration) *Ladder
func (l *Ladder) WithCooldown(c *Cooldown) *Ladder
func (l *Ladder) WithFetcherFactory(f func(Attempt) Fetcher) *Ladder
func (l *Ladder) Get(ctx context.Context, url string) (*Response, error)
func (l *Ladder) Head(ctx context.Context, url string) (*Response, error)
func (l *Ladder) Post(ctx context.Context, url, contentType string, body []byte) (*Response, error)
func (l *Ladder) DoRequest(ctx context.Context, req Request) (*Response, error)
func (l *Ladder) RoundTrip(req *http.Request) (*http.Response, error)
func (l *Ladder) Winner() Fetcher
func (l *Ladder) WinnerFor(host string) Fetcher
func (l *Ladder) Last() []AttemptResult
func (l *Ladder) CloseIdleConnections()

Options: Profile, Platform, ProxyURL, Timeout, MaxBody, Headers, AllowedContentTypes, ForceHTTP1, ProtocolRacing, InsecureSkipVerify, DisableRedirects, MaxRedirects, DisableCookies, Dialer.

Request: Method, URL, Headers, Referer, ContentType, Body, FetchMode.

Response: StatusCode, Header, Body, FinalURL, Proto, Attempts, HTTP1, Truncated, Trail, plus Get(header) and Blocked().

Zero-dependency classification subpackage (github.com/nyelonong/unblock/classify):

const MaxRetryAfter = 24 * time.Hour
type Block struct { ... }
func Classify(status int, header http.Header, body []byte) *Block
func ClassifyAt(status int, header http.Header, body []byte, now time.Time) *Block
func (b *Block) Challenge() bool
func (b *Block) RateLimited() bool
func (b *Block) IPBound() bool

Test

go test ./...

Covers a real httptest server, body limits and truncation, media-type and redirect guards, PublicDialer() SSRF prefixes, fetch-mode headers, shared cookie jars, ForceHTTP1, WAF block/challenge/rate-limit classification variants, per-host winner memory, and cooldown behaviour.

License

MIT — see LICENSE.

Documentation

Overview

Package unblock is an HTTP client for Go that looks like a browser at the network layer (Chrome-like TLS ClientHello and HTTP/2 fingerprint) and knows when it has been blocked.

Three things are handled:

  1. TLS/JA3 and HTTP/2 fingerprints — via bogdanfinn/tls-client, so WAF rules based on fingerprints do not reject the request.
  2. Automatic HTTP/1.1 fallback when a server rejects HTTP/2 (RST_STREAM), reusing the same TLS fingerprint.
  3. Block classification — Cloudflare challenges, errors 1009/1010/1015/1020, and third-party WAFs are told apart from one another, because each needs a different follow-up action.

This package does NOT execute JavaScript. A Cloudflare challenge that requires JS cannot be bypassed here; Classify only reports that this is what happened.

Index

Examples

Constants

View Source
const (
	// FetchModeNavigate selects top-level browser document navigation headers.
	FetchModeNavigate = "navigate"
	// FetchModeCORS selects subresource fetch/XHR headers (used for JSON/API calls).
	FetchModeCORS = "cors"

	// PlatformWindows selects Windows User-Agent and Sec-CH-UA-Platform tokens (default).
	PlatformWindows = "windows"
	// PlatformLinux selects Linux User-Agent and Sec-CH-UA-Platform tokens.
	PlatformLinux = "linux"
	// PlatformMacOS selects macOS User-Agent and Sec-CH-UA-Platform tokens.
	PlatformMacOS = "macos"
	// PlatformAuto matches runtime.GOOS so HTTP headers agree with the host TCP stack.
	PlatformAuto = "auto"
)
View Source
const DefaultCooldownWindow = 6 * time.Hour

DefaultCooldownWindow is used when NewCooldown receives a zero duration.

View Source
const DefaultMaxBody = 5 << 20

DefaultMaxBody caps how many body bytes are read (5 MiB).

View Source
const DefaultTimeout = 20 * time.Second

DefaultTimeout is the per-attempt deadline when Options.Timeout is zero.

View Source
const DefaultWinnerTTL = time.Hour

DefaultWinnerTTL is how long NewLadder remembers which rung answered for a host before starting from rung 0 again.

View Source
const MaxRetryAfter = classify.MaxRetryAfter

MaxRetryAfter caps upstream Retry-After headers so a malformed or hostile value cannot park a host indefinitely.

Variables

View Source
var ErrBlocked = errors.New("unblock: every attempt was blocked")

ErrBlocked is returned when every rung was blocked by a WAF.

View Source
var ErrDisallowedContentType = errors.New("unblock: disallowed content-type")

ErrDisallowedContentType is returned when Options.AllowedContentTypes rejects the response's Content-Type header before reading the body.

View Source
var ErrNoBody = errors.New("unblock: empty body")

ErrNoBody is returned when a response carries no usable payload.

View Source
var ErrPrivateAddress = errors.New("unblock: non-public destination address")

ErrPrivateAddress is returned by PublicDialer when a target hostname or redirect target resolves to a loopback, private, link-local, shared, or reserved IP address.

View Source
var ErrTooManyRedirects = errors.New("unblock: too many redirects")

ErrTooManyRedirects is returned when redirect hops exceed Options.MaxRedirects.

Functions

func DefaultHeaders added in v0.4.0

func DefaultHeaders(profile string) map[string]string

DefaultHeaders returns a browser-consistent navigation header set for a TLS profile.

tls-client fingerprints the handshake and the HTTP/2 frames but leaves the headers alone, so without this the wire says "Go-http-client/2.0" while the fingerprint claims Chrome — a mismatch any WAF will flag. The browser name and version are read from the profile (GetClientHelloId), never guessed from the profile string.

accept-encoding is deliberately absent: the transport adds its own and decompresses the body. Setting it here leaves the response compressed, which silently shrinks the HTML and breaks substring checks.

func DefaultHeadersForPlatform added in v0.10.0

func DefaultHeadersForPlatform(profile, platform string) map[string]string

DefaultHeadersForPlatform returns browser-consistent navigation headers for a TLS profile and OS platform (PlatformWindows, PlatformLinux, PlatformMacOS, or PlatformAuto). Empty defaults to PlatformWindows.

func HostOf

func HostOf(raw string) string

HostOf returns the host (without port) of a URL, or the input unchanged when it cannot be parsed.

func PublicDialer added in v0.10.0

func PublicDialer() *net.Dialer

PublicDialer returns a *net.Dialer whose Control hook refuses connections to loopback, RFC 1918 private, link-local (including 169.254.169.254 cloud metadata), CGNAT (100.64.0.0/10), NAT64, 6to4, multicast, and reserved IPs.

Pass it as Options.Dialer when fetching user-supplied URLs. Because QUIC does not use net.Dialer, Client and Ladder automatically disable HTTP/3 racing when Dialer is set. When ProxyURL is also set, the proxy resolves the target host, so SSRF filtering must be enforced by the proxy itself.

Types

type Attempt added in v0.3.0

type Attempt struct {
	Profile        string `json:"profile"`
	ForceHTTP1     bool   `json:"http1,omitempty"`
	ProtocolRacing bool   `json:"http3,omitempty"`
}

Attempt is one fetch strategy: a TLS profile plus the protocol controls that matter when a WAF rejects a fingerprint.

func DefaultAttempts added in v0.3.0

func DefaultAttempts() []Attempt

DefaultAttempts is the measured starting order.

Basis: 17 profiles, one WAF-protected page, single GET each.

  • HTTP/2 was rejected for every recent profile.
  • Racing HTTP/3 answered 200 for chrome_133 and chrome_150 while HTTP/2 was blocked for both, so the protocol is a stronger lever than the profile.
  • HTTP/1.1 carried chrome_133, chrome_144, firefox_123, and brave_146.
  • chrome_144 and chrome_150 share a JA3N hash yet behaved differently, so the HTTP/2 settings fingerprint is part of what the WAF sees.

Order: mainstream Chrome over h2, the same profile racing h3, the same profile over h1.1, then another engine for when Chrome-shaped traffic is blocked wholesale. Ties break on how common the browser version is in the wild, not on release date.

func (Attempt) String added in v0.3.0

func (a Attempt) String() string

String renders one attempt for logs: profile plus protocol.

type AttemptResult added in v0.3.0

type AttemptResult struct {
	Attempt
	HTTPStatus int    `json:"http_status,omitempty"`
	Proto      string `json:"proto,omitempty"`
	BlockKind  string `json:"block_kind,omitempty"`
	Error      string `json:"error,omitempty"`
	OK         bool   `json:"ok,omitempty"`
}

AttemptResult records what one rung did.

type Block

type Block = classify.Block

Block describes a single WAF or anti-bot blocking event.

func Classify

func Classify(r *Response) *Block

Classify inspects a response and reports whether it is a WAF/anti-bot block. It returns nil when the response is not a block.

Example

Tell block types apart.

package main

import (
	"fmt"
	"net/http"

	"github.com/nyelonong/unblock"
)

func main() {
	h := http.Header{}
	h.Set("Server", "cloudflare")
	h.Set("Cf-Ray", "8a1b2c3d-JKT")

	resp := &unblock.Response{
		StatusCode: 403,
		Header:     h,
		Body:       []byte("<title>Attention Required!</title><h2>Error 1020</h2>"),
	}

	b := unblock.Classify(resp)
	fmt.Println(b.Kind, b.Code, b.Challenge())
	fmt.Println(b.Hint)

}
Output:
CF_BLOCK_1020 1020 false
firewall rule rejected the ASN/datacenter: needs a residential proxy

type BlockedError added in v0.3.0

type BlockedError struct {
	Block    *Block
	Attempts []AttemptResult
}

BlockedError carries the last block plus the full trail.

func (*BlockedError) Error added in v0.3.0

func (e *BlockedError) Error() string

func (*BlockedError) Unwrap added in v0.3.0

func (e *BlockedError) Unwrap() error

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a fetcher with a browser fingerprint.

Example (ForceHTTP1)

Combine both levers: force HTTP/1.1 when QUIC is unavailable in the network and HTTP/2 is blocked. The TLS fingerprint is unchanged.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("ok"))
	}))
	defer srv.Close()

	c := unblock.New(unblock.Options{Timeout: 5 * time.Second, ForceHTTP1: true})
	resp, err := c.Get(context.Background(), srv.URL)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(resp.StatusCode, resp.HTTP1)

}
Output:
200 true
Example (ProtocolRacing)

Race HTTP/3 against HTTP/2 and read the protocol that actually answered.

Many anti-bot rules are scoped to the HTTP/2 fingerprint. Racing QUIC in parallel with TCP often gets an answer where HTTP/2 alone is blocked, and the same TLS profile is reused either way.

Response.Proto tells you which one won, so a "blocked" result is never ambiguous about the transport that produced it.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("<html>hello</html>"))
	}))
	defer srv.Close()

	c := unblock.New(unblock.Options{
		Profile:        "chrome_133",
		Timeout:        5 * time.Second,
		ProtocolRacing: true,
	})

	resp, err := c.Get(context.Background(), srv.URL)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(resp.StatusCode, resp.Proto)

}
Output:
200 HTTP/1.1

func New

func New(opts Options) *Client

New builds a Client. An unusable configuration does not make New fail: the client falls back to plain net/http so callers never have to handle an error on the construction path.

func (*Client) CloseIdleConnections added in v0.8.0

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes the keep-alive connections the client holds. Call it when the client is done, so a short-lived client does not keep sockets open until the idle timeout.

func (*Client) Cookies added in v0.10.0

func (c *Client) Cookies(rawURL string) []*http.Cookie

Cookies returns the cookies currently stored for rawURL, or nil when cookies are disabled or rawURL cannot be parsed.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, url string) (*Response, error)

Do performs the request and returns the full body.

When the first attempt fails because of an HTTP/2 problem (RST_STREAM, INTERNAL_ERROR), the request is retried once over HTTP/1.1 with the same TLS fingerprint. Half of the time budget is reserved for that second attempt.

func (*Client) DoRequest added in v0.10.0

func (c *Client) DoRequest(ctx context.Context, r Request) (*Response, error)

DoRequest performs a request with per-call headers, referer, body, and fetch mode, applying the same HTTP/1.1 stream-error fallback as Do.

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*Response, error)

Get fetches a URL. Redirects are followed.

Example

Fetch a page with a browser fingerprint.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("<html>hello</html>"))
	}))
	defer srv.Close()

	c := unblock.New(unblock.Options{Profile: "chrome_133", Timeout: 5 * time.Second})

	resp, err := c.Get(context.Background(), srv.URL)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(resp.StatusCode, len(resp.Body) > 0, resp.Blocked() == nil)

}
Output:
200 true true

func (*Client) Head

func (c *Client) Head(ctx context.Context, url string) (*Response, error)

Head sends a HEAD request. Some servers reject HEAD; callers that need a body should fall back to Get themselves.

func (*Client) Post added in v0.7.0

func (c *Client) Post(ctx context.Context, url, contentType string, body []byte) (*Response, error)

Post sends a request with a body using FetchModeCORS defaults, which is what JSON endpoints behind a WAF expect (for example YouTube continuation or GraphQL calls). The TLS/HTTP fingerprint is the same as for Get.

func (*Client) RoundTrip added in v0.10.0

func (c *Client) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements net/http.RoundTripper so *Client can plug directly into &http.Client{Transport: c} or any RoundTripper middleware chain. Callers that want http.Client to manage redirects and cookies itself should configure Options.DisableRedirects: true and Options.DisableCookies: true.

func (*Client) SetCookies added in v0.10.0

func (c *Client) SetCookies(rawURL string, cookies []*http.Cookie)

SetCookies stores cookies for rawURL in the client's jar. It is a no-op when Options.DisableCookies is true or rawURL has no scheme and host.

type Cooldown

type Cooldown struct {
	// contains filtered or unexported fields
}

Cooldown records hosts that just blocked us.

Cloudflare blocks are sticky: repeating a request to the same host within a short window tends to escalate the block (challenge becomes block). A cooldown buys distance before that host is attempted again.

Example

Use a per-host cooldown.

package main

import (
	"fmt"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	cd := unblock.NewCooldown(time.Hour)
	host := unblock.HostOf("https://example.com/page")

	fmt.Println(cd.Allow(host))
	cd.Mark(host)
	fmt.Println(cd.Allow(host))

}
Output:
true
false

func NewCooldown

func NewCooldown(window time.Duration) *Cooldown

NewCooldown creates a Cooldown with the given window. Zero means DefaultCooldownWindow.

func (*Cooldown) Allow

func (c *Cooldown) Allow(host string) bool

Allow reports whether the host may be attempted now.

func (*Cooldown) Mark

func (c *Cooldown) Mark(host string)

Mark parks the host for the default cooldown window.

func (*Cooldown) MarkFor added in v0.10.0

func (c *Cooldown) MarkFor(host string, d time.Duration)

MarkFor parks the host for d, or for the default window when d <= 0.

func (*Cooldown) Remaining

func (c *Cooldown) Remaining(host string) time.Duration

Remaining returns how long the host stays parked (0 when it is allowed).

func (*Cooldown) Reset

func (c *Cooldown) Reset(host string)

Reset clears the cooldown marker for a host.

type CooldownError added in v0.3.0

type CooldownError struct {
	Host      string
	Remaining time.Duration
}

CooldownError is returned when the host is still parked.

func (*CooldownError) Error added in v0.3.0

func (e *CooldownError) Error() string

type Escalate added in v0.10.0

type Escalate struct {
	// contains filtered or unexported fields
}

Escalate is an http.RoundTripper that sends requests through Primary and escalates safe GET/HEAD navigations to Fallback or Harvest only when Primary hits a JS/captcha challenge.

func NewEscalate added in v0.10.0

func NewEscalate(opts EscalateOptions) *Escalate

NewEscalate builds an Escalate RoundTripper.

func (*Escalate) RoundTrip added in v0.10.0

func (e *Escalate) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements net/http.RoundTripper.

type EscalateOptions added in v0.10.0

type EscalateOptions struct {
	// Primary handles requests first (typically *Client, *Ladder, or
	// http.DefaultTransport). Nil defaults to http.DefaultTransport.
	Primary http.RoundTripper

	// Fallback serves requests when Primary encounters a JS/captcha challenge.
	// Optional when Harvest is set.
	Fallback http.RoundTripper

	// Harvest solves a JS/captcha challenge once for rawURL, returning cookies
	// to seed into Primary and an optional already-fetched *http.Response. When
	// resp is nil, Escalate retries Primary once after seeding cookies.
	Harvest func(ctx context.Context, rawURL string) (cookies []*http.Cookie, resp *http.Response, err error)

	// CookieSetter stores harvested cookies on Primary. If nil and Primary
	// implements SetCookies(string, []*http.Cookie) (such as *Client), it is
	// wired automatically.
	CookieSetter func(rawURL string, cookies []*http.Cookie)

	// ShouldEscalate decides whether a classified block triggers escalation.
	// Defaults to (*Block).Challenge().
	ShouldEscalate func(b *Block) bool

	// Classify inspects non-2xx WAF responses from Primary. Defaults to
	// classify.Classify.
	Classify func(status int, header http.Header, body []byte) *Block
}

EscalateOptions configures a two-tier Escalate http.RoundTripper.

type Fetcher added in v0.3.0

type Fetcher interface {
	Get(ctx context.Context, url string) (*Response, error)
	Head(ctx context.Context, url string) (*Response, error)
}

Fetcher is the surface the ladder needs. *Client satisfies it.

type Ladder added in v0.3.0

type Ladder struct {
	// contains filtered or unexported fields
}

Ladder walks attempts in order and stops at the first answer that is not a WAF block. A fingerprint-sensitive block moves to the next rung; an IP-bound block (country or rate limit) or any origin response — 200, 404, even 500 — ends the walk immediately.

func NewLadder added in v0.3.0

func NewLadder(base Options, attempts ...Attempt) *Ladder

NewLadder builds a Ladder on top of base options with per-host winner memory enabled for DefaultWinnerTTL. Attempts that carry an empty Profile inherit nothing from base: a ladder rung is a complete strategy, so set Profile explicitly, or start from DefaultAttempts.

func (*Ladder) CloseIdleConnections added in v0.8.0

func (l *Ladder) CloseIdleConnections()

CloseIdleConnections closes the keep-alive connections of every rung's client. Call it when a short-lived ladder is done.

func (*Ladder) DoRequest added in v0.10.0

func (l *Ladder) DoRequest(ctx context.Context, req Request) (*Response, error)

DoRequest walks the ladder with per-request headers, referer, body, and fetch mode. Repeat-safety caveats match Post whenever req carries a body or non-idempotent method.

func (*Ladder) Get added in v0.3.0

func (l *Ladder) Get(ctx context.Context, url string) (*Response, error)

Get fetches a URL, walking the ladder.

Example

One call walks the whole ladder and stops at the first rung that gets an answer: HTTP/2, then HTTP/3 racing, then HTTP/1.1, then another engine.

A block means "try the next rung". Any answer from the origin — 200, 404, even 500 — ends the walk, because changing fingerprints cannot fix a page that does not exist.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	l := unblock.NewLadder(unblock.Options{
		Timeout: 20 * time.Second,
		Headers: map[string]string{"accept-language": "en-US,en;q=0.9"},
	}).WithMaxAttempts(4)

	resp, err := l.Get(context.Background(), "https://example.com/")
	if err != nil {
		var blocked *unblock.BlockedError
		if errors.As(err, &blocked) {
			fmt.Println("every rung blocked, last kind:", blocked.Block.Kind)
			return
		}
		fmt.Println("request failed:", err)
		return
	}

	fmt.Println(resp.StatusCode, resp.Proto)
	for _, a := range l.Last() {
		fmt.Printf("  %-32s %-9s %d\n", a.String(), a.Proto, a.HTTPStatus)
	}
}

func (*Ladder) Head added in v0.3.0

func (l *Ladder) Head(ctx context.Context, url string) (*Response, error)

Head sends a HEAD request, walking the ladder.

func (*Ladder) Last added in v0.3.0

func (l *Ladder) Last() []AttemptResult

Last returns the trail of the most recent walk. Prefer Response.Trail and BlockedError.Attempts when a single Ladder is shared across goroutines.

func (*Ladder) Post added in v0.9.0

func (l *Ladder) Post(ctx context.Context, url, contentType string, body []byte) (*Response, error)

Post sends a request with a body, walking the ladder, with the same cooldown and trail as Get.

The next rung resends the same body after a WAF block. A block is answered by the WAF before the origin sees the request, but use Post only for requests that are safe to repeat, such as read-only JSON APIs: the ladder cannot tell whether a request that failed in transit reached the origin, and Client already resends over HTTP/1.1 after an HTTP/2 failure.

func (*Ladder) RoundTrip added in v0.10.0

func (l *Ladder) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements net/http.RoundTripper so *Ladder can plug directly into &http.Client{Transport: l} or any RoundTripper middleware chain. Callers that want http.Client to manage redirects and cookies itself should configure Options.DisableRedirects: true and Options.DisableCookies: true.

func (*Ladder) Winner added in v0.3.0

func (l *Ladder) Winner() Fetcher

Winner returns the fetcher that produced the most recent successful response. Prefer WinnerFor when a single Ladder is shared across concurrent hosts.

func (*Ladder) WinnerFor added in v0.10.0

func (l *Ladder) WinnerFor(host string) Fetcher

WinnerFor returns the remembered winning fetcher for a host or URL while its TTL remains valid, or nil when none is cached.

func (*Ladder) WithCooldown added in v0.3.0

func (l *Ladder) WithCooldown(c *Cooldown) *Ladder

WithCooldown parks a host after a block, so repeated checks do not escalate it.

Example

Park a host after a block so repeated checks do not escalate it.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/nyelonong/unblock"
)

func main() {
	cd := unblock.NewCooldown(6 * time.Hour)

	l := unblock.NewLadder(unblock.Options{Timeout: 20 * time.Second}).
		WithCooldown(cd).
		WithMaxAttempts(3)

	if _, err := l.Get(context.Background(), "https://example.com/"); err != nil {
		var cooling *unblock.CooldownError
		if errors.As(err, &cooling) {
			fmt.Println("still parked for", cooling.Remaining)
		}
	}

	fmt.Println("cooling down:", !cd.Allow(unblock.HostOf("https://example.com/")))
}

func (*Ladder) WithFetcherFactory added in v0.3.0

func (l *Ladder) WithFetcherFactory(f func(Attempt) Fetcher) *Ladder

WithFetcherFactory overrides how a rung is served. Intended for tests.

func (*Ladder) WithMaxAttempts added in v0.3.0

func (l *Ladder) WithMaxAttempts(n int) *Ladder

WithMaxAttempts caps how many rungs are tried.

func (*Ladder) WithWinnerTTL added in v0.10.0

func (l *Ladder) WithWinnerTTL(d time.Duration) *Ladder

WithWinnerTTL sets how long the ladder remembers a host's winning rung so follow-up requests try it before rung 0. A non-positive duration disables per-host winner memory and clears stored winners.

type Options

type Options struct {
	// Profile names a TLS preset, e.g. "chrome_133" or "firefox_135".
	// Empty means the package default Chrome profile (the newest supported one).
	// See profiles.MappedTLSClients for the full list.
	Profile string

	// Platform selects the OS identity used in User-Agent and Sec-CH-UA-Platform
	// (PlatformWindows, PlatformLinux, PlatformMacOS, or PlatformAuto to match
	// runtime.GOOS). Empty defaults to PlatformWindows.
	Platform string

	// ProxyURL is optional: "http://127.0.0.1:8080" or "socks5://10.0.0.2:1080".
	ProxyURL string

	// Timeout per attempt. Zero means DefaultTimeout.
	Timeout time.Duration

	// MaxBody caps the number of body bytes read. Zero means DefaultMaxBody.
	MaxBody int64

	// Headers override the browser-consistent defaults derived from Profile
	// (user-agent, sec-ch-ua, accept, sec-fetch-*). Set one only when you know
	// the value stays consistent with the profile's fingerprint.
	Headers map[string]string

	// AllowedContentTypes restricts response media types (e.g. "text/*",
	// "application/json", "*+json"). Disallowed responses close the stream
	// before reading the body and fail with ErrDisallowedContentType. On
	// 202/403/405/429/503, text/html, text/plain, and untyped/empty-body
	// responses are still read (capped at 64 KiB when not explicitly allowed)
	// so WAF block pages can be classified.
	AllowedContentTypes []string

	// ForceHTTP1 disables HTTP/2 negotiation entirely. Useful for servers that
	// tarpit or consistently reject h2.
	ForceHTTP1 bool

	// ProtocolRacing races HTTP/3 (QUIC) and HTTP/2 (TCP) and uses whichever
	// connects first, similar to Chrome's Happy Eyeballs. The client then reuses
	// the winning protocol per host.
	//
	// This is the strongest lever against anti-bot rules that target the HTTP/2
	// fingerprint: measured on a Cloudflare-protected page where every recent
	// profile was blocked over HTTP/2, HTTP/3 answered 200 with both
	// chrome_133 and chrome_150. Requires UDP egress; if QUIC is blocked the
	// client falls back to TCP.
	ProtocolRacing bool

	// InsecureSkipVerify disables certificate verification. Only for internal
	// hosts with self-signed certificates and for tests; it does not affect the
	// fingerprint, only trust.
	InsecureSkipVerify bool

	// DisableRedirects returns 3xx responses directly without following
	// Location.
	DisableRedirects bool

	// MaxRedirects caps how many redirect hops are followed when positive
	// (ignored when DisableRedirects is true). Exceeding the cap fails with
	// ErrTooManyRedirects.
	MaxRedirects int

	// DisableCookies turns off automatic cookie storage and sending on this
	// Client. When false, the primary and HTTP/1.1 fallback transports share one
	// cookie jar.
	DisableCookies bool

	// Dialer opens every TCP connection, so its Control hook sees each resolved
	// address, redirects included. Use it to refuse private networks when the URL
	// comes from a user. QUIC does not use it, so setting Dialer disables HTTP/3
	// and ProtocolRacing. With ProxyURL set, Control sees only the proxy's
	// address: the proxy resolves and connects to the target, so the guard no
	// longer applies to it.
	Dialer *net.Dialer
}

Options configures a Client.

type Poster added in v0.9.0

type Poster interface {
	Post(ctx context.Context, url, contentType string, body []byte) (*Response, error)
}

Poster is the extra surface Ladder.Post needs from each rung when the rung does not implement Requester. *Client satisfies both.

type Request added in v0.10.0

type Request struct {
	Method      string
	URL         string
	Headers     map[string]string
	Referer     string
	ContentType string
	Body        []byte
	// FetchMode selects FetchModeNavigate ("navigate") or FetchModeCORS
	// ("cors"). Empty defaults to FetchModeCORS when Body != nil,
	// ContentType != "", or Method is POST/PUT/PATCH/DELETE, and
	// FetchModeNavigate otherwise.
	FetchMode string
}

Request describes an HTTP request with optional per-call headers, referer, body, and browser fetch mode.

type Requester added in v0.10.0

type Requester interface {
	DoRequest(ctx context.Context, req Request) (*Response, error)
}

Requester is the per-request surface Ladder.DoRequest uses when a rung supports full Request options. *Client satisfies it.

type Response

type Response struct {
	StatusCode int
	Header     http.Header
	Body       []byte
	FinalURL   string
	// Proto is the negotiated protocol, e.g. "HTTP/2.0" or "HTTP/3.0".
	Proto string

	// Attempts is 1 for the first try, 2 when the HTTP/1.1 fallback was used.
	Attempts int
	// HTTP1 is true when the response came from the HTTP/1.1 fallback path.
	HTTP1 bool
	// Truncated is true when the response body exceeded the read limit and was
	// sliced.
	Truncated bool
	// Trail records each rung attempted when the response came from a Ladder.
	// Direct Client calls leave it nil.
	Trail []AttemptResult
}

Response is a fully-read response, truncated at MaxBody.

func (*Response) Blocked

func (r *Response) Blocked() *Block

Blocked returns block details, or nil when the response is not a block.

func (*Response) Get

func (r *Response) Get(name string) string

Get returns the value of a response header.

Directories

Path Synopsis
Package cdp implements a minimal, standard-library-only Chrome DevTools Protocol (CDP) client and net/http.RoundTripper.
Package cdp implements a minimal, standard-library-only Chrome DevTools Protocol (CDP) client and net/http.RoundTripper.
Package classify inspects HTTP responses and classifies WAF and anti-bot blocks using only the Go standard library.
Package classify inspects HTTP responses and classifies WAF and anti-bot blocks using only the Go standard library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址