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

# API keys

> Create scoped API keys with `kavach.apiKeys.create()`, validate on every request, revoke by ID, and rotate to a new secret without changing the key's permission set.

## Setup

```ts theme={"system"}
import { createKavach } from 'kavachos';

const kavach = await createKavach({
  database: { provider: 'sqlite', url: 'kavach.db' },
  apiKeys: { // [!code highlight]
    prefix: 'kos_',          // default // [!code highlight]
    defaultExpiryDays: 90,   // default: 365 // [!code highlight]
  }, // [!code highlight]
});
```

## Creating a key

```ts theme={"system"}
const { key, apiKey } = await kavach.apiKeys.create({
  userId: 'user_abc',
  name: 'CI deploy token',
  permissions: ['agents:read', 'agents:create'], // [!code highlight]
  expiresAt: new Date('2026-01-01'),  // optional, falls back to defaultExpiryDays // [!code highlight]
});

// key = 'kos_a3f8c2e1...', the full secret, returned once only
// apiKey.id, apiKey.prefix, apiKey.permissions, apiKey.expiresAt
```

<Warning>
  The full key is never stored. Show it to the user immediately after creation, it cannot be recovered later. Only a SHA-256 hash is kept in the database.
</Warning>

## Validating a key

```ts theme={"system"}
const result = await kavach.apiKeys.validate('kos_a3f8c2e1...');
if (result) {
  // result.userId, result.permissions, result.keyId
}
```

Validation updates `lastUsedAt` asynchronously without blocking the response.

## Listing and revoking

```ts theme={"system"}
// All keys for a user (no secrets exposed)
const keys = await kavach.apiKeys.list('user_abc');

// Revoke by key ID
await kavach.apiKeys.revoke('key_...');
```

## Rotating a key

Rotation revokes the existing key and creates a new one with the same name and permissions:

```ts theme={"system"}
const { key, apiKey } = await kavach.apiKeys.rotate('key_...');
// key = new full secret, store it now
```

## Endpoints

| Method | Path                           | Description        |
| ------ | ------------------------------ | ------------------ |
| POST   | `/auth/api-keys`               | Create API key     |
| GET    | `/auth/api-keys/:userId`       | List keys for user |
| DELETE | `/auth/api-keys/:keyId`        | Revoke key         |
| POST   | `/auth/api-keys/:keyId/rotate` | Rotate key         |
