> ## 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.

# Authentication

> Authenticate Foil API requests with publishable and secret keys, including Bearer token usage, key scopes, environments, rotation, and revocation.

Foil uses `Authorization: Bearer <token>` for every authenticated request. The token format signals what the key is for and what it can do.

## Key types

Two distinct credential types exist on the public API. Each has a different prefix, lives in a different place, and authorizes a different set of endpoints.

| Prefix | Lives in | Authorizes |
| - | - | - |
| `pk_live_*`, `pk_test_*` | Browser bundles and mobile apps (public by design) | The Collect API endpoints that the browser and mobile SDKs use to open a session, stream observation batches, and mint a sealed handoff. |
| `sk_live_*`, `sk_test_*` | Your server only | The REST endpoints that the key's [scopes](#scopes) allow: session and fingerprint readback, agent IP rotation, organization and API key management, and webhooks and events. |

One endpoint needs no key: `GET /v2/collect/pings/:pingId`.

> [!WARNING]
>
> Secret keys (`sk_*`) have read access to your session history and visitor fingerprint data, and depending on their scopes they can manage your API keys and webhooks. Never commit one to git, send it over a non-TLS channel, or ship it in a client bundle. If a secret key is ever exposed, [rotate it immediately](#rotating-a-key).

## Using a key

Send the key as a Bearer token on every request.

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

```javascript Node.js theme={"dark"}
const { Foil } = require("@abxy/foil-server");
const client = new Foil({ secretKey: process.env.FOIL_SECRET_KEY });

const session = await client.sessions.get("sid_...");
```

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

client = Foil(secret_key=os.environ["FOIL_SECRET_KEY"])
session = client.sessions.get("sid_...")
```

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

client, err := foil.NewClient(foil.WithSecretKey(os.Getenv("FOIL_SECRET_KEY")))
if err != nil {
    return err
}
session, err := client.Sessions.Get(ctx, "sid_...")
```

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

client = Foil::Server::Client.new(secret_key: ENV["FOIL_SECRET_KEY"])
session = client.sessions.get("sid_...")
```

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

$client = new Client(secretKey: getenv("FOIL_SECRET_KEY") ?: null);
$session = $client->sessions()->get("sid_...");
```

If the `Authorization` header is missing, the API returns `401` with `auth.missing_api_key`. If the header is malformed, or the key is unrecognized, revoked, or past the end of its rotation grace window, the API returns `401` with `auth.invalid_api_key`.

## Scopes

Publishable keys are limited to the Collect API, and secret keys are limited by scope. The endpoint decides which key type it accepts, and for secret keys it also decides which scope the key must carry.

### Publishable keys (`pk_*`)

A publishable key can call only the Collect API endpoints that the SDKs need:

* `POST /v2/collect/sessions` - open or resume an encrypted unified session
* `POST /v2/collect/sessions/:sessionId/documents/:documentId/batches` - stream observation batches
* `POST /v2/collect/sessions/:sessionId/documents/:documentId/results` - mint a sealed handoff for the current session

A publishable key can't read verdict data, list sessions, inspect fingerprints, or reach any management endpoint. Calling those endpoints with a publishable key returns `403` with `auth.secret_key_required`. There is no escalation path from `pk_*` to `sk_*` - the keys are fully partitioned.

#### Native publishable keys

Each publishable key has a `client_target`: `browser` (the default), `native-ios`, or `native-android`. A native key works only with the matching Foil mobile SDK on the `/v2/collect/sessions` endpoints. Any other use of a native key, including a request from a different client or to a different path, returns `403` with `auth.native_key_not_allowed`. Origin restrictions apply to browser keys only, and native keys can't define allowed origins.

### Secret keys (`sk_*`)

Each secret key carries a list of scopes, and each endpoint requires one scope. A request to an endpoint whose scope the key doesn't carry returns `403` with `auth.insufficient_scope`, and the error message names the missing scope. The scope `*` grants all current and future scopes.

A secret key with no stored scopes receives the default scopes `sessions:read`, `sessions:update`, and `fingerprints:read`. The defaults don't include `sessions:list` or `fingerprints:list`, so add those scopes if your integration lists sessions or fingerprints.

| Endpoint | Required scope |
| - | - |
| `GET /v1/sessions` | `sessions:list` |
| `GET /v1/sessions/:sessionId` | `sessions:read` |
| `PATCH /v1/sessions/:sessionId` | `sessions:update` |
| `GET /v1/fingerprints` | `fingerprints:list` |
| `GET /v1/fingerprints/:visitorId` | `fingerprints:read` |
| `POST /v1/agents/ip-rotation` | `agents:ip_rotation` |
| `POST /v1/organizations` | `organizations:create` |
| `GET /v1/organizations/:organizationId` | `organizations:read` |
| `PATCH /v1/organizations/:organizationId` | `organizations:update` |
| `GET /v1/organizations/:organizationId/api-keys` | `api_keys:read` |
| `POST`, `PATCH`, and `DELETE` on `/v1/organizations/:organizationId/api-keys`, and `POST` on `.../api-keys/:keyId/rotations` | `api_keys:manage` |
| `GET` on `/v1/organizations/:organizationId/webhooks/endpoints`, `GET /v1/organizations/:organizationId/events`, and `GET /v1/organizations/:organizationId/events/:eventId` | `webhooks:read` |
| `POST`, `PATCH`, and `DELETE` on `/v1/organizations/:organizationId/webhooks/endpoints`, plus `.../rotations` and `.../test` | `webhooks:manage` |

Foil accepts secret keys only on the REST endpoints in this table. Calling a Collect API endpoint with a secret key returns `403` with `auth.secret_key_not_allowed`.

The `/v1/organizations/:organizationId/...` endpoints work only for the organization that owns the calling key. A request for any other organization returns `403` with `auth.organization_access_denied`. See [Organizations](https://usefoil.com/docs/api-reference/organizations.md) for the full list of scopes.

Secret keys on test mode (`sk_test_*`) and live mode (`sk_live_*`) operate on separate data. They authorize the same endpoints, except the live-only endpoints listed under [Live and test environments](#live-and-test-environments).

## Live and test environments

Each organization has separate live and test key pairs. They share the same REST surface but are fully isolated:

* Sessions minted under `pk_test_*` cannot be read back with `sk_live_*`, and vice versa.
* Organization, billing, and member state is the same across both environments. Sessions and fingerprints are separate.
* A test secret key can manage only test keys. Creating, changing, rotating, or revoking a live key needs a live secret key; a test key gets `403` with `auth.live_key_required`.
* The webhook endpoints, the events endpoints, and `PATCH /v1/organizations/:organizationId` need a live secret key. Webhook endpoints receive live events, events carry live payloads, and an organization status change affects live traffic. A test key gets `403` with `auth.live_key_required`, but it can still call `GET /v1/organizations/:organizationId`.
* Test-mode sessions may expose richer debug detail in internal tooling and the dashboard; the public browser handoff stays opaque regardless of environment.

Use test mode for automated integration tests, development, and CI. Use live mode when you ship.

## Origin restrictions

Browser publishable keys can be narrowed to a list of allowed origins in the dashboard or through the [API keys endpoints](https://usefoil.com/docs/api-reference/organizations.md#origin-rules). A `pk_live_*` limited to `https://yourdomain.com` is rejected with `auth.origin_not_allowed` when presented from any other origin, or without an `Origin` header, so a leaked key is only as dangerous as the origins it's allowed to speak for. A key with no allowed origins accepts any origin.

Restrict every production publishable key to the exact hostnames you load `t.js` from. Allow wildcards only on test keys.

> [!NOTE]
>
> Secret keys are not origin-restricted - they're meant for server-to-server traffic where the caller's "origin" is your infrastructure. Control where they're used by keeping them on the server side and not shipping them into the browser.

## Rotating a key

Rotation issues a new key with the same type, environment, name, origins, client target, and scopes. The old key keeps working for a 24-hour grace window. This lets you roll new secrets into deployment before the old one stops - no flight of 401s during the overlap.

```bash theme={"dark"}
curl -X POST https://api.usefoil.com/v1/organizations/org_.../api-keys/key_.../rotations \
  -H "Authorization: Bearer sk_live_..."
```

During the grace window the old key has the status `rotating`, and its `grace_expires_at` field shows when it stops working. When the window ends, Foil revokes the old key automatically. While it is rotating, the old key can read data and authenticate collection but can't change keys, organizations, or webhook endpoints, and it can't be rotated again. If you're rotating because a key leaked, revoke the old key as soon as the replacement is deployed.

Recommended rotation flow:

1. Call the rotation endpoint. You receive the new key material in the response.
2. Deploy the new key to all environments that use the old one.
3. Verify the new key is in use (e.g. by inspecting logs or a dashboard request count).
4. Optionally revoke the old key without waiting for the grace window to end.

See [API keys](https://usefoil.com/docs/api-reference/organizations.md) for the full request and response shapes.

## Revoking a key

Revocation is unconditional. When you revoke a key, Foil notifies its API servers. Each server stops accepting your key as soon as the notice reaches it. A server that misses the notice stops accepting your key within about 15 seconds. Changes to your key's scopes or allowed origins take up to about 15 seconds to apply.

Foil checks your key against its database. If Foil can't reach its database, its servers keep accepting a key they verified recently. A publishable key keeps working for up to 2 minutes, and a secret key for up to 1 minute. During that time, a revoked key can keep working on a server that missed the revocation notice.

If Foil can't check your key at all, you get a retryable `503` response with the `internal.unavailable` code and a `Retry-After` header. You don't get a `401`. See [Errors](https://usefoil.com/docs/api-reference/errors.md#http-status-codes).

```bash theme={"dark"}
curl -X DELETE https://api.usefoil.com/v1/organizations/org_.../api-keys/key_... \
  -H "Authorization: Bearer sk_live_..."
```

If you believe a secret key has been exposed, revoke first and investigate second. The rotation flow above is for planned, graceful transitions; revocation is for incidents.

## Rate limits

Foil applies rate limits per organization, key type, and environment. The limit belongs to the organization, not to an individual key. By default, all of an organization's live secret keys share one limit of `600` requests per 60-second window, and all of its live publishable keys share one limit of `3000` requests per 60-second window. Test keys have separate limits of the same size. Each source can use only part of the publishable-key limit. Foil support can configure organization-level overrides when a production integration needs more headroom.

Responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Cost` headers. Rate-limited responses are `429 Too Many Requests` and include a `Retry-After` header. See [Rate limits](https://usefoil.com/docs/api-reference/rate-limits.md) for how the window works, what counts against it, and how to retry.

## What's next

> [card] [Errors](https://usefoil.com/docs/api-reference/errors.md)
>
> Error envelope shape, status codes, and retry semantics.

> [card] [Pagination](https://usefoil.com/docs/api-reference/pagination.md)
>
> How list endpoints paginate and filter.

> [card] [Security and privacy](https://usefoil.com/docs/privacy-and-data.md)
>
> How keys are protected end-to-end.

> [card] [Sessions](https://usefoil.com/docs/api-reference/sessions.md)
>
> First authenticated endpoint most integrations hit.


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