# Akamai Solver API

> Akamai Bot Manager solver API. Nullgate generates sensor_data, pixel and SBSD requests for the _abck cookie, and your HTTP client sends them. SDKs for Python, TypeScript and Go.

> For 1,000 requests, you pay $1.50 for sensor, $1.50 for pixel, or $2.50 for SBSD ([all prices](https://nullgate.club/en/prices)).

For automatic cookies, use [`POST /solve` with `type: "akamai"`](https://nullgate.club/en/solver). The sections below cover manual SDK generation.

## Advanced: prepare and send requests

Install the SDK through [Deep](https://nullgate.club/en/deep#sdk-clients) and get an API key from the bot. [Top up](https://nullgate.club/en/account#top-up) before generating. For Go, see the [Go SDK guide](https://nullgate.club/en/go-sdk).

```python
import os

import httpx

from nullgate import Nullgate

UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
)
url = os.environ["TARGET_URL"]
with Nullgate() as ng, httpx.Client(headers={"User-Agent": UA}) as http:
    session = ng.session(user_agent=UA)
    html = http.get(url).text
    page = session.page(url, html)
    assert page.sensor_url is not None
    sensor = page.sensor(script=http.get(page.sensor_url).text, cookies=http.cookies)
    sensor.wait()
    http.post(sensor.url, content=sensor.body, headers=sensor.headers)
```

```typescript
import { Nullgate } from "@nullgate/sdk";

const url = process.argv[2] ?? "https://www.nike.com/";
const userAgent =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36";
const http = (url: string) =>
  fetch(url, { headers: { "User-Agent": userAgent } });
const response = await http(url);
const cookies = Object.fromEntries(
  response.headers.getSetCookie().map((cookie) => {
    const pair = cookie.split(";", 1)[0] ?? "";
    const separator = pair.indexOf("=");
    return [pair.slice(0, separator), pair.slice(separator + 1)];
  }),
);
const page = new Nullgate()
  .session({ userAgent })
  .page(response.url, await response.text());
if (!page.sensorUrl) throw new Error("This page has no sensor script");
const sensor = await page.sensor({
  script: await (await http(page.sensorUrl)).text(),
  cookies,
});
await sensor.wait();
const sent = await fetch(sensor.url, {
  method: "POST",
  body: sensor.body,
  headers: {
    ...sensor.headers,
    "User-Agent": userAgent,
    Cookie: Object.entries(cookies)
      .map(([name, value]) => name + "=" + value)
      .join("; "),
  },
});
console.log(sent.status);
```

A rejected request raises `NullgateError` with a `code`. See [Errors](https://nullgate.club/en/errors).

In your project, send the page request, the script request and the generated request through one HTTP client, with one proxy and one cookie jar.

## Three common mistakes

### A new session for every request

`ng.session(...)` creates a new browser identity on every call. Create one session per visit to the target and call `session.page(url, html)` for every page of that visit. More: [Sessions](https://nullgate.club/en/sessions).

### Sending without `wait()`

Every result has `send_at`: the earliest moment the target should receive the request. Call `wait()`, then send the request at once.

### A script from another page

Pass the script text downloaded from `page.sensor_url` of this exact page, with the same HTTP client. A different script restarts the page state in the session.

## How the requests work

A page can need a sensor, a pixel and SBSD. Each has its own script. The flow is the same:

1. The SDK finds the script URL in the page HTML.
2. Your client downloads the script.
3. The SDK returns a ready request.
4. You call `wait()`, then your client sends the request.

```python
sensor = page.sensor(script=http.get(page.sensor_url).text, cookies=http.cookies)
sensor.wait()
http.post(sensor.url, content=sensor.body, headers=sensor.headers)
```

```typescript
const sensor = await page.sensor({
  script: await (await http(page.sensorUrl)).text(),
  cookies,
});
await sensor.wait();
await post(sensor);
```

The TypeScript snippets send a result with this helper:

```typescript
const post = (request: {
  url: string;
  body: string;
  headers: Record<string, string>;
}) =>
  fetch(request.url, {
    method: "POST",
    body: request.body,
    headers: {
      ...request.headers,
      "User-Agent": userAgent,
      Cookie: Object.entries(cookies)
        .map(([name, value]) => name + "=" + value)
        .join("; "),
    },
  });
```

## Find the scripts

| Python            | TypeScript       | Value                                                     |
| ----------------- | ---------------- | --------------------------------------------------------- |
| `page.sensor_url` | `page.sensorUrl` | URL of the sensor script, or nothing if the page has none |
| `page.pixel_url`  | `page.pixelUrl`  | URL of the pixel script                                   |
| `page.sbsd_url`   | `page.sbsdUrl`   | URL of the SBSD script                                    |

The search runs on your machine and makes no network requests.

- If the page has several candidates, the SDK raises `ambiguous_protection` and lists them. Pass one as `script_url` (`scriptUrl` in TypeScript).
- If the SDK finds no script but you know its URL, pass `script_url` too.

**Limits.** A script can contain up to 2 MiB of UTF-8 bytes, the complete API JSON body up to 8 MiB. Above either limit the API returns HTTP 413 `invalid_request`.

**Overload.** If generation capacity stays full, the API returns HTTP 503 `unavailable` with `Retry-After: 1`. You are not charged, and the session state does not change.

## Sensor

| Argument  | Meaning                                                                                                                                    |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `script`  | The text of the sensor script, downloaded with your client                                                                                 |
| `cookies` | The cookies your client holds for the target: a mapping or a cookie jar. The SDK sends only `_abck` and `bm_sz` to Nullgate                |
| `inputs`  | Optional. The fields you filled before submitting, for example `{"email": "user@example.com"}`. The key is the `id` or `name` of the field |

### Script retention

Pass `script` on every SDK call. One download per document is enough. The SDK avoids sending the text again when it can:

1. After the server returns top-level `script_retained: true`, the SDK sends only the `script_digest` on later calls for that document.
2. If the server returns `script_required`, the SDK retries once with the full script.

A new document, a new session or a changed script resets retention. Older servers omit `script_retained`, so the SDK keeps sending the full script. Wire contract: [HTTP API](https://nullgate.club/en/http#retaining-an-akamai-sensor-script). Pixel and SBSD do not use retention.

### Form inputs

Raw values of non-password fields stay on your machine: the SDK sends only their lengths and hashes. Pass passwords through `prepare_inputs()` / `prepareInputs()`, which returns `PreparedInput` summaries. A raw password value fails with `invalid_inputs`.

```python
from nullgate import prepare_inputs

inputs = [
    {"name": "email", "value": "user@example.com"},
    *prepare_inputs([{"name": "password", "type": "password", "value": password}]),
]
sensor = page.sensor(script=script, cookies=http.cookies, inputs=inputs)
```

```typescript
import { prepareInputs } from "@nullgate/sdk";

const inputs = [
  { name: "email", value: "user@example.com" },
  ...prepareInputs([{ name: "password", type: "password", value: password }]),
];
const sensor = await page.sensor({ script, cookies, inputs });
```

[Amazon FWCIM](https://nullgate.club/en/amazon-fwcim) accepts the same prepared inputs.

`actions` supplies observed interaction events, such as pointer and key events.

| You pass          | Effect                                                                   |
| ----------------- | ------------------------------------------------------------------------ |
| No `inputs`       | The session keeps its input observations                                 |
| `inputs=[]`       | Replaces the input goals with none                                       |
| No `actions`      | The server can add automatic actions                                     |
| `actions=[]`      | Adds no caller actions and disables automatic actions for this call      |

Neither empty list erases past events.

With `inputs` and no `actions`, automatic typing keeps the timer and pointer submission boundaries. Continue on the same `page` and honor each `send_at`. Earlier sensors may precede typing, so one response does not guarantee that every declared field has been collected.

### Result and next sensors

The result has `url`, `body`, `headers`, `send_at` and `request_id`. Send `body` unchanged.

If the target needs one more sensor, call `page.sensor(...)` again on the same `page` with the cookies your client holds now.

Three or four sensors are usually enough. Do not wait for `_abck` to change from `-1` to `0`: the target may never do that, and later requests do not require it.

The local cookie helpers tell you when to stop sending sensors. They do not prove that the target accepted anything:

| Python | TypeScript | Meaning |
| --- | --- | --- |
| `abck_counters(abck)` | `abckCounters(abck)` | Returns `(response limit, generation)`. An unavailable counter is `-1` |
| `is_enough(abck, response_count=count)` | `isEnough(abck, count)` | True when the limit is available and completed sensor responses reach it |

Count target sensor responses within the current cookie generation. Reset the count when the generation changes. An unavailable limit keeps the gate open.

Import the helpers from `nullgate.akamai` in Python or `@nullgate/sdk` in TypeScript.

## Pixel

```python
pixel = page.pixel(script=http.get(page.pixel_url).text)
pixel.wait()
http.post(pixel.url, content=pixel.body, headers=pixel.headers)
```

```typescript
const pixel = await page.pixel({
  script: await (await http(page.pixelUrl)).text(),
});
await pixel.wait();
await post(pixel);
```

The SDK reads the pixel challenge from the page HTML. To override it, pass `challenge` as a decimal string: `page.pixel(script=script, challenge="123")` or `await page.pixel({ script, challenge: "123" })`. Pixel takes no cookies.

For a hidden cross-origin iframe without delegated permissions, pass `iframe=True` in Python,
`iframe: true` in TypeScript, or call `session.PixelIframe(...)` in Go.
This models zero-sized content and restricted permissions for this pixel only.
Leave it unset for the main page or visible frames. It requires an updated API server.

## SBSD

```python
sbsd = page.sbsd(script=http.get(page.sbsd_url).text, cookies=http.cookies)
sbsd.wait()
http.post(sbsd.url, content=sbsd.body, headers=sbsd.headers)
```

```typescript
const sbsd = await page.sbsd({
  script: await (await http(page.sbsdUrl)).text(),
  cookies,
});
await sbsd.wait();
await post(sbsd);
```

The SDK sends only the `bm_so`, `sbsd_o` and `bm_s` cookies to Nullgate.

## Common mistakes

| You see                                                                      | Cause                                                          | Fix                                                                    |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `protection_not_found`                                                       | The page HTML has no script of this kind                       | Check that you passed the HTML of the right page, or pass `script_url` |
| `ambiguous_protection`                                                       | Several scripts match                                          | Pass one of the listed URLs as `script_url`                            |
| [`invalid_request`](https://nullgate.club/en/errors#invalid_request) with `Invalid field: script` | The text is not the script of this page                        | Download the script again from the URL the SDK found                   |
| [`session_busy`](https://nullgate.club/en/errors#session_busy)                                    | Two requests of one session run at the same time over raw HTTP | Send the requests of one session one by one. The SDKs do this for you  |
