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

# Authentication

> Authentication system for OnDB

OnDB uses two key types to authenticate application operations and autonomous agent operations.

## Key Types

<CardGroup cols={2}>
  <Card title="App Key (X-App-Key)" icon="building">
    * Required for write operations
    * Identifies the application
    * Used for app-level permissions
  </Card>

  <Card title="Agent Key (X-Agent-Key)" icon="robot">
    * App Key with Pay permission
    * Enables autonomous agents to pay other apps inline
    * Configurable spend limits and target app whitelisting
  </Card>
</CardGroup>

## Configuration

```typescript TypeScript theme={null}
import { createClient } from '@ondb/sdk';

const client = createClient({
  endpoint: 'https://api.ondb.io',
  appId: 'my_app',
  appKey: 'app_xxx...' // For writes
});
```

## App Key Permissions

App Keys support a four-tier permission system, allowing you to create keys with granular access control:

<CardGroup cols={2}>
  <Card title="Read" icon="eye">
    * Query data
    * Read documents
    * Access collections
    * View indexes
  </Card>

  <Card title="Write" icon="pen">
    * Store data
    * Update documents
    * Delete documents
    * Create collections
  </Card>

  <Card title="Admin" icon="shield">
    * Manage indexes
    * Configure encryption
    * App-level settings
    * Full access
  </Card>

  <Card title="Pay" icon="wallet">
    * Agent Key permission
    * Pay other apps inline via USDC
    * Configurable spend limits
    * Target app whitelisting
  </Card>
</CardGroup>

When generating an App Key from the Dashboard, you can select any combination of these permissions:

| Permission Combination | Use Case                                 |
| ---------------------- | ---------------------------------------- |
| Read only              | Public APIs, analytics dashboards        |
| Read + Write           | Standard application backend             |
| Read + Write + Admin   | Full application management              |
| Write only             | Data ingestion pipelines                 |
| Read + Write + Pay     | Autonomous AI agents accessing paid data |

<Tip>
  Create separate keys with minimal permissions for different parts of your application. A read-only key for your frontend proxy and a write key for your backend services.
</Tip>

## Agent Keys

An Agent Key is an App Key with the `Pay` permission. It enables autonomous agents to pay other apps inline when storing or querying their data, using USDC.

### Generating an Agent Key

```typescript theme={null}
// Via API
const response = await fetch(`${endpoint}/api/apps/${agentAppId}/regenerate-key`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    permissions: ['Pay'],
    pay_limits: {
      max_payment_per_tx: 1_000_000,       // 1 USDC max per transaction
      spend_allowance: 50_000_000,          // 50 USDC lifetime cap
      expires_at: '2026-06-01',             // Key expiry
      allowed_target_apps: ['target_app']   // Whitelist (omit to allow all)
    }
  })
});
// Key is returned once and never stored -- save it immediately
```

### Using an Agent Key

```typescript TypeScript theme={null}
import { createClient } from '@ondb/sdk';

const agent = createClient({
  endpoint: 'https://api.ondb.io',
  appId: 'my_agent_app',
  agentKey: 'app_a3f9...'  // X-Agent-Key header — key must have Pay permission
});

// Write to another app's collection -- payment is automatic
await agent.store({
  collection: 'target_app::data',
  data: [{ content: 'example' }]
});

// Read from another app's collection
const result = await agent.queryBuilder()
  .collection('target_app::premium_data')
  .selectAll()
  .execute();
```

### How Agent Auto-Pay Works

**Writes**: The broker handles payment automatically in a background task:

```
1. Agent sends POST /store with X-Agent-Key header
2. Pre-flight: verify Pay permission, expiry, target app whitelist
3. Return 200 + ticket_id immediately
4. Background task:
   a. Calculate write cost (USDC)
   b. Verify amount <= max_payment_per_tx
   c. Verify cumulative spend <= spend_allowance
   d. Broker transfers USDC from agent wallet to target app wallet
   f. Credit target app wallet, record spend against allowance
   g. Write data to storage
```

**Reads**: The agent key authenticates the request. If the collection has paid fields, the standard `PaymentRequiredError` flow applies separately.

### Pay Limits

All limits are optional -- omit any to leave it uncapped. Limits are enforced fail-fast in order:

| Limit                 | Enforced at | Effect                                         |
| --------------------- | ----------- | ---------------------------------------------- |
| `expires_at`          | Pre-flight  | Key stops working after this timestamp         |
| `max_payment_per_tx`  | Per-write   | Single write cannot exceed this amount (uUSDC) |
| `spend_allowance`     | Per-write   | Cumulative lifetime cap (uUSDC)                |
| `allowed_target_apps` | Pre-flight  | Whitelist of app IDs the key can pay into      |

```typescript theme={null}
interface PayLimits {
  expires_at?: string;           // ISO 8601 expiry time
  max_payment_per_tx?: number;   // Max USDC per transaction (6 decimals)
  spend_allowance?: number;      // Lifetime spend cap in USDC base units
  allowed_target_apps?: string[]; // Whitelist of target app IDs
}
```

<Note>
  1 USDC = 1,000,000 uUSDC (6 decimals). A `max_payment_per_tx` of `5_000_000` means 5 USDC.
</Note>

## App Key Usage

The App Key (`X-App-Key` header) is required for all write operations:

* Creating documents
* Updating documents
* Deleting documents
* Creating indexes
* Creating collections
* Managing views

```typescript TypeScript theme={null}
// App key is automatically included in all requests
const result = await client.store({
  collection: 'posts',
  data: [{ title: 'Hello World', content: 'My first post' }]
});
```

## Managing App Keys

### Generating a New Key

1. Go to [app.ondb.ai](https://app.ondb.ai)
2. Log in to your account
3. Select your application
4. Navigate to the **Security** tab
5. Enter a name for your key (e.g., "production-backend", "staging-api")
6. Select the permissions (Read, Write, Admin)
7. Click **Generate New API Key**
8. Approve the transaction (small fee \~\$0.001 USDC)
9. **Copy your key immediately** - it will only be shown once

<Warning>
  App Keys are only displayed once at creation time. Store them securely in your environment variables or secrets manager immediately after generation.
</Warning>

### Listing Existing Keys

From the Security tab, click **Load Keys** to view all your active App Keys. For each key you can see:

* **Key Hash**: First 16 characters of the key hash for identification
* **Name**: The name you assigned when creating the key
* **Permissions**: Visual badges showing Read/Write/Admin access
* **Created**: When the key was generated
* **Last Used**: Most recent API request with this key

### Revoking a Key

If a key is compromised or no longer needed:

1. Go to the **Security** tab
2. Click **Load Keys** to list all keys
3. Find the key you want to revoke
4. Click the **Revoke** button
5. Confirm the revocation
6. Approve the transaction

<Note>
  Revoked keys are immediately invalidated. Any applications using that key will receive authentication errors.
</Note>

## Security Best Practices

<Warning>
  Never expose your App Key in client-side code. Use environment variables and server-side APIs for write operations.
</Warning>

### Key Management Guidelines

| Practice                     | Description                                     |
| ---------------------------- | ----------------------------------------------- |
| Use environment variables    | Never hardcode keys in source code              |
| Principle of least privilege | Create keys with only necessary permissions     |
| Rotate keys regularly        | Regenerate keys every 90 days                   |
| Separate environments        | Use different keys for dev/staging/production   |
| Monitor usage                | Check "Last Used" to detect unauthorized access |
| Immediate revocation         | Revoke compromised keys immediately             |

### Server-Side Configuration

```typescript TypeScript theme={null}
// Server-side (Node.js)
const client = createClient({
  endpoint: process.env.ONDB_ENDPOINT,
  appId: process.env.ONDB_APP_ID,
  appKey: process.env.ONDB_APP_KEY
});
```

### HTTPS Only

Always use HTTPS when communicating with OnDB APIs. Never send App Keys over unencrypted connections.

## Next Steps

<CardGroup cols={2}>
  <Card title="Security Settings" icon="shield-halved" href="/concepts/security">
    Authentication and authz grants
  </Card>

  <Card title="Collections & Indexes" icon="table" href="/concepts/collections-indexes">
    Learn about organizing your data
  </Card>

  <Card title="Payment Flows" icon="credit-card" href="/concepts/payment-flows">
    Understand payment options
  </Card>
</CardGroup>
