# Authentication Guide

This guide explains the authentication mechanisms available in the Oshun
Platform API.

## Table of Contents

1. [Overview](#overview)
2. [Authentication Methods](#authentication-methods)
3. [JWT Authentication](#jwt-authentication)
4. [API Key Authentication](#api-key-authentication)
5. [OAuth 2.0](#oauth-20)
6. [Multi-Factor Authentication](#multi-factor-authentication)
7. [Token Management](#token-management)
8. [Security Best Practices](#security-best-practices)

---

## Overview

The Oshun Platform uses a unified authentication system across all domains. All
API requests must include valid credentials in the request headers.

### Authentication Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                         CLIENT                                   │
│  (Web App / Mobile App / API Consumer / SDK)                    │
└─────────────────────────────────┬───────────────────────────────┘
                                  │
                                  │ Credentials
                                  ▼
┌─────────────────────────────────────────────────────────────────┐
│                      API GATEWAY                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                Authentication Layer                       │   │
│  │  • JWT Verification                                       │   │
│  │  • API Key Validation                                     │   │
│  │  • OAuth Token Validation                                 │   │
│  │  • Rate Limiting                                          │   │
│  └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────┬───────────────────────────────┘
                                  │
                                  │ Authenticated Request
                                  ▼
┌─────────────────────────────────────────────────────────────────┐
│                      DOMAIN SERVICES                             │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐   │
│  │  Isis   │ │ Sophia  │ │ Hathor  │ │ Bellona │ │   ...   │   │
│  └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘   │
└─────────────────────────────────────────────────────────────────┘
```

---

## Authentication Methods

| Method         | Use Case                                | Token Lifetime | Refresh         |
| -------------- | --------------------------------------- | -------------- | --------------- |
| **JWT Bearer** | Web/mobile apps, user sessions          | 15 minutes     | Yes (7 days)    |
| **API Key**    | Server-to-server, CLI tools, automation | Long-lived     | Manual rotation |
| **OAuth 2.0**  | Third-party integrations, partner apps  | Configurable   | Yes             |

---

## JWT Authentication

JWT (JSON Web Token) authentication is the primary method for user-facing
applications.

### Token Structure

```
Header.Payload.Signature

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-id-001"
}
.
{
  "sub": "user_abc123",           // User ID
  "iss": "https://auth.oshun.io", // Issuer
  "aud": "https://api.oshun.io",  // Audience
  "exp": 1704067200,              // Expiration (Unix timestamp)
  "iat": 1704066300,              // Issued at
  "jti": "token_xyz789",          // Token ID (for revocation)
  "scope": "generation:write knowledge:read",
  "org": "org_def456",            // Organization ID (optional)
  "permissions": ["admin", "billing"]
}
.
[Signature]
```

### Obtaining Tokens

#### Login Flow

```http
POST /auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "your-password"
}
```

**Response:**

```json
{
  "accessToken": "eyJhbGciOiJSUzI1NiIs...",
  "refreshToken": "rt_abc123xyz...",
  "tokenType": "Bearer",
  "expiresIn": 900,
  "scope": "generation:write knowledge:read"
}
```

#### Using Tokens

Include the access token in the `Authorization` header:

```http
GET /api/isis/generation/jobs
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
```

### Token Refresh

When the access token expires, use the refresh token to obtain a new one:

```http
POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "rt_abc123xyz..."
}
```

**Response:**

```json
{
  "accessToken": "eyJhbGciOiJSUzI1NiIs...",
  "refreshToken": "rt_new456def...",
  "tokenType": "Bearer",
  "expiresIn": 900
}
```

### Token Revocation

To invalidate a token (e.g., on logout):

```http
POST /auth/revoke
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
Content-Type: application/json

{
  "token": "rt_abc123xyz...",
  "tokenTypeHint": "refresh_token"
}
```

---

## API Key Authentication

API keys are long-lived credentials for server-to-server communication.

### Key Types

| Type           | Prefix     | Use Case                    |
| -------------- | ---------- | --------------------------- |
| **Live**       | `sk_live_` | Production environment      |
| **Test**       | `sk_test_` | Sandbox/testing environment |
| **Restricted** | `rk_`      | Limited scope keys          |

### Creating API Keys

```http
POST /api/keys
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "name": "Production Server",
  "permissions": ["generation:write", "generation:read"],
  "expiresAt": "2025-12-31T23:59:59Z",
  "ipAllowlist": ["203.0.113.0/24"],
  "rateLimit": {
    "requests": 1000,
    "period": "minute"
  }
}
```

**Response:**

```json
{
  "id": "key_abc123",
  "key": "sk_live_abc123xyz789...",
  "name": "Production Server",
  "permissions": ["generation:write", "generation:read"],
  "createdAt": "2024-01-15T10:30:00Z",
  "expiresAt": "2025-12-31T23:59:59Z"
}
```

> **Important:** The full API key is only shown once. Store it securely.

### Using API Keys

Include the API key in the `X-API-Key` header or `Authorization` header:

```http
GET /api/isis/generation/jobs
X-API-Key: sk_live_abc123xyz789...
```

Or:

```http
GET /api/isis/generation/jobs
Authorization: ApiKey sk_live_abc123xyz789...
```

### Key Rotation

Rotate keys periodically for security:

```http
POST /api/keys/{keyId}/rotate
Authorization: Bearer {access_token}
```

**Response:**

```json
{
  "id": "key_abc123",
  "key": "sk_live_newkey456...",
  "previousKey": "sk_live_abc123xyz789...",
  "previousKeyExpiresAt": "2024-01-22T10:30:00Z"
}
```

The previous key remains valid for 7 days to allow gradual migration.

---

## OAuth 2.0

OAuth 2.0 is used for third-party application integration.

### Supported Grant Types

| Grant Type                    | Use Case                           |
| ----------------------------- | ---------------------------------- |
| **Authorization Code**        | Web applications with backend      |
| **Authorization Code + PKCE** | Mobile apps, SPAs                  |
| **Client Credentials**        | Server-to-server (no user context) |

### Authorization Code Flow

#### Step 1: Redirect to Authorization

```
https://auth.oshun.io/oauth/authorize?
  client_id=your_client_id&
  redirect_uri=https://your-app.com/callback&
  response_type=code&
  scope=generation:write%20knowledge:read&
  state=random_state_string&
  code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&
  code_challenge_method=S256
```

#### Step 2: User Authenticates

The user logs in and approves the requested permissions.

#### Step 3: Handle Callback

```
https://your-app.com/callback?code=auth_code_here&state=random_state_string
```

#### Step 4: Exchange Code for Tokens

```http
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&
code=auth_code_here&
redirect_uri=https://your-app.com/callback&
client_id=your_client_id&
client_secret=your_client_secret&
code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "rt_oauth_abc123...",
  "scope": "generation:write knowledge:read"
}
```

### Client Credentials Flow

For server-to-server communication without user context:

```http
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&
client_id=your_client_id&
client_secret=your_client_secret&
scope=generation:write
```

### Available Scopes

| Scope              | Description                          |
| ------------------ | ------------------------------------ |
| `generation:read`  | Read generation jobs and outputs     |
| `generation:write` | Create and manage generation jobs    |
| `knowledge:read`   | Search and read documents            |
| `knowledge:write`  | Ingest and manage documents          |
| `world:read`       | Read worlds and entities             |
| `world:write`      | Create and modify worlds             |
| `build:read`       | Read build configurations and status |
| `build:write`      | Create and manage builds             |
| `user:read`        | Read user profile                    |
| `user:write`       | Update user profile                  |
| `admin`            | Full administrative access           |

---

## Multi-Factor Authentication

MFA adds an additional layer of security to user accounts.

### Supported Methods

| Method       | Description                                                |
| ------------ | ---------------------------------------------------------- |
| **TOTP**     | Time-based One-Time Password (Google Authenticator, Authy) |
| **WebAuthn** | Hardware security keys (YubiKey), biometrics               |
| **SMS**      | SMS verification codes (backup method)                     |
| **Email**    | Email verification codes (backup method)                   |

### Enrolling MFA

#### TOTP Setup

```http
POST /auth/mfa/totp/enroll
Authorization: Bearer {access_token}
```

**Response:**

```json
{
  "secret": "JBSWY3DPEHPK3PXP",
  "qrCode": "data:image/png;base64,iVBORw0KGgo...",
  "backupCodes": [
    "abc12-def34",
    "ghi56-jkl78",
    ...
  ]
}
```

#### TOTP Verification

```http
POST /auth/mfa/totp/verify
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "code": "123456"
}
```

### Login with MFA

When MFA is enabled, login returns a challenge:

```http
POST /auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "your-password"
}
```

**Response (MFA Required):**

```json
{
  "mfaRequired": true,
  "mfaToken": "mfa_challenge_token_xyz...",
  "availableMethods": ["totp", "webauthn"]
}
```

Complete MFA:

```http
POST /auth/mfa/verify
Content-Type: application/json

{
  "mfaToken": "mfa_challenge_token_xyz...",
  "method": "totp",
  "code": "123456"
}
```

---

## Token Management

### Viewing Active Sessions

```http
GET /auth/sessions
Authorization: Bearer {access_token}
```

**Response:**

```json
{
  "sessions": [
    {
      "id": "sess_abc123",
      "device": "Chrome on macOS",
      "ip": "203.0.113.42",
      "location": "San Francisco, CA",
      "lastActive": "2024-01-15T10:30:00Z",
      "current": true
    },
    {
      "id": "sess_def456",
      "device": "Oshun iOS App",
      "ip": "198.51.100.23",
      "location": "New York, NY",
      "lastActive": "2024-01-14T15:45:00Z",
      "current": false
    }
  ]
}
```

### Revoking Sessions

```http
DELETE /auth/sessions/{sessionId}
Authorization: Bearer {access_token}
```

### Revoking All Sessions

```http
POST /auth/sessions/revoke-all
Authorization: Bearer {access_token}
```

---

## Security Best Practices

### 1. Store Tokens Securely

**Web Applications:**

- Store access tokens in memory only
- Store refresh tokens in HTTP-only, secure cookies
- Never store tokens in localStorage or sessionStorage

**Mobile Applications:**

- Use platform secure storage (Keychain, Keystore)
- Enable biometric protection

**Server Applications:**

- Use environment variables or secret managers
- Never commit credentials to version control

### 2. Implement Token Refresh

```typescript
// Example: Automatic token refresh
async function fetchWithAuth(url: string, options: RequestInit = {}) {
  let accessToken = getAccessToken();

  if (isTokenExpired(accessToken)) {
    const newTokens = await refreshTokens();
    accessToken = newTokens.accessToken;
    storeTokens(newTokens);
  }

  return fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${accessToken}`,
    },
  });
}
```

### 3. Validate Tokens Server-Side

Always validate tokens on your backend before trusting them:

```typescript
import { verify } from 'jose';

async function validateToken(token: string) {
  const JWKS = jose.createRemoteJWKSet(
    new URL('https://auth.oshun.io/.well-known/jwks.json')
  );

  const { payload } = await jose.jwtVerify(token, JWKS, {
    issuer: 'https://auth.oshun.io',
    audience: 'https://api.oshun.io',
  });

  return payload;
}
```

### 4. Use IP Allowlisting for API Keys

Restrict API keys to specific IP ranges:

```json
{
  "ipAllowlist": ["203.0.113.0/24", "198.51.100.0/24"]
}
```

### 5. Monitor for Suspicious Activity

- Set up alerts for failed authentication attempts
- Monitor for unusual patterns (geographic anomalies, time-based)
- Implement progressive delays for failed attempts

### 6. Rotate Credentials Regularly

| Credential Type      | Recommended Rotation |
| -------------------- | -------------------- |
| API Keys             | Every 90 days        |
| OAuth Client Secrets | Every 180 days       |
| Service Account Keys | Every 90 days        |

---

## Error Responses

### Authentication Errors

| Code                      | HTTP Status | Description                      |
| ------------------------- | ----------- | -------------------------------- |
| `AUTH_INVALID_TOKEN`      | 401         | Token is invalid or malformed    |
| `AUTH_EXPIRED_TOKEN`      | 401         | Token has expired                |
| `AUTH_REVOKED_TOKEN`      | 401         | Token has been revoked           |
| `AUTH_INSUFFICIENT_SCOPE` | 403         | Token lacks required permissions |
| `AUTH_MFA_REQUIRED`       | 401         | MFA verification required        |
| `AUTH_RATE_LIMITED`       | 429         | Too many authentication attempts |

### Example Error Response

```json
{
  "error": {
    "code": "AUTH_EXPIRED_TOKEN",
    "message": "The access token has expired",
    "details": {
      "expiredAt": "2024-01-15T10:30:00Z"
    }
  },
  "requestId": "req_abc123xyz"
}
```

---

## Support

- **Documentation:** https://docs.oshun.io/authentication
- **API Status:** https://status.oshun.io
- **Security Issues:** security@oshun.io
