> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Server verification

> Verify Foil sealed tokens on your backend with a local check, no network call, then read the verdict and risk score to allow, challenge, or block actions.

Foil is designed around backend verification. The browser sends your backend a fresh `{ sessionId, sealedToken }` handoff, and your backend decides whether to allow, challenge, throttle, or block the action.

## Recommended flow

**1. Start Foil early**

Initialize the browser client on page load so collection begins before the user reaches the protected action.

**2. Request a fresh session handoff**

Right before signup, checkout, login, or another sensitive action, call `foil.getSession()`.

**3. Submit the handoff with the business action**

Send `{ sessionId, sealedToken }` to your backend alongside your normal payload.

**4. Verify on the server**

Use the SDK to verify the sealed token locally with your secret key.

**5. Apply policy**

Allow, challenge, rate-limit, or block based on the verdict.

## Browser handoff

```html theme={"dark"}
<script type="module">
  const { sessionId, sealedToken } = await foil.getSession();

  await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      ...formData,
      foil: { sessionId, sealedToken },
    }),
  });
</script>
```

## Verify the sealed token

The primary verification path. Local, fast, no network call to Foil.

The [iOS](https://usefoil.com/docs/ios-sdk.md) and [Android](https://usefoil.com/docs/android-sdk.md) SDKs return the same `{ sessionId, sealedToken }` handoff, and you verify a native token the same way as a browser token.

> [!NOTE]
>
> The method is named `safeVerifyFoilToken` (and snake/Pascal variants) in every SDK except PHP, where it is `SealedToken::safeVerify`.

```javascript Node.js theme={"dark"}
const { safeVerifyFoilToken } = require("@abxy/foil-server");

app.post("/api/signup", (req, res) => {
  const result = safeVerifyFoilToken(
    req.body.foil.sealedToken,
    process.env.FOIL_SECRET_KEY,
  );

  if (!result.ok) {
    return res.status(500).json({ error: "Verification failed" });
  }

  console.log(result.data.decision.verdict);    // "human", "bot", or "inconclusive"
  console.log(result.data.decision.risk_score); // 0–100
  console.log(result.data.session_id);

  if (result.data.decision.verdict === "bot") {
    return res.status(403).json({ error: "Blocked" });
  }

  // Proceed with the action
});
```

```python Python theme={"dark"}
from foil_server import safe_verify_foil_token
import os

@app.post("/api/signup")
def signup(request):
    result = safe_verify_foil_token(
        request.json["foil"]["sealedToken"],
        os.environ["FOIL_SECRET_KEY"],
    )

    if not result.ok:
        return {"error": "Verification failed"}, 500

    print(result.data.decision.verdict)    # "human", "bot", or "inconclusive"
    print(result.data.decision.risk_score) # 0 – 100

    if result.data.decision.verdict == "bot":
        return {"error": "Blocked"}, 403

    # Proceed with the action
```

```go Go theme={"dark"}
import foil "github.com/abxy-labs/foil-server-go"

func signupHandler(w http.ResponseWriter, r *http.Request) {
    var body struct {
        Foil struct {
            SealedToken string `json:"sealedToken"`
        } `json:"foil"`
    }
    json.NewDecoder(r.Body).Decode(&body)

    result := foil.SafeVerifyFoilToken(
        body.Foil.SealedToken,
        os.Getenv("FOIL_SECRET_KEY"),
    )
    if !result.OK {
        http.Error(w, "Verification failed", 500)
        return
    }

    if result.Data.Decision.Verdict == "bot" {
        http.Error(w, "Blocked", 403)
        return
    }

    // Proceed with the action
}
```

```ruby Ruby theme={"dark"}
require "foil/server"

post "/api/signup" do
  body = JSON.parse(request.body.read)
  result = Foil::Server::SealedToken.safe_verify_foil_token(
    body.dig("foil", "sealedToken"),
    ENV.fetch("FOIL_SECRET_KEY"),
  )

  halt 500, { error: "Verification failed" }.to_json unless result[:ok]

  decision = result[:data][:decision]
  halt 403, { error: "Blocked" }.to_json if decision[:verdict] == "bot"

  # Proceed with the action
end
```

```php PHP theme={"dark"}
use Foil\Server\SealedToken;

$body = json_decode(file_get_contents("php://input"), true);
$result = SealedToken::safeVerify(
    $body["foil"]["sealedToken"],
    getenv("FOIL_SECRET_KEY"),
);

if (!$result->ok) {
    http_response_code(500);
    echo json_encode(["error" => "Verification failed"]);
    exit;
}

if ($result->data->decision["verdict"] === "bot") {
    http_response_code(403);
    echo json_encode(["error" => "Blocked"]);
    exit;
}

// Proceed with the action
```

```bash cURL theme={"dark"}
# Use the SDK for local verification. For API-based readback, see below.
```

## What verification doesn't check

Verification confirms that the token is authentic and that your secret key can open it. The server SDKs decrypt the token and return its contents. They don't check how old the token is, they don't remember which tokens they have seen, and they don't wait for a final result. Three things follow from that:

* **A token has no expiry.** Every `getSession()` call produces a new token, and the token's `decision.evaluated_at` records when Foil produced it. A token that someone captured from a real browser still verifies later, so reject tokens whose `evaluated_at` is more than a few minutes old.

* **A token can be submitted more than once.** Verification is stateless. To reject repeats, record the `decision.event_id` of each token you accept, which is unique to each token, or the `session_id` if you allow one action per session.

* **A token can carry a provisional result.** A token minted before the visitor has interacted with the page holds a snapshot-phase result with `decision.is_provisional` set to `true`. Foil may finish the session later with a different risk score, and that final result doesn't come back through the token you already verified. If your policy depends on a fine threshold, treat a provisional token as provisional: call `getSession()` again after the visitor has interacted, or read the session's final result with the [Sessions API](https://usefoil.com/docs/api-reference/sessions.md) or a [webhook](https://usefoil.com/docs/webhooks.md). See [Preliminary vs final](https://usefoil.com/docs/verdicts-and-scoring.md#preliminary-vs-final).

Also use the `session_id` from the verified token, not the `sessionId` that the browser sent. Nothing in the request ties the browser's `sessionId` field to the token, so a caller can send a valid token next to a different session ID.

The following example treats a token that fails verification or is more than five minutes old as missing:

```javascript theme={"dark"}
const { safeVerifyFoilToken } = require("@abxy/foil-server");

const MAX_TOKEN_AGE_MS = 5 * 60 * 1000;

function verifyFoil(handoff) {
  if (!handoff?.sealedToken) return null;

  const result = safeVerifyFoilToken(
    handoff.sealedToken,
    process.env.FOIL_SECRET_KEY,
  );
  if (!result.ok) return null;

  const age = Date.now() - Date.parse(result.data.decision.evaluated_at);
  if (age > MAX_TOKEN_AGE_MS) return null;

  return result.data;
}
```

Decide in your policy what a missing token means. See [Verify the token on your server](https://usefoil.com/docs/use-cases/checkout.md#verify-the-token-on-your-server) in the checkout guide for a complete example in every server SDK language.

## Alternative: session readback

If you prefer to fetch the full session from the API (useful for async or audit workflows):

```javascript Node.js theme={"dark"}
const resp = await fetch(
  `https://api.usefoil.com/v1/sessions/${sessionId}`,
  { headers: { Authorization: `Bearer ${process.env.FOIL_SECRET_KEY}` } }
);
const session = await resp.json();

console.log(session.data.decision.automation_status); // "human", "automated", or "uncertain"
console.log(session.data.decision.risk_score);        // 0 – 100
```

```python Python theme={"dark"}
import requests

resp = requests.get(
    f"https://api.usefoil.com/v1/sessions/{session_id}",
    headers={"Authorization": f"Bearer {os.environ['FOIL_SECRET_KEY']}"},
)
session = resp.json()

print(session["data"]["decision"]["automation_status"])
print(session["data"]["decision"]["risk_score"])
```

```bash cURL theme={"dark"}
curl https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..."
```

Key fields in the session readback response:

| Field | Description |
| - | - |
| `decision.automation_status` | `human`, `automated`, or `uncertain` |
| `decision.risk_score` | integer `0` (human) to `100` (bot) |
| `decision.evaluation_phase` | `snapshot`, `behavioral`, or `null` |
| `decision.decision_status` | `preliminary` or `final` |
| `client_user_id` | Your own end-user ID, if you attached one |
| `client_application_id` | Your own ID for the application or organization the session belongs to, if you attached one |
| `highlights` | Top signals that influenced the decision |
| `attribution` | Labels for what is behind the session, such as the actor, tool, and provider. See [Attribution labels](https://usefoil.com/docs/attribution.md) for every value. |
| `visitor_fingerprint` | Persistent device identifier |

## Attach your user ID

If the Foil session starts before the user exists in your database, attach your user ID after signup succeeds from your backend. Pass the `session_id` from the verified token.

```javascript Node.js theme={"dark"}
const { Foil } = require("@abxy/foil-server");

const client = new Foil({ secretKey: process.env.FOIL_SECRET_KEY });

await client.sessions.attachClientUser(sessionId, user.id);
// Later, if needed:
await client.sessions.clearClientUser(sessionId);
```

```python Python theme={"dark"}
from foil_server import Foil

client = Foil(secret_key=os.environ["FOIL_SECRET_KEY"])

client.sessions.attach_client_user(session_id, user.id)
# Later, if needed:
client.sessions.clear_client_user(session_id)
```

```go Go theme={"dark"}
client, err := foil.NewClient(foil.WithSecretKey(os.Getenv("FOIL_SECRET_KEY")))
if err != nil {
    log.Fatal(err)
}

_, err = client.Sessions.AttachClientUser(ctx, sessionID, user.ID)
_, err = client.Sessions.ClearClientUser(ctx, sessionID)
```

```ruby Ruby theme={"dark"}
client = Foil::Server::Client.new(secret_key: ENV.fetch("FOIL_SECRET_KEY"))

client.sessions.attach_client_user(session_id, user.id)
client.sessions.clear_client_user(session_id)
```

```php PHP theme={"dark"}
use Foil\Server\Client;

$client = new Client(secretKey: getenv("FOIL_SECRET_KEY"));

$client->sessions()->attachClientUser($sessionId, $user->id);
$client->sessions()->clearClientUser($sessionId);
```

```bash cURL theme={"dark"}
curl -X PATCH https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"client_user_id":"user_123"}'
```

If your product serves other businesses, you can also attach your own ID for the application or organization that the session belongs to, such as a platform customer account or a tenant. Send it as `client_application_id`, either alone or in the same request as `client_user_id`:

```javascript Node.js theme={"dark"}
await client.sessions.attachClientApplication(sessionId, account.id);
// Later, if needed:
await client.sessions.clearClientApplication(sessionId);
```

```python Python theme={"dark"}
client.sessions.attach_client_application(session_id, account.id)
client.sessions.clear_client_application(session_id)
```

```go Go theme={"dark"}
_, err = client.Sessions.AttachClientApplication(ctx, sessionID, account.ID)
_, err = client.Sessions.ClearClientApplication(ctx, sessionID)
```

```ruby Ruby theme={"dark"}
client.sessions.attach_client_application(session_id, account.id)
client.sessions.clear_client_application(session_id)
```

```php PHP theme={"dark"}
$client->sessions()->attachClientApplication($sessionId, $account->id);
$client->sessions()->clearClientApplication($sessionId);
```

```bash cURL theme={"dark"}
curl -X PATCH https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"client_user_id":"user_123","client_application_id":"app_123"}'
```

A key you leave out keeps its current value. See the [Sessions API](https://usefoil.com/docs/api-reference/sessions.md) for the validation rules.

## Policy patterns

| Pattern | When to use | Example |
| - | - | - |
| **Report only** | First week of integration | Log verdicts, don't block anyone |
| **Soft challenge** | `inconclusive` on sensitive endpoints | Show CAPTCHA or require email verification |
| **Hard block** | `bot` on signup, checkout, scraping | Return 403 immediately |
| **Rate control** | Repeated fingerprints | Slow down instead of blocking |

> [!TIP]
>
> Start in report-only mode. Once you understand your traffic's verdict distribution, gradually enable enforcement.

## What's next

* [Testing your integration](https://usefoil.com/docs/testing.md) - simulate bot traffic and debug
* [Going to production](https://usefoil.com/docs/going-to-production.md) - rollout checklist
* [Verdicts & scoring](https://usefoil.com/docs/verdicts-and-scoring.md) - understand what scores mean
* [Sessions API](https://usefoil.com/docs/api-reference/sessions.md) - full API reference


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.