# 5-Second Challenge (WAF)

> Pass Cloudflare's "Just a moment..." browser check.

Source: https://docs.peak.fo/docs/tasks/cloudflare-5s

Passes Cloudflare's browser check, the "Just a moment..." page that runs before a site loads. Peak Solutions returns the clearance cookies, the headers to send, and the form fields that complete the challenge.

## How it works [#how-it-works]

1. **Load the page** through your proxy. Cloudflare answers with the challenge page.
2. **Send it to Peak Solutions**, with the same proxy and user-agent.
3. **Complete the challenge.** Add the returned cookies, then post the returned form fields back to the page.
4. **Keep going** with the same proxy, cookies and headers. Cloudflare now lets you through.

<Callout type="warn" title="Use a sticky proxy">
  Cloudflare ties the clearance to the IP that solved it. Use a sticky (session) proxy, and keep
  the same session from step 1 to step 4. Start a new proxy session for each solve.
</Callout>

## Request [#request]

`POST https://api.peak.fo/solve`

| Field        | Type     | Required | Description                                                                                                                                                               |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `task_type`  | `string` | Yes      | `cloudflare5stask`                                                                                                                                                        |
| `url`        | `string` | Yes      | The page that shows the challenge.                                                                                                                                        |
| `proxy`      | `string` | Yes      | A [sticky](/docs/proxies#sticky-sessions) proxy, as `protocol://user:pass@host:port` or in [proxy parameters](/docs/proxies#proxy-parameters). The same one your code uses. |
| `user_agent` | `string` | No       | The user-agent your code sends. Must be a Windows Chrome user-agent.                                                                                                      |
| `html`       | `string` | No       | The challenge page you already loaded in step 1. Saves a request, so solves faster.                                                                                       |

```bash title="Terminal"
curl https://api.peak.fo/solve \
  -H "X-API-Key: pk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "task_type": "cloudflare5stask",
    "url": "https://example.com/",
    "proxy": "http://user:pass@1.2.3.4:8080",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
  }'
```

## Response [#response]

| Field             | Type     | Description                                                            |
| ----------------- | -------- | ---------------------------------------------------------------------- |
| `data.cookies`    | `object` | Cookies to add for the site, such as `cf_clearance`.                   |
| `data.headers`    | `object` | Headers to send on every request from now on. Names are lowercase.     |
| `data.attributes` | `object` | Form fields to post back to the page, to complete the challenge.       |
| `data.cf_rt`      | `string` | Challenge token. Goes in the `Referer` of that post, as `__cf_chl_tk`. |
| `cost`            | `number` | What the solve was charged, in USD.                                    |
| `error`           | `string` | On failure: what went wrong, in words.                                 |
| `error_code`      | `string` | On failure: what went wrong, as a stable [code](/docs/api/errors).     |

```json tab="Success"
{
  "success": true,
  "data": {
    "cookies": {
      "cf_clearance": "Kx9...",
      "__cf_bm": "aB3..."
    },
    "headers": {
      "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ..."
    },
    "attributes": {
      "md": "Zq1...",
      "r": "7Hk..."
    },
    "cf_rt": "Wm2..."
  },
  "cost": 0.001
}
```

```json tab="Failure"
{
  "success": false,
  "error": "IP address is blocked by CloudFlare - use a different proxy with cleaner reputation",
  "error_code": "ip_blocked"
}
```

## Complete the challenge [#complete-the-challenge]

After the solve, post `attributes` back to the page:

- **Method and URL:** `POST` to the same `url` you solved.
- **Body:** `attributes` as a URL-encoded form (`application/x-www-form-urlencoded`).
- **Cookies:** everything in `cookies`.
- **Headers:** everything in `headers`, plus a `Referer` of your `url` with `__cf_chl_tk=<cf_rt>` added to its query string.

Cloudflare checks the TLS fingerprint as well as the headers, so use an HTTP client that looks like Chrome. A plain HTTP library gets challenged again.

This full example runs all four steps. Install the client for your language:

- **Python:** [wreq](https://github.com/0x676e67/wreq-python), `pip install wreq` (Python 3.11+)
- **JavaScript:** [wreq-js](https://github.com/sqdshguy/wreq-js), `npm install wreq-js`
- **Go:** [tls-client](https://github.com/bogdanfinn/tls-client), `go get github.com/bogdanfinn/tls-client` (Go 1.27+)

```python tab="Python" tab-group="language"
import asyncio
from datetime import timedelta
from urllib.parse import urlencode

from wreq import Client, Cookie, Emulation, Platform, Proxy

API_KEY = "pk_your_api_key"
USER_AGENT = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"
)


async def solve(url: str, proxy: str, html: str) -> dict:
    """Sends the challenge page to Peak Solutions and returns the solution."""
    async with Client(timeout=timedelta(seconds=120)) as client:
        resp = await client.post(
            "https://api.peak.fo/solve",
            headers={"X-API-Key": API_KEY},
            json={
                "task_type": "cloudflare5stask",
                "url": url,
                "proxy": proxy,
                "user_agent": USER_AGENT,
                "html": html,
            },
        )
        body = await resp.json()

    if not body["success"]:
        raise RuntimeError(f"{body['error_code']}: {body['error']}")
    return body["data"]


async def main() -> None:
    url = "https://example.com/"
    proxy = "http://user:pass@1.2.3.4:8080"  # a sticky session

    async with Client(
        emulation=Emulation(Emulation.Chrome154, Platform.Windows),
        user_agent=USER_AGENT,
        proxies=[Proxy.all(proxy)],
        cookie_store=True,
        timeout=timedelta(seconds=60),
    ) as browser:
        # 1. Load the page. Cloudflare answers with the challenge.
        page = await browser.get(url)

        # 2. Send it to Peak Solutions.
        solution = await solve(url, proxy, await page.text())

        # 3. Add the cookies, then post the form fields back.
        for name, value in solution["cookies"].items():
            browser.cookie_jar.add(Cookie(name, value), url)

        separator = "&" if "?" in url else "?"
        referer = url + separator + urlencode({"__cf_chl_tk": solution["cf_rt"]})
        await browser.post(
            url,
            form=solution.get("attributes", {}),
            headers={**solution["headers"], "referer": referer},
        )

        # 4. You're through. Keep using the same browser and headers.
        page = await browser.get(url, headers=solution["headers"])
        print(page.status, await page.text())


if __name__ == "__main__":
    asyncio.run(main())
```

```js tab="JavaScript" tab-group="language"
import { createSession } from "wreq-js";

const API_KEY = "pk_your_api_key";
const USER_AGENT =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
  "(KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";

// Sends the challenge page to Peak Solutions and returns the solution.
async function solve(url, proxy, html) {
  const resp = await fetch("https://api.peak.fo/solve", {
    method: "POST",
    headers: { "X-API-Key": API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({
      task_type: "cloudflare5stask",
      url,
      proxy,
      user_agent: USER_AGENT,
      html,
    }),
  });
  const body = await resp.json();

  if (!body.success) {
    throw new Error(`${body.error_code}: ${body.error}`);
  }
  return body.data;
}

async function main() {
  const url = "https://example.com/";
  const proxy = "http://user:pass@1.2.3.4:8080"; // a sticky session

  // Chrome 149 on Windows, through your proxy. The session keeps cookies between requests.
  const browser = await createSession({
    browser: "chrome_149",
    os: "windows",
    proxy,
    timeout: 60_000,
  });

  try {
    // 1. Load the page. Cloudflare answers with the challenge.
    const page = await browser.fetch(url);

    // 2. Send it to Peak Solutions.
    const solution = await solve(url, proxy, await page.text());

    // 3. Add the cookies, then post the form fields back.
    for (const [name, value] of Object.entries(solution.cookies)) {
      browser.setCookie(name, value, url);
    }

    const separator = url.includes("?") ? "&" : "?";
    const referer = url + separator + new URLSearchParams({ __cf_chl_tk: solution.cf_rt });
    await browser.fetch(url, {
      method: "POST",
      headers: {
        ...solution.headers,
        "content-type": "application/x-www-form-urlencoded",
        referer,
      },
      body: new URLSearchParams(solution.attributes).toString(),
    });

    // 4. You're through. Keep using the same browser and headers.
    const result = await browser.fetch(url, { headers: solution.headers });
    console.log(result.status, await result.text());
  } finally {
    await browser.close();
  }
}

await main();
```

```go tab="Go" tab-group="language"
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/url"
	"strings"

	http "github.com/bogdanfinn/fhttp"
	tls_client "github.com/bogdanfinn/tls-client"
	"github.com/bogdanfinn/tls-client/profiles"
)

const (
	apiKey    = "pk_your_api_key"
	userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
)

// Solution is what Peak Solutions returns for a cloudflare5stask.
type Solution struct {
	Cookies    map[string]string `json:"cookies"`
	Headers    map[string]string `json:"headers"`
	Attributes map[string]string `json:"attributes"`
	CfRt       string            `json:"cf_rt"`
}

// solve sends the challenge page to Peak Solutions and returns the solution.
func solve(pageURL, proxy, html string) (*Solution, error) {
	payload, err := json.Marshal(map[string]string{
		"task_type":  "cloudflare5stask",
		"url":        pageURL,
		"proxy":      proxy,
		"user_agent": userAgent,
		"html":       html,
	})
	if err != nil {
		return nil, err
	}

	client, err := tls_client.NewHttpClient(tls_client.NewNoopLogger(), tls_client.WithTimeoutSeconds(120))
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, "https://api.peak.fo/solve", bytes.NewReader(payload))
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-Key", apiKey)
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var body struct {
		Success   bool     `json:"success"`
		Error     string   `json:"error"`
		ErrorCode string   `json:"error_code"`
		Data      Solution `json:"data"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return nil, err
	}
	if !body.Success {
		return nil, fmt.Errorf("%s: %s", body.ErrorCode, body.Error)
	}
	return &body.Data, nil
}

// send makes a request that looks like Chrome, adds any extra headers, and returns the status and body.
func send(browser tls_client.HttpClient, method, pageURL, body string, headers map[string]string) (int, string, error) {
	var reader io.Reader
	if body != "" {
		reader = strings.NewReader(body)
	}
	req, err := http.NewRequest(method, pageURL, reader)
	if err != nil {
		return 0, "", err
	}
	req.Header = http.Header{
		"accept":          {"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
		"accept-language": {"en-US,en;q=0.9"},
		"user-agent":      {userAgent},
	}
	for name, value := range headers {
		req.Header[strings.ToLower(name)] = []string{value}
	}

	resp, err := browser.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	text, err := io.ReadAll(resp.Body)
	return resp.StatusCode, string(text), err
}

func main() {
	pageURL := "https://example.com/"
	proxy := "http://user:pass@1.2.3.4:8080" // a sticky session

	browser, err := tls_client.NewHttpClient(tls_client.NewNoopLogger(),
		tls_client.WithClientProfile(profiles.Chrome_152),
		tls_client.WithProxyUrl(proxy),
		tls_client.WithCookieJar(tls_client.NewCookieJar()),
		tls_client.WithTimeoutSeconds(60),
	)
	if err != nil {
		log.Fatal(err)
	}

	// 1. Load the page. Cloudflare answers with the challenge.
	_, html, err := send(browser, http.MethodGet, pageURL, "", nil)
	if err != nil {
		log.Fatal(err)
	}

	// 2. Send it to Peak Solutions.
	solution, err := solve(pageURL, proxy, html)
	if err != nil {
		log.Fatal(err)
	}

	// 3. Add the cookies, then post the form fields back.
	u, err := url.Parse(pageURL)
	if err != nil {
		log.Fatal(err)
	}
	var cookies []*http.Cookie
	for name, value := range solution.Cookies {
		cookies = append(cookies, &http.Cookie{Name: name, Value: value})
	}
	browser.SetCookies(u, cookies)

	form := url.Values{}
	for name, value := range solution.Attributes {
		form.Set(name, value)
	}
	separator := "?"
	if strings.Contains(pageURL, "?") {
		separator = "&"
	}
	headers := map[string]string{
		"content-type": "application/x-www-form-urlencoded",
		"referer":      pageURL + separator + url.Values{"__cf_chl_tk": {solution.CfRt}}.Encode(),
	}
	for name, value := range solution.Headers {
		headers[name] = value
	}
	if _, _, err := send(browser, http.MethodPost, pageURL, form.Encode(), headers); err != nil {
		log.Fatal(err)
	}

	// 4. You're through. Keep using the same browser and headers.
	status, page, err := send(browser, http.MethodGet, pageURL, "", solution.Headers)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(status, page)
}
```

## Errors [#errors]

A failed solve returns HTTP `200` with `"success": false`, and is not charged.

| `error_code`             | What to do                                                         |
| ------------------------ | ------------------------------------------------------------------ |
| `no_challenge`           | The page isn't showing the challenge, or the `url` is wrong.       |
| `ip_blocked`             | Retry with a different proxy.                                      |
| `unsupported_user_agent` | Send a Windows Chrome user-agent.                                  |
| `invalid_html`           | Check the `url`, and that `html` is the challenge page itself.     |
| `invalid_request_data`   | Check the `url` format, such as `https://example.com/`.            |
| `challenge_flagged`      | Retry with a proxy that has a cleaner IP.                          |
| `turnstile_failed`       | Retry with a different proxy.                                      |
| `invalid_sitekey`        | The Turnstile inside the challenge has a sitekey the solver can't use. Retry, or [contact support](/docs/support). |
| `invalid_action`         | The Turnstile inside the challenge rejected the action. Retry.     |
| `invalid_cdata`          | The Turnstile inside the challenge rejected the cdata. Retry.      |
| `no_servers`             | No solver is free right now. Retry in a few seconds.               |
| `proxy_error`            | Check the proxy format, that it's reachable, and that it's sticky. Also returned when the proxy fails during the challenge's Turnstile step. |
| `timeout`                | Retry, or use a faster proxy closer to the site.                   |
| `solve_failed`           | Retry with a different proxy.                                      |
| `solver_error`           | Retry with a different proxy.                                      |

A request missing `url` or `proxy` is rejected with HTTP `400` and `missing_fields`. For rejections like `insufficient_balance`, see [Error codes](/docs/api/errors).
