# Security Plugin (sentinel) (/docs/infrastructure/plugins/sentinel)

The `sentinel()` plugin provides comprehensive security and abuse protection for your authentication system. It detects and prevents various attack vectors including credential stuffing, impossible travel, free trial abuse, and more.



## Installation [#installation]

```tsx
import { betterAuth } from "better-auth";
import { sentinel } from "@better-auth/infra";

export const auth = betterAuth({
  plugins: [
    sentinel({
      security: {
        // Configure security features here
      },
    }),
  ],
});
```

## Configuration Options [#configuration-options]

### SentinelOptions [#sentineloptions]

| Option            | Type                   | Description                                                                                                                                                                                                          |
| ----------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiUrl`          | `string`               | Better Auth infrastructure API URL. Default: `https://dash.better-auth.com`                                                                                                                                          |
| `kvUrl`           | `string`               | Better Auth identification infrastructure URL. Default: `https://kv.better-auth.com`                                                                                                                                 |
| `apiKey`          | `string`               | Your API key for authentication. Falls back to `BETTER_AUTH_API_KEY` in env.                                                                                                                                         |
| `apiOptions`      | `object`               | Dash API HTTP options. Accepts `timeout?: number` (ms, default `3000`) and `headers?: Record<string, string>`.                                                                                                       |
| `kvOptions`       | `object`               | KV HTTP options. Accepts `timeout?: number` (ms, default `1000`), `retry?: { attempts?: number; baseDelay?: number; maxDelay?: number }`, and `headers?: Record<string, string>`.                                    |
| `apiTimeout`      | `number`               | Deprecated alias for `apiOptions.timeout`.                                                                                                                                                                           |
| `kvTimeout`       | `number`               | Deprecated alias for `kvOptions.timeout`.                                                                                                                                                                            |
| `sentinelHeaders` | `"legacy" \| "modern"` | PoW challenge headers the server writes. `"modern"` also writes `X-Sentinel-PoW-*` and does not change identify reads. Does not have to match the client. See [Protocol headers](#protocol-headers-sentinelheaders). |
| `security`        | `SecurityOptions`      | Security feature configuration.                                                                                                                                                                                      |

### SecurityOptions [#securityoptions]

```ts
interface SecurityOptions {
  unknownDeviceNotification?: boolean;
  credentialStuffing?: CredentialStuffingConfig;
  impossibleTravel?: ImpossibleTravelConfig;
  geoBlocking?: GeoBlockingConfig;
  botBlocking?: boolean | { action: SecurityAction };
  suspiciousIpBlocking?: boolean | { action: SecurityAction };
  velocity?: VelocityConfig;
  freeTrialAbuse?: FreeTrialAbuseConfig;
  compromisedPassword?: CompromisedPasswordConfig;
  emailValidation?: EmailValidationConfig;
  emailNormalization?: { enabled?: boolean };
  staleUsers?: StaleUsersConfig;
  challengeDifficulty?: number;
}

type SecurityAction = "log" | "challenge" | "block";
```

## Security Features [#security-features]

### Credential Stuffing Protection [#credential-stuffing-protection]

Detects and blocks credential stuffing attacks by tracking failed login attempts per visitor.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    credentialStuffing: {
      enabled: true,
      action: "challenge", // optional default action; thresholds still drive challenge vs block
      thresholds: {
        challenge: 3,  // Issue PoW challenge after 3 failures
        block: 5,      // Block after 5 failures
      },
      windowSeconds: 3600,     // 1 hour window
      cooldownSeconds: 900,    // 15 minute cooldown after block
    },
  },
}),
```

**How it works:**

1. Tracks failed login attempts per visitor ID
2. After reaching the challenge threshold, issues a Proof-of-Work challenge
3. After reaching the block threshold, blocks the visitor entirely
4. Automatically clears failed attempts on successful login

### Impossible Travel Detection [#impossible-travel-detection]

Detects logins from geographically distant locations in impossibly short timeframes.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    impossibleTravel: {
      enabled: true,
      maxSpeedKmh: 1000,    // Max realistic travel speed
      action: "challenge",  // "log", "challenge", or "block"
    },
  },
}),
```

**Example:** If a user logs in from New York and then 30 minutes later from Tokyo, this would be flagged as impossible travel (would require traveling faster than 1000 km/h).

### Free Trial Abuse Prevention [#free-trial-abuse-prevention]

Prevents users from creating multiple accounts to abuse free trials using device fingerprinting.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    freeTrialAbuse: {
      enabled: true,
      thresholds: {
        challenge: 2,
        block: 3,
      },
      maxAccountsPerVisitor: 3,
      retentionSeconds: 90 * 24 * 60 * 60, // optional; default 90 days
      action: "block",
    },
  },
}),
```

**How it works:**

1. Tracks account creations per visitor fingerprint
2. When threshold is exceeded, blocks new account creation
3. Useful for preventing free tier abuse

`retentionSeconds` controls how long per-visitor signup ledger keys are kept (sliding window). Default is 90 days; the platform clamps values to between 1 day and 365 days.

### Compromised Password Detection [#compromised-password-detection]

Checks passwords against the HaveIBeenPwned database to detect compromised credentials.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    compromisedPassword: {
      enabled: true,
      action: "block",      // "log", "challenge", or "block"
      minBreachCount: 1,    // Minimum breaches to trigger
    },
  },
}),
```

**Privacy:** Uses k-anonymity - only the first 5 characters of the password hash are sent to the API, never the full password.

### Stale Account Monitoring [#stale-account-monitoring]

Detects when dormant accounts suddenly become active, which could indicate account takeover.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    staleUsers: {
      enabled: true,
      staleDays: 90,           // Account considered stale after 90 days
      action: "log",           // "log", "challenge", or "block"
      notifyUser: true,        // Send email to user
      notifyAdmin: true,       // Send email to admin
      adminEmail: "admin@yourapp.com",
    },
  },
}),
```

**Notifications include:**

* Login time and location
* Days since last activity
* Device information

### Geo-Blocking [#geo-blocking]

Block or challenge users from specific countries.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    geoBlocking: {
      allowList: ["US", "CA", "GB"],  // Only allow these countries
      // OR
      denyList: ["XX", "YY"],          // Block these countries
      action: "block",                  // "challenge" or "block"
    },
  },
}),
```

Use ISO 3166-1 alpha-2 country codes.

### Bot Blocking [#bot-blocking]

Detect and block automated bot traffic.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    botBlocking: true,
    // OR with custom action
    botBlocking: {
      action: "challenge",  // "log", "challenge", or "block"
    },
  },
}),
```

### Suspicious IP Detection [#suspicious-ip-detection]

Block requests from known malicious IP addresses.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    suspiciousIpBlocking: true,
    // OR with custom action
    suspiciousIpBlocking: {
      action: "block",
    },
  },
}),
```

### Velocity / Rate Limiting [#velocity--rate-limiting]

Limit the rate of various operations.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    velocity: {
      enabled: true,
      thresholds: {
        challenge: 10,
        block: 20,
      },
      maxSignupsPerVisitor: 5,
      maxPasswordResetsPerIp: 10,
      maxSignInsPerIp: 50,
      windowSeconds: 3600,
      action: "challenge",
    },
  },
}),
```

### Email Validation [#email-validation]

Block disposable email addresses and validate email domains.

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    emailValidation: {
      enabled: true,
      strictness: "medium",  // "low", "medium", or "high"
      action: "block",
      domainAllowlist: ["company.com", "partner.org"], // always allow these domains
    },
  },
}),
```

**Strictness levels:**

* `low` - Block only known disposable domains
* `medium` - Also check for valid MX records
* `high` - Additional heuristic checks

`domainAllowlist` skips disposable/heuristic checks for the listed domains (exact domain match).

### Email normalization [#email-normalization]

Sentinel can normalize email addresses before sign-up and sign-in so aliases and provider quirks do not create duplicate accounts or mismatched logins. Normalization includes lowercasing, stripping plus-address tags on common providers (for example `user+tag@gmail.com` → `user@gmail.com`), removing dots in Gmail-style addresses, and mapping `googlemail.com` to `gmail.com`.

Use `security.emailNormalization` when you want to control this separately from disposable-domain validation (`emailValidation`):

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    emailValidation: {
      enabled: false, // skip disposable / MX checks
    },
    emailNormalization: {
      enabled: true, // still normalize for deduplication and consistent sign-in
    },
  },
}),
```

## Protocol headers (`sentinelHeaders`) [#protocol-headers-sentinelheaders]

Sentinel carries visitor identity and PoW challenges over HTTP headers. `sentinelHeaders` chooses the names `sentinel()`, `sentinelClient()`, and `sentinelNativeClient()` write. Default: `"legacy"`. Server and client settings are independent.

| Role          | `"legacy"` (default) | `"modern"`                 |
| ------------- | -------------------- | -------------------------- |
| Request id    | `X-Request-Id`       | `X-Sentinel-Request-Id`    |
| Visitor id    | `X-Visitor-Id`       | `X-Sentinel-Visitor-Id`    |
| PoW challenge | `X-PoW-Challenge`    | `X-Sentinel-PoW-Challenge` |
| PoW reason    | `X-PoW-Reason`       | `X-Sentinel-PoW-Reason`    |
| PoW solution  | `X-PoW-Solution`     | `X-Sentinel-PoW-Solution`  |

Clients write only that family. A request id is sent only after identify succeeds.

A `"modern"` server still sends `X-PoW-Challenge` and `X-PoW-Reason`, and also sends `X-Sentinel-PoW-Challenge` and `X-Sentinel-PoW-Reason`, so an older client can read the challenge. That does not change identify or PoW solution reads. A `"legacy"` server sends only `X-PoW-*`.

Visitor id, PoW challenge, PoW reason, and PoW solution are read from `X-Sentinel-*` first, then the legacy name. The identify request id is stricter: `X-Sentinel-Request-Id` wins even when the server option is `"legacy"`. `X-Request-Id` is used only when `X-Visitor-Id` is set and `X-Sentinel-Visitor-Id` is not. A bare `X-Request-Id` is ignored. So is `X-Request-Id` beside `X-Sentinel-Visitor-Id` when `X-Sentinel-Request-Id` is missing: the client omitted the id because identify was not stored.

<Callout type="warn">
  Proxies such as Envoy often set or replace `X-Request-Id`, and the server cannot tell that apart from a legacy client's value. Leave an incoming `X-Request-Id` unchanged, and do not add one when the client omitted it. If the proxy replaces it, set `sentinelHeaders: "modern"` on `sentinelClient()` and `sentinelNativeClient()`. The server option does not fix that, and forwarding the proxy's id is not a substitute.

  Until every client sends `X-Sentinel-*`, pass the client's `X-Request-Id` (do not replace it), `X-Visitor-Id`, and `X-PoW-Solution`, plus `X-Sentinel-Request-Id`, `X-Sentinel-Visitor-Id`, and `X-Sentinel-PoW-Solution`. A legacy `X-Request-Id` counts only when `X-Visitor-Id` is also present. Do not strip `X-PoW-*` or `X-Sentinel-PoW-*` on the response, and do not copy a proxy id into `X-Sentinel-Request-Id`. Same-origin and native clients do not use the CORS list below. Do not turn security checks off to work around a rewritten `X-Request-Id`.
</Callout>

```ts title="auth-client.ts"
sentinelClient({
  // When a proxy rewrites X-Request-Id. Independent of the server option.
  sentinelHeaders: "modern",
  autoSolveChallenge: true,
})
```

```ts title="auth-client.native.ts"
sentinelNativeClient({
  sentinelHeaders: "modern",
  autoSolveChallenge: true,
})
```

```ts title="auth.ts"
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  // Optional. Dual-writes challenge headers. Does not change identify reads.
  sentinelHeaders: "modern",
})
```

### Cross-origin CORS [#cross-origin-cors]

Same-origin browser apps and native clients do not need CORS for these headers. Cross-origin browser clients do: list the **exact** names. `Access-Control-Allow-Headers: *` and `Access-Control-Expose-Headers: *` do not apply to credentialed requests.

Allow the request headers your clients send, and expose the challenge headers your server returns. The browser can only read exposed names, and a `"legacy"` server does not send `X-Sentinel-PoW-*`.

| Who writes        | Allow on preflight (request)                                                | Expose on response                                                                     |
| ----------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Legacy client     | `X-Request-Id`, `X-Visitor-Id`, `X-PoW-Solution`                            | —                                                                                      |
| Modern client     | `X-Sentinel-Request-Id`, `X-Sentinel-Visitor-Id`, `X-Sentinel-PoW-Solution` | —                                                                                      |
| Server `"legacy"` | —                                                                           | `X-PoW-Challenge`, `X-PoW-Reason`                                                      |
| Server `"modern"` | —                                                                           | `X-PoW-Challenge`, `X-PoW-Reason`, `X-Sentinel-PoW-Challenge`, `X-Sentinel-PoW-Reason` |

While any browser client or the server is still `"legacy"`, allow and expose both families. A modern-only allow list drops legacy browser clients. Exposing only `X-Sentinel-PoW-*` hides challenges from a `"legacy"` server.

After every browser client sends only `X-Sentinel-*`, you can drop the legacy names from `allowedHeaders`. Drop `X-PoW-Challenge` and `X-PoW-Reason` from `exposedHeaders` only when the server is `"modern"` and `X-Sentinel-PoW-Challenge` and `X-Sentinel-PoW-Reason` are already exposed.

```ts
{
  // Your real app origin only — not "*"
  // Both families while any browser client or the server is still "legacy".
  origin: "https://app.example.com",
  credentials: true,
  allowedHeaders: [
    "Content-Type",
    "Authorization",
    "X-Request-Id",
    "X-Visitor-Id",
    "X-PoW-Solution",
    "X-Sentinel-Request-Id",
    "X-Sentinel-Visitor-Id",
    "X-Sentinel-PoW-Solution",
  ],
  exposedHeaders: [
    "X-PoW-Challenge",
    "X-PoW-Reason",
    "X-Sentinel-PoW-Challenge",
    "X-Sentinel-PoW-Reason",
  ],
}
```

<Callout type="warn">
  Restrict CORS to origins you control (see [trusted origins](/docs/reference/security#trusted-origins)). Do not use `origin: "*"` with credentialed requests, and do not turn off origin or CSRF checks to make these headers succeed.
</Callout>

## Proof-of-Work Challenges [#proof-of-work-challenges]

When a security check results in a "challenge" action, Sentinel issues a Proof-of-Work (PoW) challenge that must be solved by the client.

### How PoW Works [#how-pow-works]

1. Server issues a cryptographic challenge
2. Client must find a solution that satisfies difficulty requirements
3. Solution is computationally expensive but verification is fast
4. Prevents automated attacks while allowing legitimate users through

### Challenge Difficulty [#challenge-difficulty]

```ts
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    challengeDifficulty: 18,  // Default difficulty level
  },
}),
```

Higher difficulty = more computation required = slower for attackers.

## Client Integration [#client-integration]

### sentinelClient() [#sentinelclient]

The client plugin handles device fingerprinting and automatic PoW challenge solving.

```ts
import { createAuthClient } from "better-auth/client";
import { sentinelClient } from "@better-auth/infra/client";

export const authClient = createAuthClient({
  plugins: [
    sentinelClient({
      autoSolveChallenge: true,
    }),
  ],
});
```

### Configuration [#configuration]

| Option                | Type                            | Default                                                                    | Description                                                                                                                                                                                                                     |
| --------------------- | ------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `identifyUrl`         | `string`                        | `BETTER_AUTH_KV_URL` or `https://kv.better-auth.com`                       | Base URL for the identify endpoint.                                                                                                                                                                                             |
| `identifyOptions`     | `object`                        | `{ timeout: 1000, retry: { attempts: 2, baseDelay: 400, maxDelay: 600 } }` | Identify HTTP timeout and retry policy.                                                                                                                                                                                         |
| `sentinelHeaders`     | `"legacy" \| "modern"`          | `"legacy"`                                                                 | Header names the client sends. `"modern"` sends only `X-Sentinel-*`. Does not have to match the server. Set this on the client when a proxy rewrites `X-Request-Id`. See [Protocol headers](#protocol-headers-sentinelheaders). |
| `autoSolveChallenge`  | `boolean`                       | `true`                                                                     | Automatically solve PoW challenges.                                                                                                                                                                                             |
| `kvTimeout`           | `number`                        | `1000`                                                                     | Deprecated alias for `identifyOptions.timeout`.                                                                                                                                                                                 |
| `onChallengeReceived` | `(reason: string) => void`      | —                                                                          | Called when a PoW challenge is received.                                                                                                                                                                                        |
| `onChallengeSolved`   | `(solveTimeMs: number) => void` | —                                                                          | Called after a successful solve.                                                                                                                                                                                                |
| `onChallengeFailed`   | `(error: Error) => void`        | —                                                                          | Called if solving fails.                                                                                                                                                                                                        |

### Browser Fingerprinting [#browser-fingerprinting]

The client sends a visitor id on each request, and a request id after identify succeeds ([header names](#protocol-headers-sentinelheaders)). Security checks use the visitor id stored with that identify record, not the visitor header by itself. That record is what Sentinel uses for:

* Credential stuffing detection
* Free trial abuse prevention
* Device tracking

### PoW Solution Header [#pow-solution-header]

When auto-solving is enabled, the retry sends the solution on `X-PoW-Solution`, or `X-Sentinel-PoW-Solution` when the client uses `"modern"`. The server accepts either name.

### Expo and React Native [#expo-and-react-native]

For **Expo** and **React Native** apps, use `sentinelNativeClient` from `@better-auth/infra/native` instead of using `@better-auth/infra/client`.

For **React Native** apps, install the following peer dependencies:

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install @react-native-async-storage/async-storage react-native-get-random-values
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add @react-native-async-storage/async-storage react-native-get-random-values
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add @react-native-async-storage/async-storage react-native-get-random-values
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add @react-native-async-storage/async-storage react-native-get-random-values
    ```
  </CodeBlockTab>
</CodeBlockTabs>

`@react-native-async-storage/async-storage` is optional. If it is not installed, the client uses a session-only in-memory visitor ID. For production, install it or pass a custom `storage` (for example a secure store).

#### Example [#example]

```ts
import { createAuthClient } from "better-auth/client";
import { dashClient, sentinelNativeClient } from "@better-auth/infra/native";

export const authClient = createAuthClient({
  baseURL: "https://your-api.example.com",
  plugins: [
    dashClient(),
    sentinelNativeClient({
      autoSolveChallenge: true,
    }),
  ],
});
```

For **Expo** apps, install the packages below for richer native identity payloads.

<Callout type="info">
  **Expo:** Follow the [Expo integration](/docs/integrations/expo) before adding infrastructure plugins.
</Callout>

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install expo-constants expo-device expo-crypto
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add expo-constants expo-device expo-crypto
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add expo-constants expo-device expo-crypto
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add expo-constants expo-device expo-crypto
    ```
  </CodeBlockTab>
</CodeBlockTabs>

#### Example [#example-1]

```ts
import { createAuthClient } from "better-auth/react";
import { expoClient } from "@better-auth/expo/client";
import { dashClient, sentinelNativeClient } from "@better-auth/infra/native";
import * as SecureStore from "expo-secure-store";

export const authClient = createAuthClient({
  baseURL: "https://your-api.example.com",
  plugins: [
    expoClient({
      scheme: "myapp",
      storagePrefix: "myapp",
      storage: SecureStore,
    }),
    dashClient(),
    sentinelNativeClient({
      autoSolveChallenge: true,
    }),
  ],
});
```

#### `sentinelNativeClient` options [#sentinelnativeclient-options]

| Option                | Type                            | Default                                                                    | Description                                                                                                                                                                                                                     |
| --------------------- | ------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `identifyUrl`         | `string`                        | `BETTER_AUTH_KV_URL`, then `https://kv.better-auth.com`                    | Identify endpoint base URL.                                                                                                                                                                                                     |
| `identifyOptions`     | `object`                        | `{ timeout: 1000, retry: { attempts: 2, baseDelay: 400, maxDelay: 600 } }` | Identify HTTP timeout and retry policy.                                                                                                                                                                                         |
| `sentinelHeaders`     | `"legacy" \| "modern"`          | `"legacy"`                                                                 | Header names the client sends. `"modern"` sends only `X-Sentinel-*`. Does not have to match the server. Set this on the client when a proxy rewrites `X-Request-Id`. See [Protocol headers](#protocol-headers-sentinelheaders). |
| `kvTimeout`           | `number`                        | `1000`                                                                     | Deprecated alias for `identifyOptions.timeout`.                                                                                                                                                                                 |
| `autoSolveChallenge`  | `boolean`                       | `true`                                                                     | On `423` with a PoW challenge header, solve and retry once with the solution header.                                                                                                                                            |
| `onChallengeReceived` | `(reason: string) => void`      | —                                                                          | Called when a PoW challenge is received.                                                                                                                                                                                        |
| `onChallengeSolved`   | `(solveTimeMs: number) => void` | —                                                                          | Called after a successful solve.                                                                                                                                                                                                |
| `onChallengeFailed`   | `(error: Error) => void`        | —                                                                          | Called if solving fails.                                                                                                                                                                                                        |
| `storage`             | `{ getItem, setItem }`          | Async Storage when installed                                               | Persistent async storage for a stable per-install visitor ID.                                                                                                                                                                   |

## Security Events [#security-events]

Sentinel records security activity as audit events:

| Event Type        | Description                                                                                                                                                |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `security_check`  | One event per protected user action. `eventData.outcome` is `passed`, `challenged`, or `blocked`. Includes `evaluatedChecks`, `triggeredBy`, and `reason`. |
| `security_signal` | Informational detection detail for the Security dashboard. Does not count toward security usage.                                                           |

These events are visible in the Security dashboard and included in [audit logs](/docs/infrastructure/plugins/audit-logs).

## Complete Example [#complete-example]

```ts
import { betterAuth } from "better-auth";
import { sentinel } from "@better-auth/infra";

export const auth = betterAuth({
  plugins: [
    sentinel({
      apiKey: process.env.BETTER_AUTH_API_KEY,
      security: {
        // Core protections
        credentialStuffing: {
          enabled: true,
          thresholds: { challenge: 3, block: 5 },
        },
        compromisedPassword: {
          enabled: true,
          action: "block",
        },
        emailValidation: {
          enabled: true,
          strictness: "medium",
          action: "block",
        },
        
        // Location-based
        impossibleTravel: {
          enabled: true,
          action: "challenge",
        },
        geoBlocking: {
          denyList: ["XX"],
          action: "block",
        },
        
        // Abuse prevention
        freeTrialAbuse: {
          enabled: true,
          maxAccountsPerVisitor: 3,
          action: "block",
        },
        velocity: {
          enabled: true,
          maxSignupsPerVisitor: 5,
          action: "challenge",
        },
        
        // Bot protection
        botBlocking: { action: "challenge" },
        suspiciousIpBlocking: { action: "block" },
        
        // Account monitoring
        staleUsers: {
          enabled: true,
          staleDays: 90,
          notifyUser: true,
          notifyAdmin: true,
          adminEmail: "security@yourapp.com",
        },
      },
    }),
  ],
});
```

## Best Practices [#best-practices]

1. **Start with logging** - Set actions to "log" initially to understand your traffic patterns before blocking.

2. **Tune thresholds** - Every application is different. Monitor false positives and adjust thresholds accordingly.

3. **Use challenges before blocks** - Challenges allow legitimate users through while stopping automated attacks.

4. **Enable client-side auto-solve** - Use `sentinelClient({ autoSolveChallenge: true })` in the browser, or `sentinelNativeClient({ autoSolveChallenge: true })` in Expo / React Native.

5. **Monitor security events** - Regularly review the Security dashboard to identify attack patterns.

6. **Set up admin notifications** - Enable `notifyAdmin` for critical events like stale account reactivations.

## Troubleshooting [#troubleshooting]

### Missing API Key Warning [#missing-api-key-warning]

```
[Sentinel] Missing BETTER_AUTH_API_KEY. Security checks may fall back to allow mode.
```

Make sure your API key environment variable is set correctly.

### Challenges Not Working [#challenges-not-working]

If PoW challenges aren't being solved:

1. Verify the correct client plugin: `sentinelClient()` for web (`@better-auth/infra/client`), or `sentinelNativeClient()` for Expo / React Native (`@better-auth/infra/native`)
2. Check that `autoSolveChallenge` is `true`
3. Ensure the client can reach the server
4. Cross-origin, expose the challenge headers the server returns (`X-PoW-*`, plus `X-Sentinel-PoW-*` when the server is `"modern"`). Exact names, not `*`. See [Protocol headers](#protocol-headers-sentinelheaders).

### High False Positive Rate [#high-false-positive-rate]

If legitimate users are being blocked:

1. Increase thresholds
2. Change action from "block" to "challenge"
3. Review security events to identify patterns

