# Authentication Guide

This comprehensive guide covers all aspects of authentication with the Lilith
API, from basic JWT tokens to advanced security patterns.

## Table of Contents

- [Authentication Overview](#authentication-overview)
- [JWT Token Authentication](#jwt-token-authentication)
- [Login Flow](#login-flow)
- [Token Management](#token-management)
- [Security Best Practices](#security-best-practices)
- [Error Handling](#error-handling)
- [Advanced Patterns](#advanced-patterns)

## Authentication Overview

The Lilith API uses **JWT (JSON Web Token)** authentication for secure,
stateless access control. All API requests (except public endpoints like
`/v1/health`) require a valid JWT token in the `Authorization` header.

### Authentication Features

- ✅ **Stateless**: No server-side session storage
- ✅ **Secure**: Cryptographically signed tokens
- ✅ **Flexible**: Configurable expiration and refresh
- ✅ **Scalable**: Works across distributed services
- ✅ **Standards-based**: RFC 7519 compliant

### Token Types

| Token Type        | Purpose                | Lifetime     | Refresh           |
| ----------------- | ---------------------- | ------------ | ----------------- |
| **Access Token**  | API authentication     | 1 hour       | Via refresh token |
| **Refresh Token** | Token renewal          | 30 days      | Single use        |
| **API Key**       | Service authentication | Configurable | Manual rotation   |

## JWT Token Authentication

### Token Structure

JWT tokens consist of three base64-encoded parts separated by dots:

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```

**Header**: Algorithm and token type

```json
{
  "alg": "HS256",
  "typ": "JWT"
}
```

**Payload**: Claims and user information

```json
{
  "sub": "user_123",
  "name": "John Doe",
  "email": "john@example.com",
  "iat": 1516239022,
  "exp": 1516242622,
  "scope": "read write",
  "role": "user"
}
```

**Signature**: Cryptographic signature for verification

### Using JWT Tokens

Include your JWT token in the `Authorization` header with the `Bearer` scheme:

```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

## Login Flow

### Standard Login

Authenticate with email and password to receive JWT tokens:

```bash
curl -X POST "https://api.lilith.app/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "secure_password"
  }'
```

**Response:**

```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "refresh_abc123def456...",
  "expires_in": 3600,
  "token_type": "Bearer",
  "user": {
    "id": "user_123",
    "email": "user@example.com",
    "name": "John Doe",
    "role": "user",
    "preferences": {
      "default_persona": "zen_master",
      "preferred_voice": "calm_female_01"
    }
  }
}
```

### Implementation Examples

#### JavaScript/TypeScript

```javascript
class LilithAuth {
  constructor(baseURL = 'https://api.lilith.app') {
    this.baseURL = baseURL;
    this.token = localStorage.getItem('lilith_token');
    this.refreshToken = localStorage.getItem('lilith_refresh_token');
  }

  async login(email, password) {
    try {
      const response = await fetch(`${this.baseURL}/v1/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      });

      if (!response.ok) {
        throw new Error(`Login failed: ${response.status}`);
      }

      const auth = await response.json();

      // Store tokens securely
      this.token = auth.token;
      this.refreshToken = auth.refresh_token;
      localStorage.setItem('lilith_token', auth.token);
      localStorage.setItem('lilith_refresh_token', auth.refresh_token);

      return auth;
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  }

  async makeAuthenticatedRequest(url, options = {}) {
    const headers = {
      Authorization: `Bearer ${this.token}`,
      'Content-Type': 'application/json',
      ...options.headers,
    };

    const response = await fetch(url, {
      ...options,
      headers,
    });

    // Handle token expiration
    if (response.status === 401) {
      const refreshed = await this.refreshAccessToken();
      if (refreshed) {
        // Retry with new token
        headers.Authorization = `Bearer ${this.token}`;
        return fetch(url, { ...options, headers });
      } else {
        // Redirect to login
        this.logout();
        throw new Error('Authentication required');
      }
    }

    return response;
  }

  logout() {
    this.token = null;
    this.refreshToken = null;
    localStorage.removeItem('lilith_token');
    localStorage.removeItem('lilith_refresh_token');
  }
}
```

#### Kotlin/Android

```kotlin
class LilithAuthManager(
    private val baseUrl: String = "https://api.lilith.app",
    private val context: Context
) {
    private val client = OkHttpClient()
    private val prefs = context.getSharedPreferences("lilith_auth", Context.MODE_PRIVATE)

    var accessToken: String?
        get() = prefs.getString("access_token", null)
        set(value) = prefs.edit().putString("access_token", value).apply()

    var refreshToken: String?
        get() = prefs.getString("refresh_token", null)
        set(value) = prefs.edit().putString("refresh_token", value).apply()

    suspend fun login(email: String, password: String): AuthResponse = withContext(Dispatchers.IO) {
        val loginRequest = LoginRequest(email, password)
        val json = Gson().toJson(loginRequest)

        val body = json.toRequestBody("application/json".toMediaType())
        val request = Request.Builder()
            .url("$baseUrl/v1/auth/login")
            .post(body)
            .build()

        val response = client.newCall(request).execute()

        if (!response.isSuccessful) {
            throw Exception("Login failed: ${response.code}")
        }

        val authResponse = Gson().fromJson(response.body?.string(), AuthResponse::class.java)

        // Store tokens
        accessToken = authResponse.token
        refreshToken = authResponse.refreshToken

        authResponse
    }

    fun addAuthHeader(requestBuilder: Request.Builder): Request.Builder {
        accessToken?.let { token ->
            requestBuilder.addHeader("Authorization", "Bearer $token")
        }
        return requestBuilder
    }

    fun logout() {
        accessToken = null
        refreshToken = null
        prefs.edit().clear().apply()
    }
}

data class LoginRequest(
    val email: String,
    val password: String
)

data class AuthResponse(
    val token: String,
    @SerializedName("refresh_token")
    val refreshToken: String,
    @SerializedName("expires_in")
    val expiresIn: Int,
    val user: User
)
```

#### Swift/iOS

```swift
class LilithAuthManager: ObservableObject {
    private let baseURL = "https://api.lilith.app"

    @Published var isAuthenticated = false

    private var accessToken: String? {
        get { KeychainHelper.retrieve(key: "lilith_access_token") }
        set {
            if let token = newValue {
                KeychainHelper.store(key: "lilith_access_token", value: token)
            } else {
                KeychainHelper.delete(key: "lilith_access_token")
            }
        }
    }

    private var refreshToken: String? {
        get { KeychainHelper.retrieve(key: "lilith_refresh_token") }
        set {
            if let token = newValue {
                KeychainHelper.store(key: "lilith_refresh_token", value: token)
            } else {
                KeychainHelper.delete(key: "lilith_refresh_token")
            }
        }
    }

    func login(email: String, password: String) async throws -> AuthResponse {
        let url = URL(string: "\(baseURL)/v1/auth/login")!

        let loginData: [String: Any] = [
            "email": email,
            "password": password
        ]

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONSerialization.data(withJSONObject: loginData)

        let (data, response) = try await URLSession.shared.data(for: request)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw AuthError.loginFailed
        }

        let authResponse = try JSONDecoder().decode(AuthResponse.self, from: data)

        // Store tokens
        self.accessToken = authResponse.token
        self.refreshToken = authResponse.refreshToken
        self.isAuthenticated = true

        return authResponse
    }

    func makeAuthenticatedRequest(url: URL, method: String = "GET", body: Data? = nil) async throws -> (Data, URLResponse) {
        guard let token = accessToken else {
            throw AuthError.noToken
        }

        var request = URLRequest(url: url)
        request.httpMethod = method
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = body

        let (data, response) = try await URLSession.shared.data(for: request)

        // Handle token expiration
        if let httpResponse = response as? HTTPURLResponse,
           httpResponse.statusCode == 401 {

            let refreshed = try await refreshAccessToken()
            if refreshed {
                // Retry with new token
                request.setValue("Bearer \(accessToken!)", forHTTPHeaderField: "Authorization")
                return try await URLSession.shared.data(for: request)
            } else {
                logout()
                throw AuthError.authenticationRequired
            }
        }

        return (data, response)
    }

    func logout() {
        accessToken = nil
        refreshToken = nil
        isAuthenticated = false
    }
}

enum AuthError: Error {
    case loginFailed
    case noToken
    case authenticationRequired
    case refreshFailed
}
```

## Token Management

### Token Refresh

Access tokens have a short lifetime (1 hour) for security. Use refresh tokens to
obtain new access tokens without re-authentication:

```bash
curl -X POST "https://api.lilith.app/v1/auth/refresh" \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "refresh_abc123def456..."
  }'
```

**Response:**

```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

### Automatic Token Refresh

```javascript
class TokenManager {
  constructor() {
    this.token = localStorage.getItem('lilith_token');
    this.refreshToken = localStorage.getItem('lilith_refresh_token');
    this.tokenExpiry = localStorage.getItem('lilith_token_expiry');
  }

  async refreshAccessToken() {
    if (!this.refreshToken) {
      return false;
    }

    try {
      const response = await fetch('https://api.lilith.app/v1/auth/refresh', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          refresh_token: this.refreshToken,
        }),
      });

      if (!response.ok) {
        return false;
      }

      const data = await response.json();

      this.token = data.token;
      this.tokenExpiry = Date.now() + data.expires_in * 1000;

      localStorage.setItem('lilith_token', this.token);
      localStorage.setItem('lilith_token_expiry', this.tokenExpiry.toString());

      return true;
    } catch (error) {
      console.error('Token refresh failed:', error);
      return false;
    }
  }

  isTokenExpired() {
    return this.tokenExpiry && Date.now() >= parseInt(this.tokenExpiry);
  }

  async getValidToken() {
    if (this.isTokenExpired()) {
      const refreshed = await this.refreshAccessToken();
      if (!refreshed) {
        throw new Error('Unable to refresh token');
      }
    }
    return this.token;
  }
}
```

### Token Validation

Validate tokens before making API calls:

```bash
curl -X GET "https://api.lilith.app/v1/auth/validate" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**Response:**

```json
{
  "valid": true,
  "user": {
    "id": "user_123",
    "email": "user@example.com",
    "role": "user"
  },
  "expires_at": "2023-12-01T13:00:00Z",
  "scopes": ["read", "write"]
}
```

## Security Best Practices

### Token Storage

#### ✅ Secure Storage Options

**Web Applications:**

```javascript
// Use httpOnly cookies for SPAs with backend proxy
document.cookie = `token=${jwt}; httpOnly; secure; sameSite=strict`;

// For client-side apps, use secure storage libraries
import SecureStore from 'secure-web-storage';
const secureStorage = new SecureStore(localStorage, {
  hash: function hash(key) {
    return CryptoJS.SHA256(key).toString();
  },
  encrypt: function encrypt(data) {
    return CryptoJS.AES.encrypt(data, 'secret-key').toString();
  },
  decrypt: function decrypt(data) {
    return CryptoJS.AES.decrypt(data, 'secret-key').toString(CryptoJS.enc.Utf8);
  },
});
```

**Mobile Applications:**

```kotlin
// Android - Use EncryptedSharedPreferences
val masterKey = MasterKey.Builder(context)
    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
    .build()

val sharedPreferences = EncryptedSharedPreferences.create(
    context,
    "lilith_secure_prefs",
    masterKey,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
```

```swift
// iOS - Use Keychain Services
import Security

class KeychainHelper {
    static func store(key: String, value: String) {
        let data = value.data(using: .utf8)!

        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: key,
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
        ]

        SecItemDelete(query as CFDictionary)
        SecItemAdd(query as CFDictionary, nil)
    }
}
```

#### ❌ Insecure Storage (Avoid)

- Plain text in localStorage/sessionStorage
- Unencrypted SharedPreferences
- URL parameters or query strings
- Client-side cookies without httpOnly flag
- Version control systems
- Application logs

### Token Transmission

#### ✅ Secure Transmission

```bash
# Always use HTTPS
curl -X POST "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer $TOKEN"

# Verify SSL certificates
curl --cacert /path/to/ca-bundle.crt \
  -X POST "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer $TOKEN"
```

#### ❌ Insecure Transmission (Never Do)

```bash
# Never use HTTP for token transmission
curl -X POST "http://api.lilith.app/v1/chat"  # ❌ Insecure

# Never include tokens in URLs
curl "https://api.lilith.app/v1/chat?token=jwt_token"  # ❌ Logs token
```

### Environment-Specific Security

#### Development

```bash
# Use separate development credentials
export LILITH_API_BASE_URL="https://staging-api.lilith.app"
export LILITH_API_TOKEN="dev_token_with_limited_scope"
export LILITH_DEBUG="true"
```

#### Production

```bash
# Use production credentials with full security
export LILITH_API_BASE_URL="https://api.lilith.app"
export LILITH_API_TOKEN="prod_token_with_full_scope"
export LILITH_DEBUG="false"
export LILITH_TOKEN_REFRESH_THRESHOLD="300"  # 5 minutes
```

### Rate Limiting and Abuse Prevention

Implement client-side rate limiting to prevent abuse:

```javascript
class RateLimiter {
  constructor(maxRequests = 100, windowMs = 60000) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
    this.requests = [];
  }

  async acquire() {
    const now = Date.now();

    // Remove old requests outside the window
    this.requests = this.requests.filter(
      (timestamp) => now - timestamp < this.windowMs
    );

    if (this.requests.length >= this.maxRequests) {
      const oldestRequest = this.requests[0];
      const waitTime = this.windowMs - (now - oldestRequest);

      console.warn(`Rate limit reached. Waiting ${waitTime}ms`);
      await this.sleep(waitTime);
      return this.acquire(); // Retry
    }

    this.requests.push(now);
    return true;
  }

  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}
```

## Error Handling

### Authentication Errors

#### 401 Unauthorized

```json
{
  "code": "INVALID_TOKEN",
  "message": "JWT token is expired or invalid",
  "details": {
    "token_status": "expired",
    "expired_at": "2023-12-01T12:00:00Z"
  },
  "trace_id": "550e8400-e29b-41d4-a716-446655440000"
}
```

**Handling Strategy:**

```javascript
async function handleAuthError(response, error) {
  switch (error.code) {
    case 'INVALID_TOKEN':
    case 'TOKEN_EXPIRED':
      // Try to refresh token
      const refreshed = await authManager.refreshToken();
      if (refreshed) {
        // Retry original request
        return retryRequest();
      } else {
        // Redirect to login
        window.location.href = '/login';
      }
      break;

    case 'MISSING_TOKEN':
      // Redirect to login immediately
      window.location.href = '/login';
      break;

    case 'INSUFFICIENT_PERMISSIONS':
      // Show permission denied message
      showError('You do not have permission to access this resource');
      break;

    default:
      // Generic error handling
      showError(error.message);
  }
}
```

#### 403 Forbidden

```json
{
  "code": "INSUFFICIENT_PERMISSIONS",
  "message": "User does not have permission to access this resource",
  "details": {
    "required_scope": "admin",
    "user_scope": "user",
    "resource": "/v1/notifications/test"
  },
  "trace_id": "550e8400-e29b-41d4-a716-446655440001"
}
```

### Comprehensive Error Handler

```javascript
class AuthErrorHandler {
  constructor(authManager) {
    this.authManager = authManager;
    this.retryQueue = [];
  }

  async handleResponse(response, originalRequest) {
    if (response.status === 401) {
      return await this.handle401(response, originalRequest);
    }

    if (response.status === 403) {
      return await this.handle403(response);
    }

    return response;
  }

  async handle401(response, originalRequest) {
    const error = await response.json();

    if (error.code === 'TOKEN_EXPIRED') {
      // Add request to retry queue
      this.retryQueue.push(originalRequest);

      try {
        await this.authManager.refreshToken();

        // Retry all queued requests
        const retryPromises = this.retryQueue.map((req) =>
          this.authManager.makeAuthenticatedRequest(req.url, req.options)
        );

        this.retryQueue = [];
        return Promise.all(retryPromises);
      } catch (refreshError) {
        // Refresh failed, clear queue and redirect to login
        this.retryQueue = [];
        this.authManager.logout();
        throw new Error('Authentication required');
      }
    }

    // Other 401 errors require re-authentication
    this.authManager.logout();
    throw new Error('Authentication required');
  }

  async handle403(response) {
    const error = await response.json();
    throw new Error(`Access denied: ${error.message}`);
  }
}
```

## Advanced Patterns

### Service Account Authentication

For server-to-server communication:

```javascript
class ServiceAuth {
  constructor(clientId, clientSecret, scope) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.scope = scope;
    this.token = null;
    this.tokenExpiry = null;
  }

  async authenticate() {
    const credentials = btoa(`${this.clientId}:${this.clientSecret}`);

    const response = await fetch('https://api.lilith.app/v1/auth/token', {
      method: 'POST',
      headers: {
        Authorization: `Basic ${credentials}`,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `grant_type=client_credentials&scope=${this.scope}`,
    });

    const data = await response.json();

    this.token = data.access_token;
    this.tokenExpiry = Date.now() + data.expires_in * 1000;

    return this.token;
  }

  async getToken() {
    if (!this.token || Date.now() >= this.tokenExpiry) {
      await this.authenticate();
    }
    return this.token;
  }
}
```

### Multi-Tenant Authentication

For applications serving multiple organizations:

```javascript
class MultiTenantAuth {
  constructor() {
    this.tenantTokens = new Map();
  }

  async authenticateForTenant(tenantId, credentials) {
    const response = await fetch('https://api.lilith.app/v1/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-ID': tenantId,
      },
      body: JSON.stringify(credentials),
    });

    const auth = await response.json();

    this.tenantTokens.set(tenantId, {
      token: auth.token,
      refreshToken: auth.refresh_token,
      expiry: Date.now() + auth.expires_in * 1000,
    });

    return auth;
  }

  getTokenForTenant(tenantId) {
    return this.tenantTokens.get(tenantId);
  }

  async makeRequestForTenant(tenantId, url, options = {}) {
    const tokenData = this.getTokenForTenant(tenantId);

    if (!tokenData) {
      throw new Error(`No authentication found for tenant: ${tenantId}`);
    }

    return fetch(url, {
      ...options,
      headers: {
        Authorization: `Bearer ${tokenData.token}`,
        'X-Tenant-ID': tenantId,
        ...options.headers,
      },
    });
  }
}
```

### Token Introspection

For validating tokens on your backend:

```javascript
async function introspectToken(token) {
  const response = await fetch('https://api.lilith.app/v1/auth/introspect', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
    },
    body: `token=${token}`,
  });

  const result = await response.json();

  return {
    active: result.active,
    scopes: result.scope ? result.scope.split(' ') : [],
    userId: result.sub,
    expiresAt: result.exp ? new Date(result.exp * 1000) : null,
    clientId: result.client_id,
  };
}
```

---

## Quick Reference

### Authentication Endpoints

| Endpoint              | Method | Description                 |
| --------------------- | ------ | --------------------------- |
| `/v1/auth/login`      | POST   | User authentication         |
| `/v1/auth/refresh`    | POST   | Token refresh               |
| `/v1/auth/validate`   | GET    | Token validation            |
| `/v1/auth/logout`     | POST   | Logout and token revocation |
| `/v1/auth/introspect` | POST   | Token introspection         |

### Common Headers

```http
# Required for all authenticated requests
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# Content type for JSON requests
Content-Type: application/json

# Optional: specify tenant for multi-tenant apps
X-Tenant-ID: tenant_123

# Optional: user agent for analytics
User-Agent: MyApp/1.0.0
```

### Token Lifetimes

| Token Type    | Default Lifetime | Configurable         |
| ------------- | ---------------- | -------------------- |
| Access Token  | 1 hour           | Yes (15min - 24h)    |
| Refresh Token | 30 days          | Yes (1 day - 1 year) |
| Service Token | 1 hour           | Yes (1min - 24h)     |

### Security Checklist

- ✅ Use HTTPS for all token transmission
- ✅ Store tokens securely (encrypted storage/keychain)
- ✅ Implement automatic token refresh
- ✅ Handle authentication errors gracefully
- ✅ Use appropriate token lifetimes
- ✅ Implement rate limiting
- ✅ Validate tokens on the backend
- ✅ Revoke tokens on logout
- ✅ Monitor for suspicious activity
- ✅ Rotate keys regularly

For more advanced authentication scenarios, see our
[Security Guide](./security.md) and
[Enterprise Authentication](./enterprise-auth.md) documentation.
