# ThreatMetrix Solver API

> ThreatMetrix (LexisNexis) profiling solver API. Nullgate runs the device profile through your own HTTP client with one send callback.

> ThreatMetrix costs $1.00 per 1,000 requests passed to `send` ([all prices](https://nullgate.club/en/prices)).

For automatic collection and cookies, use [`POST /solve` with `type: "threatmetrix"`](https://nullgate.club/en/solver). The sections below explain the SDK callback and profile lifetime.

## Advanced: run the profile through your client

While a ThreatMetrix profile runs, Nullgate makes HTTP requests to the target through your `send` function.

1. Load the page with your client and call `session.page(url, html)`.
2. Start the profile: `page.threatmetrix(send=...)`.
3. Wait for collection: `wait_collected()` / `waitForCollected()`.
4. Call `pagehide()` before you submit a form or go to another page.
5. Close the profile.

```python
import asyncio
import os

import httpx

from nullgate import TargetRequest, TargetResponse
from nullgate.aio 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"
)

async def main() -> None:
    async with (
        Nullgate() as ng,
        httpx.AsyncClient(headers={"User-Agent": UA}, follow_redirects=False) as http,
    ):

        async def my_send(request: TargetRequest) -> TargetResponse:
            if request.credentials == "omit":
                async with httpx.AsyncClient(headers={"User-Agent": UA}) as isolated:
                    response = await isolated.request(
                        request.method,
                        request.url,
                        headers=request.headers,
                        content=request.body,
                    )
            else:
                response = await http.request(
                    request.method,
                    request.url,
                    headers=request.headers,
                    content=request.body,
                )
            return TargetResponse(
                response.status_code, dict(response.headers), response.content
            )

        url = os.environ["TARGET_URL"]
        page = ng.session(user_agent=UA).page(url, (await http.get(url)).text)
        async with page.threatmetrix(send=my_send) as tmx:
            await tmx.pagehide()

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

```typescript
import { readFile } from "node:fs/promises";
import { Nullgate, type TargetFetch } from "@nullgate/sdk";

const userAgent =
  process.env.USER_AGENT ??
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36";
const page = new Nullgate()
  .session({ userAgent })
  .page(
    process.env.PAGE_URL ?? "https://shop.example/login",
    await readFile("page.html", "utf8"),
  );
// Native fetch has no cookie jar. Use your client here when the site needs one.
const send: TargetFetch = async (request) => {
  const response = await fetch(request.url, {
    method: request.method,
    headers: request.headers,
    body: request.body === null ? null : new Uint8Array(request.body),
    credentials: request.credentials,
    redirect: "manual",
    signal: request.signal,
  });
  return {
    status: response.status,
    headers: Object.fromEntries(response.headers),
    body: new Uint8Array(await response.arrayBuffer()),
  };
};
const tmx = await page.threatmetrix({ send });
try {
  await tmx.waitForCollected();
  await tmx.pagehide();
} finally {
  await tmx.close();
}
```

## The send callback

| Request field                      | Meaning                                                                                                    |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `url`, `method`, `headers`, `body` | Send them unchanged. `body` is bytes, or nothing when the request has no body                              |
| `credentials`                      | `include`: use your normal cookie jar. `omit`: send no cookies and do not keep the cookies from the answer |
| `role`                             | What the request is for. Use it as a label in your logs                                                    |
| `signal`                           | TypeScript only. Abort the request when it fires                                                           |

Return `status`, `headers` and the raw `body` bytes.

- Return every answer the target gives, including `403` and `5xx`.
- Do not follow redirects.
- If the request cannot be made, raise an exception. The profile then ends with the code [`upstream`](https://nullgate.club/en/errors#upstream).

## Profile methods

| Python                      | TypeScript           | What it does                                                                                        |
| --------------------------- | -------------------- | --------------------------------------------------------------------------------------------------- |
| `wait_collected()`          | `waitForCollected()` | Waits until the profile has collected everything for this page                                      |
| `pagehide()`                | `pagehide()`         | Tells the profile that you leave the page. Call it before you submit the form or go to another page |
| end of `with`, or `close()` | `close()`            | Ends the profile. Always end it                                                                     |

## Options

- `script_url` (`scriptUrl`): the URL of the ThreatMetrix `tags.js` script. The SDK finds it in the page HTML when the URL has `org_id` and `session_id`. Pass it if the SDK raises `protection_not_found`.
- `collector`: replaces `script_url` when the site starts ThreatMetrix through its own JavaScript wrapper. Pass the wrapper's `url`, `org_id` and `session_id` (`orgId`, `sessionId` in TypeScript). Example: `examples/kleinanzeigen` in the SDK repositories.
- `proxy`: the proxy of your HTTP client, as an `http`, `socks4` or `socks5` URL with an explicit port. The SDK uses it for the one connection it opens itself.
- `inputs`, `actions`: `inputs` accepts raw non-password fields or prepared summaries, as for [Akamai](https://nullgate.club/en/akamai#sensor). Omitted `actions` enables automatic interactions. `actions: []` / `actions=[]` disables them and supplies no events.

Python blocking form: import `Nullgate` from `nullgate` and use `with page.threatmetrix(send=my_send) as tmx:`. There `send` can be a plain function.

## Limits and capacity

Page HTML: up to 4 MiB of UTF-8.

Profile startup may wait for capacity. If capacity stays full, it fails with `unavailable` over the WebSocket. Retry later.

## Billing

One request passed to `send` is one `threatmetrix.profile` operation. See [Keys and balance](https://nullgate.club/en/account).
