# Authentication & Authorization

This document provides comprehensive documentation for the Lilith API
authentication and authorization system.

## Overview

The Lilith API implements a defense-in-depth security architecture with multiple
authentication methods and fine-grained authorization controls.

**Supported Authentication Methods:**

- JWT-based session authentication
- OAuth 2.0 (Google, GitHub, Apple)
- API keys for programmatic access
- WebAuthn/Passkeys for passwordless authentication
- Magic Links for email-based login
- TOTP-based Two-Factor Authentication (2FA)

---

## Table of Contents

1. [JWT Authentication](#jwt-authentication)
2. [OAuth Integration](#oauth-integration)
3. [RBAC Permission Matrix](#rbac-permission-matrix)
4. [API Key Management](#api-key-management)
5. [WebAuthn/Passkeys](#webauthnpasskeys)
6. [Two-Factor Authentication](#two-factor-authentication)
7. [Magic Link Authentication](#magic-link-authentication)
8. [Session Management](#session-management)
9. [Security Features](#security-features)

---

## JWT Authentication

### Token Structure

The Lilith API uses JSON Web Tokens (JWT) for session-based authentication with
the following claim structure:

**Access Token Claims:**

```json
{
  "sub": "user_12345",
  "userId": "user_12345",
  "email": "user@example.com",
  "roles": ["user"],
  "permissions": ["profile:read", "content:view:published"],
  "sessionId": "sess_abc123",
  "deviceId": "device_xyz",
  "iss": "https://auth.lilith.app",
  "aud": "lilith-api",
  "exp": 1704067200,
  "iat": 1704063600,
  "jti": "token_unique_id"
}
```

| Claim         | Description                  |
| ------------- | ---------------------------- |
| `sub`         | Subject - User ID            |
| `userId`      | User identifier              |
| `email`       | User email address           |
| `roles`       | Array of assigned roles      |
| `permissions` | Array of granted permissions |
| `sessionId`   | Unique session identifier    |
| `deviceId`    | Device identifier (optional) |
| `iss`         | Token issuer                 |
| `aud`         | Token audience               |
| `exp`         | Expiration timestamp         |
| `iat`         | Issued at timestamp          |
| `jti`         | Unique token ID              |

### Token Signing

**Algorithm:** RS256 (RSA Signature with SHA-256)

The Lilith API uses asymmetric RSA key pairs for JWT signing:

- **Private Key:** Used by the Auth Service to sign tokens (never exposed)
- **Public Key:** Available for external verification via JWKS endpoint

The RS256 algorithm provides:

- Asymmetric verification (anyone with the public key can verify)
- Non-repudiation (only the Auth Service can create valid tokens)
- Key rotation support (via key ID in token header)

```
Token Header:
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "a1b2c3d4"  // Key ID for rotation support
}
```

### Token Lifetimes

| Token Type    | Default Lifetime  | Configurable |
| ------------- | ----------------- | ------------ |
| Access Token  | 15 minutes (900s) | Yes          |
| Refresh Token | 7 days (604800s)  | Yes          |

**Security Rationale:**

- Short-lived access tokens (15 min) minimize exposure if compromised
- Refresh tokens rotate on each use (single-use tokens)
- Device fingerprinting detects token theft across devices

### Authentication Flow

```
┌─────────────┐         ┌─────────────┐         ┌─────────────┐
│   Client    │         │  Lilith API │         │ Auth Service│
└─────┬───────┘         └──────┬──────┘         └──────┬──────┘
      │                        │                       │
      │  1. POST /v1/auth/login                       │
      │  {email, password}     │                       │
      ├───────────────────────►│                       │
      │                        │  2. Validate creds    │
      │                        ├──────────────────────►│
      │                        │                       │
      │                        │  3. Generate tokens   │
      │                        │◄──────────────────────┤
      │                        │                       │
      │  4. Return tokens      │                       │
      │  {access_token,        │                       │
      │   refresh_token,       │                       │
      │   expires_in}          │                       │
      │◄───────────────────────┤                       │
      │                        │                       │
      │  5. API Request        │                       │
      │  Authorization: Bearer │                       │
      ├───────────────────────►│                       │
      │                        │  6. Validate JWT      │
      │                        ├──────────────────────►│
      │                        │                       │
      │  7. API Response       │                       │
      │◄───────────────────────┤                       │
      │                        │                       │
```

### Login

**Endpoint:** `POST /v1/auth/login`

**Request:**

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

**Response:**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImExYjJjM2Q0In0...",
  "refresh_token": "a1b2c3d4e5f6...",
  "token_type": "Bearer",
  "expires_in": 900,
  "session_id": "sess_abc123",
  "user": {
    "id": "user_12345",
    "email": "user@example.com",
    "roles": ["user"]
  }
}
```

### Token Refresh Flow

```
┌─────────────┐         ┌─────────────┐
│   Client    │         │  Lilith API │
└─────┬───────┘         └──────┬──────┘
      │                        │
      │ Access token expired   │
      │                        │
      │ POST /v1/auth/refresh  │
      │ {refresh_token}        │
      ├───────────────────────►│
      │                        │
      │ Validate refresh token │
      │ Check device fingerprint
      │ Rotate refresh token   │
      │                        │
      │ New tokens returned    │
      │ {access_token,         │
      │  refresh_token}        │
      │◄───────────────────────┤
      │                        │
```

**Endpoint:** `POST /v1/auth/refresh`

**Request:**

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

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "f6e5d4c3b2a1...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

**Security Notes:**

- Refresh tokens are rotated on each use (old token invalidated)
- Device fingerprint (IP + User-Agent) is validated on refresh
- Suspicious refresh patterns trigger security alerts

### Using Access Tokens

Include the access token in the `Authorization` header:

```bash
curl -X GET "https://api.lilith.app/v1/chat" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

### Token Validation

**Endpoint:** `POST /v1/auth/validate`

Validate a token without making an API call:

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

**Response:**

```json
{
  "valid": true,
  "claims": {
    "userId": "user_12345",
    "email": "user@example.com",
    "roles": ["user"],
    "exp": 1704067200
  }
}
```

### Logout

**Endpoint:** `POST /v1/auth/logout`

```bash
curl -X POST "https://api.lilith.app/v1/auth/logout" \
  -H "Authorization: Bearer <access_token>"
```

This invalidates the current session and blacklists the token.

---

## OAuth Integration

### Supported Providers

| Provider | Endpoint | Scopes                |
| -------- | -------- | --------------------- |
| Google   | `google` | email, profile        |
| GitHub   | `github` | read:user, user:email |
| Apple    | `apple`  | email, name           |

### OAuth Flow

```
┌──────────┐     ┌─────────────┐     ┌────────────┐     ┌─────────────┐
│  Client  │     │ Lilith API  │     │  Provider  │     │ Auth Service│
└────┬─────┘     └──────┬──────┘     └─────┬──────┘     └──────┬──────┘
     │                  │                  │                   │
     │ 1. GET /v1/auth/oauth/google        │                   │
     ├─────────────────►│                  │                   │
     │                  │                  │                   │
     │ 2. Redirect to Google               │                   │
     │◄─────────────────┤                  │                   │
     │                  │                  │                   │
     │ 3. User authenticates with Google   │                   │
     ├────────────────────────────────────►│                   │
     │                  │                  │                   │
     │ 4. Redirect back with code          │                   │
     │◄────────────────────────────────────┤                   │
     │                  │                  │                   │
     │ 5. POST /v1/auth/oauth/callback     │                   │
     │    {provider, code}                 │                   │
     ├─────────────────►│                  │                   │
     │                  │ 6. Exchange code for tokens          │
     │                  ├─────────────────►│                   │
     │                  │                  │                   │
     │                  │ 7. Get user info │                   │
     │                  ├─────────────────►│                   │
     │                  │                  │                   │
     │                  │ 8. Create/update user                │
     │                  ├──────────────────────────────────────►
     │                  │                  │                   │
     │ 9. Return tokens │                  │                   │
     │◄─────────────────┤                  │                   │
     │                  │                  │                   │
```

### Initiating OAuth

**Step 1: Get Provider Authorization URL**

**Endpoint:** `GET /v1/auth/oauth/{provider}`

```bash
curl -X GET "https://api.lilith.app/v1/auth/oauth/google?redirect_uri=https://app.lilith.app/auth/callback"
```

**Response:**

```json
{
  "authorization_url": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=...&scope=email%20profile&state=abc123"
}
```

**Step 2: Redirect User**

Redirect the user to the `authorization_url`. They will authenticate with the
provider.

**Step 3: Handle Callback**

**Endpoint:** `POST /v1/auth/oauth/callback`

```bash
curl -X POST "https://api.lilith.app/v1/auth/oauth/callback" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "google",
    "code": "auth_code_from_provider",
    "state": "abc123"
  }'
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "a1b2c3d4e5f6...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "user": {
    "id": "user_12345",
    "email": "user@gmail.com",
    "name": "John Doe",
    "picture": "https://..."
  }
}
```

### Linking Social Accounts

**Endpoint:** `POST /v1/auth/social/link`

Link an additional OAuth provider to an existing account:

```bash
curl -X POST "https://api.lilith.app/v1/auth/social/link" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "github",
    "code": "github_auth_code"
  }'
```

### Provider-Specific Notes

**Google:**

- Uses OpenID Connect
- Email always verified
- Profile picture URL included

**GitHub:**

- May require additional `user:email` scope for private emails
- Returns username as well as email

**Apple:**

- User name only provided on first authentication
- Email may be relay address (@privaterelay.appleid.com)

---

## RBAC Permission Matrix

### Available Roles

| Role      | Description                   | Typical Users           |
| --------- | ----------------------------- | ----------------------- |
| `user`    | Standard authenticated user   | Regular app users       |
| `admin`   | Full administrative access    | Platform administrators |
| `support` | Customer support capabilities | Support team            |
| `auditor` | Read-only audit access        | Compliance reviewers    |

### Permission Definitions

Permissions follow the format: `resource:action:scope`

**Examples:**

- `profile:read` - Read any profile
- `profile:update:self` - Update own profile only
- `content:view:published` - View published content
- `audit-log:read:any` - Read all audit logs

### Role-Permission Matrix

| Permission                  | user | admin | support | auditor |
| --------------------------- | :--: | :---: | :-----: | :-----: |
| `profile:read`              |  ✓   |   ✓   |    ✓    |    ✓    |
| `profile:update:self`       |  ✓   |   ✓   |    ✓    |    -    |
| `content:view:published`    |  ✓   |   ✓   |    ✓    |    ✓    |
| `content:view:drafts`       |  -   |   ✓   |    ✓    |    -    |
| `comments:create:self`      |  ✓   |   ✓   |    ✓    |    -    |
| `comments:update:self`      |  ✓   |   ✓   |    ✓    |    -    |
| `comments:delete:self`      |  ✓   |   ✓   |    ✓    |    -    |
| `user:roles:view`           |  -   |   ✓   |    ✓    |    -    |
| `user:roles:update`         |  -   |   ✓   |    -    |    -    |
| `user:status:update`        |  -   |   ✓   |    ✓    |    -    |
| `audit-log:read:any`        |  -   |   ✓   |    -    |    ✓    |
| `telemetry:read:aggregated` |  -   |   ✓   |    -    |    ✓    |
| `service-account:manage`    |  -   |   ✓   |    -    |    -    |

### Self-Scope Permissions

Permissions ending in `:self` automatically check resource ownership:

```javascript
// User can only update their own profile
if (permission === 'profile:update:self') {
  return request.userId === resource.ownerId;
}
```

### Admin Auto-Promotion

Users with specific email domains or addresses can be automatically promoted to
admin:

**Configuration:**

```bash
AUTH_DEFAULT_ADMIN_EMAILS="admin@company.com,security@company.com"
```

### IP Restrictions for Admin Operations

Administrative endpoints can be restricted by IP:

**Configuration:**

```bash
AUTH_ADMIN_ALLOWED_IPS="10.0.0.0/8,192.168.1.0/24"
```

---

## API Key Management

### Overview

API keys provide programmatic access to the Lilith API without user sessions.
They are ideal for:

- Server-to-server integrations
- CI/CD pipelines
- Automated scripts
- Third-party integrations

### Creating an API Key

**Endpoint:** `POST /v1/auth/api-keys`

```bash
curl -X POST "https://api.lilith.app/v1/auth/api-keys" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production Integration",
    "scopes": ["content:read", "chat:create"]
  }'
```

**Response:**

```json
{
  "id": "key_abc123",
  "key": "lk_live_a1b2c3d4e5f6g7h8i9j0...",
  "name": "Production Integration",
  "scopes": ["content:read", "chat:create"],
  "created_at": "2024-01-01T00:00:00Z"
}
```

**Important:** The `key` value is only shown once at creation time. Store it
securely.

### Listing API Keys

**Endpoint:** `GET /v1/auth/api-keys`

```bash
curl -X GET "https://api.lilith.app/v1/auth/api-keys" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "keys": [
    {
      "id": "key_abc123",
      "key": "lk_live_a1b2c3d4...",
      "name": "Production Integration",
      "scopes": ["content:read", "chat:create"],
      "created_at": "2024-01-01T00:00:00Z",
      "last_used": "2024-01-15T10:30:00Z"
    }
  ]
}
```

Note: Keys are masked after creation (first 8 characters + "...").

### Using API Keys

Include the API key in the `Authorization` header:

```bash
curl -X GET "https://api.lilith.app/v1/content/courses" \
  -H "Authorization: Bearer lk_live_a1b2c3d4e5f6g7h8i9j0..."
```

### Revoking an API Key

**Endpoint:** `DELETE /v1/auth/api-keys/{keyId}`

```bash
curl -X DELETE "https://api.lilith.app/v1/auth/api-keys/key_abc123" \
  -H "Authorization: Bearer <access_token>"
```

### API Key Best Practices

1. **Use specific scopes** - Only grant permissions that are actually needed
2. **Rotate keys regularly** - Generate new keys periodically and revoke old
   ones
3. **Use environment variables** - Never commit API keys to version control
4. **Monitor usage** - Check `last_used` to detect unused or compromised keys
5. **Separate environments** - Use different keys for development and production

---

## WebAuthn/Passkeys

### Overview

WebAuthn enables passwordless authentication using biometrics (Face ID,
fingerprint) or hardware security keys (YubiKey).

### Registration Flow

```
┌──────────┐     ┌─────────────┐     ┌─────────────────┐
│  Client  │     │ Lilith API  │     │  Authenticator  │
└────┬─────┘     └──────┬──────┘     └────────┬────────┘
     │                  │                     │
     │ 1. POST /v1/auth/webauthn/registration/begin
     ├─────────────────►│                     │
     │                  │                     │
     │ 2. Challenge + options                 │
     │◄─────────────────┤                     │
     │                  │                     │
     │ 3. Create credential                   │
     ├───────────────────────────────────────►│
     │                  │                     │
     │ 4. Credential response                 │
     │◄───────────────────────────────────────┤
     │                  │                     │
     │ 5. POST /v1/users/:id/webauthn/register
     │    {credentialId, publicKey, ...}      │
     ├─────────────────►│                     │
     │                  │                     │
     │ 6. Credential stored                   │
     │◄─────────────────┤                     │
     │                  │                     │
```

**Step 1: Begin Registration**

**Endpoint:** `POST /v1/auth/webauthn/registration/begin`

```bash
curl -X POST "https://api.lilith.app/v1/auth/webauthn/registration/begin" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "challenge": "randomBase64EncodedChallenge...",
  "rp": {
    "name": "Lilith App",
    "id": "lilith.app"
  },
  "user": {
    "id": "dXNlcl8xMjM0NQ==",
    "name": "user@example.com",
    "displayName": "John Doe"
  },
  "pubKeyCredParams": [
    { "type": "public-key", "alg": -7 },
    { "type": "public-key", "alg": -257 }
  ],
  "timeout": 60000,
  "attestation": "none",
  "authenticatorSelection": {
    "authenticatorAttachment": "platform",
    "residentKey": "discouraged",
    "userVerification": "preferred"
  }
}
```

**Step 2: Register Credential**

**Endpoint:** `POST /v1/users/{userId}/webauthn/register`

```bash
curl -X POST "https://api.lilith.app/v1/users/user_12345/webauthn/register" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "credentialId": "base64EncodedCredentialId",
    "publicKey": "base64EncodedPublicKey",
    "clientDataJSON": "base64EncodedClientData",
    "attestationObject": "base64EncodedAttestation"
  }'
```

### Authentication Flow

**Endpoint:** `POST /v1/auth/webauthn/authenticate`

```bash
curl -X POST "https://api.lilith.app/v1/auth/webauthn/authenticate" \
  -H "Content-Type: application/json" \
  -d '{
    "credentialId": "base64EncodedCredentialId",
    "signature": "base64EncodedSignature",
    "clientDataJSON": "base64EncodedClientData",
    "authenticatorData": "base64EncodedAuthenticatorData"
  }'
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "a1b2c3d4e5f6...",
  "session_id": "sess_abc123"
}
```

### Listing Credentials

**Endpoint:** `GET /v1/users/{userId}/webauthn/credentials`

```bash
curl -X GET "https://api.lilith.app/v1/users/user_12345/webauthn/credentials" \
  -H "Authorization: Bearer <access_token>"
```

---

## Two-Factor Authentication

### Enabling 2FA

**Step 1: Request 2FA Setup**

**Endpoint:** `POST /v1/auth/2fa/enable`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/enable" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "secret": "JBSWY3DPEHPK3PXP",
  "qrcode": "otpauth://totp/user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Lilith",
  "backup_codes": ["a1b2c3d4", "e5f6g7h8", "i9j0k1l2", "m3n4o5p6", "q7r8s9t0"]
}
```

**Step 2: Scan QR Code**

Scan the QR code (from `qrcode` URL) with an authenticator app (Google
Authenticator, Authy, 1Password).

**Step 3: Verify Setup**

**Endpoint:** `POST /v1/auth/2fa/verify`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/verify" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "123456"
  }'
```

### Login with 2FA

When logging in with 2FA enabled, provide the TOTP code:

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

### Disabling 2FA

**Endpoint:** `POST /v1/auth/2fa/disable`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/disable" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "password": "SecureP@ssw0rd!"
  }'
```

### Backup Codes

If you lose access to your authenticator app, use a backup code:

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

**Note:** Each backup code can only be used once.

### Regenerate Backup Codes

**Endpoint:** `POST /v1/auth/2fa/backup-codes/regenerate`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/backup-codes/regenerate" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "password": "SecureP@ssw0rd!"
  }'
```

**Response:**

```json
{
  "backup_codes": [
    "x1y2z3a4",
    "b5c6d7e8",
    "f9g0h1i2",
    "j3k4l5m6",
    "n7o8p9q0",
    "r1s2t3u4",
    "v5w6x7y8",
    "z9a0b1c2"
  ],
  "generated_at": "2024-01-15T12:00:00Z",
  "message": "8 new backup codes generated. Previous codes have been invalidated."
}
```

### SMS OTP (Fallback)

SMS OTP provides a fallback verification method when TOTP is unavailable.

#### Request SMS OTP

**Endpoint:** `POST /v1/auth/2fa/sms/request`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/sms/request" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "phone_number": "+1234567890"
  }'
```

**Response:**

```json
{
  "message": "Verification code sent",
  "expires_in": 300,
  "cooldown": 60
}
```

**Rate Limits:**

- Cooldown between requests: 60 seconds
- Maximum per hour: 5 requests
- Maximum per day: 10 requests

#### Verify SMS OTP

**Endpoint:** `POST /v1/auth/2fa/sms/verify`

```bash
curl -X POST "https://api.lilith.app/v1/auth/2fa/sms/verify" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "123456"
  }'
```

**Response:**

```json
{
  "verified": true,
  "message": "Phone number verified successfully"
}
```

**Security Notes:**

- SMS codes expire after 5 minutes
- Maximum 3 verification attempts per code
- Failed attempts are logged for security auditing
- SMS OTP should be used as a fallback, not primary 2FA method

#### Login with SMS OTP

When TOTP is unavailable, request SMS verification during login:

```bash
# Step 1: Login with password (returns 2FA challenge)
curl -X POST "https://api.lilith.app/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecureP@ssw0rd!"
  }'

# Response: { "requires_2fa": true, "challenge_token": "chall_abc123" }

# Step 2: Request SMS OTP
curl -X POST "https://api.lilith.app/v1/auth/2fa/sms/request" \
  -H "Content-Type: application/json" \
  -d '{
    "challenge_token": "chall_abc123",
    "method": "sms"
  }'

# Step 3: Complete login with SMS code
curl -X POST "https://api.lilith.app/v1/auth/login/2fa" \
  -H "Content-Type: application/json" \
  -d '{
    "challenge_token": "chall_abc123",
    "sms_code": "123456"
  }'
```

### MFA Best Practices

| Practice      | Recommendation                       |
| ------------- | ------------------------------------ |
| Primary 2FA   | Use TOTP or WebAuthn                 |
| Backup Method | Store backup codes securely          |
| Fallback      | Enable SMS OTP as last resort        |
| Recovery      | Keep backup email verified           |
| Device Trust  | Use "Remember this device" sparingly |

---

## Magic Link Authentication

### Overview

Magic links provide passwordless email-based authentication. Users receive a
time-limited link that authenticates them automatically.

### Request Magic Link

**Endpoint:** `POST /v1/auth/magic-link/request`

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

**Response:**

```json
{
  "message": "Magic link sent to user@example.com",
  "expires_in": 900
}
```

### Authenticate with Magic Link

The user receives an email with a link like:

```
https://app.lilith.app/auth/magic?token=abc123xyz...
```

**Endpoint:** `POST /v1/auth/magic-link/authenticate`

```bash
curl -X POST "https://api.lilith.app/v1/auth/magic-link/authenticate" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "abc123xyz..."
  }'
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "a1b2c3d4e5f6...",
  "session_id": "sess_abc123"
}
```

**Security Notes:**

- Magic links expire after 15 minutes
- Each link can only be used once
- New account created if email doesn't exist

---

## Session Management

### List Active Sessions

**Endpoint:** `GET /v1/auth/sessions`

```bash
curl -X GET "https://api.lilith.app/v1/auth/sessions" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "sessions": [
    {
      "id": "sess_abc123",
      "created_at": "2024-01-01T00:00:00Z",
      "last_accessed": "2024-01-15T10:30:00Z",
      "ip_address": "192.168.1.100",
      "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
      "is_current": true
    },
    {
      "id": "sess_def456",
      "created_at": "2024-01-10T00:00:00Z",
      "last_accessed": "2024-01-14T08:00:00Z",
      "ip_address": "10.0.0.50",
      "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0)...",
      "is_current": false
    }
  ]
}
```

### Revoke Specific Session

**Endpoint:** `DELETE /v1/auth/sessions/{sessionId}`

```bash
curl -X DELETE "https://api.lilith.app/v1/auth/sessions/sess_def456" \
  -H "Authorization: Bearer <access_token>"
```

### Revoke All Sessions

**Endpoint:** `POST /v1/auth/sessions/revoke-all`

```bash
curl -X POST "https://api.lilith.app/v1/auth/sessions/revoke-all" \
  -H "Authorization: Bearer <access_token>"
```

This logs out all devices including the current one.

### Token Lifecycle

Understanding the complete token lifecycle is essential for implementing proper
authentication in client applications.

```
                           TOKEN LIFECYCLE
    ┌─────────────────────────────────────────────────────────────┐
    │                                                             │
    │  ┌─────────────┐     ┌─────────────┐     ┌─────────────┐   │
    │  │   Login     │     │   Access    │     │   Refresh   │   │
    │  │  Request    │────►│   Token     │────►│   Token     │   │
    │  │             │     │  (15 min)   │     │   (7 days)  │   │
    │  └─────────────┘     └──────┬──────┘     └──────┬──────┘   │
    │                             │                   │          │
    │                    ┌────────▼────────┐          │          │
    │                    │  API Requests   │          │          │
    │                    │  (Authorized)   │          │          │
    │                    └────────┬────────┘          │          │
    │                             │                   │          │
    │                    ┌────────▼────────┐          │          │
    │                    │ Token Expires   │◄─────────┘          │
    │                    │   (15 min)      │   Refresh & Rotate  │
    │                    └────────┬────────┘                     │
    │                             │                              │
    │                    ┌────────▼────────┐                     │
    │                    │ Logout/Revoke   │                     │
    │                    │   All Tokens    │                     │
    │                    └─────────────────┘                     │
    └─────────────────────────────────────────────────────────────┘
```

**Lifecycle Stages:**

| Stage          | Description                                    | Duration     |
| -------------- | ---------------------------------------------- | ------------ |
| **Issuance**   | Tokens issued after successful authentication  | Immediate    |
| **Active**     | Access token valid for API requests            | 15 minutes   |
| **Refresh**    | Refresh token used to obtain new access token  | On demand    |
| **Rotation**   | Old refresh token invalidated, new pair issued | Each refresh |
| **Expiration** | Refresh token expires after 7 days             | 7 days       |
| **Revocation** | Tokens explicitly invalidated by user/admin    | Immediate    |

**Token Refresh Best Practices:**

1. **Proactive Refresh**: Refresh tokens before they expire (e.g., when 2
   minutes remain)
2. **Retry Logic**: Handle token refresh failures gracefully
3. **Concurrency**: Prevent multiple simultaneous refresh requests
4. **Fallback**: Redirect to login if refresh fails

```typescript
// Example client-side token refresh logic
async function refreshTokenIfNeeded(token: string): Promise<string> {
  const decoded = jwt.decode(token);
  const expiresIn = decoded.exp - Date.now() / 1000;

  // Refresh when less than 2 minutes remaining
  if (expiresIn < 120) {
    const response = await fetch('/v1/auth/refresh', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refresh_token: storedRefreshToken }),
    });
    const { access_token, refresh_token } = await response.json();
    storeTokens(access_token, refresh_token);
    return access_token;
  }

  return token;
}
```

**Token Revocation Scenarios:**

| Scenario          | Revocation Type           | Affected Tokens        |
| ----------------- | ------------------------- | ---------------------- |
| User logout       | Session revocation        | Current session        |
| Password change   | Full revocation           | All user tokens        |
| Security incident | Emergency revocation      | All user tokens        |
| Admin action      | Administrative revocation | Specified tokens       |
| Device compromise | Device revocation         | Specific device tokens |

**Security Events Logged:**

All token lifecycle events are recorded in the audit log:

- `TOKEN_ISSUED` - New token pair generated
- `TOKEN_VALIDATED` - Token successfully verified
- `TOKEN_ROTATION` - Refresh token rotated
- `TOKEN_REVOKED` - Token explicitly revoked
- `SUSPICIOUS_ACTIVITY` - Anomalous token usage detected

---

## Security Features

### Rate Limiting

Authentication endpoints are rate-limited to prevent brute-force attacks:

| Endpoint                  | Limit       | Window             |
| ------------------------- | ----------- | ------------------ |
| `/v1/auth/login`          | 5 attempts  | 1 minute per email |
| `/v1/auth/register`       | 3 attempts  | 1 minute per IP    |
| `/v1/auth/password/reset` | 3 attempts  | 1 hour per email   |
| `/v1/auth/refresh`        | 10 attempts | 1 minute per user  |

### Password Requirements

The Lilith API implements a modern, strength-based password policy using zxcvbn
for realistic password strength estimation. This approach is more secure than
traditional character-type requirements.

**Core Requirements:**

| Requirement            | Value                      |
| ---------------------- | -------------------------- |
| Minimum length         | 8 characters               |
| Maximum length         | 128 characters             |
| Minimum strength score | 2 (Fair)                   |
| Password history       | Last 5 passwords           |
| Breach detection       | HaveIBeenPwned integration |

**Password Strength Scores:**

| Score | Label       | Description                                   |
| ----- | ----------- | --------------------------------------------- |
| 0     | Very Weak   | Can be cracked instantly                      |
| 1     | Weak        | Can be cracked quickly                        |
| 2     | Fair        | May be cracked with effort (minimum required) |
| 3     | Strong      | Hard to crack                                 |
| 4     | Very Strong | Very hard to crack                            |

**Get Password Requirements:**

**Endpoint:** `GET /v1/auth/password/requirements`

```bash
curl -X GET "https://api.lilith.app/v1/auth/password/requirements"
```

**Response:**

```json
{
  "minLength": 8,
  "maxLength": 128,
  "minStrengthScore": 2,
  "strengthLabels": {
    "0": "very_weak",
    "1": "weak",
    "2": "fair",
    "3": "strong",
    "4": "very_strong"
  },
  "requirements": [
    "At least 8 characters",
    "Must be strong enough to resist common attacks",
    "Avoid common passwords and personal information"
  ],
  "historyCheck": true,
  "historySize": 5
}
```

**Password Change:**

**Endpoint:** `POST /v1/auth/password/change`

```bash
curl -X POST "https://api.lilith.app/v1/auth/password/change" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "current_password": "CurrentPassword123!",
    "new_password": "NewSecurePassword456!"
  }'
```

**Validation Checks:**

1. Current password verification
2. Password strength validation (zxcvbn score ≥ 2)
3. Password history check (not one of last 5 passwords)
4. Context-aware validation (not similar to email/username)

**Password Reset:**

**Endpoint:** `POST /v1/auth/password/reset-request`

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

**Reset Flow:**

1. User requests password reset (always returns success to prevent email
   enumeration)
2. Email sent with secure reset token (valid for 1 hour)
3. User submits new password with token
4. All active sessions are invalidated on successful reset

**Breach Detection:**

Passwords are checked against the HaveIBeenPwned database using k-anonymity:

- Only the first 5 characters of the password's SHA-1 hash are sent to the API
- Full hash comparison happens locally
- Prevents passwords that have appeared in known data breaches

**Password Hashing:**

Passwords are hashed using Argon2id with OWASP recommended settings:

| Parameter   | Value        |
| ----------- | ------------ |
| Algorithm   | Argon2id     |
| Memory Cost | 64 MiB       |
| Time Cost   | 3 iterations |
| Parallelism | 4 threads    |
| Hash Length | 32 bytes     |

**Error Codes:**

| Code                    | Description                                  |
| ----------------------- | -------------------------------------------- |
| `auth.weak_password`    | Password does not meet strength requirements |
| `auth.password_reuse`   | Password was previously used                 |
| `auth.invalid_password` | Current password is incorrect                |
| `auth.same_password`    | New password cannot be the same as current   |
| `password.breached`     | Password found in data breach database       |
| `password.too_short`    | Password below minimum length                |
| `password.too_long`     | Password exceeds maximum length              |

### Security Headers

All authentication responses include security headers:

```http
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
```

### Audit Logging

All authentication events are logged:

- Login attempts (success and failure)
- Token refresh operations
- Password reset requests
- Session creation and revocation
- OAuth authentication
- MFA operations
- API key usage

### Suspicious Activity Detection

The system monitors for:

- Multiple failed login attempts from same IP
- Rapid token issuance (>10 tokens in 5 minutes)
- Login from unusual locations
- Device fingerprint changes during refresh

Critical events trigger automatic account protection measures.

---

## Security Hardening

### Account Lockout

The account lockout system protects against brute-force attacks by temporarily
disabling accounts after repeated failed login attempts.

**Configuration:**

| Parameter               | Default            | Description                        |
| ----------------------- | ------------------ | ---------------------------------- |
| `maxFailedAttempts`     | 5                  | Failed attempts before lockout     |
| `lockoutDurationMs`     | 900,000 (15 min)   | Initial lockout duration           |
| `failedAttemptWindowMs` | 1,800,000 (30 min) | Window for tracking failures       |
| `progressiveLockout`    | true               | Enable progressive lockout         |
| `progressiveMultiplier` | 2                  | Multiplier for successive lockouts |
| `maxLockoutDurationMs`  | 86,400,000 (24 hr) | Maximum lockout duration           |

**Progressive Lockout:**

Each successive lockout increases the duration:

- 1st lockout: 15 minutes
- 2nd lockout: 30 minutes
- 3rd lockout: 60 minutes
- 4th lockout: 2 hours
- 5th+ lockout: 24 hours (max)

**Administrative Unlock:**

Administrators can manually unlock accounts via:

```bash
curl -X POST "https://api.lilith.app/v1/admin/accounts/{userId}/unlock" \
  -H "Authorization: Bearer <admin_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "reason": "User identity verified via phone"
  }'
```

### IP Filtering

IP-based access control protects sensitive endpoints and blocks malicious
traffic.

**Features:**

- Allow/deny lists with CIDR notation support
- Geo-restriction by country code
- Admin endpoint protection
- Proxy header support (X-Forwarded-For, CF-Connecting-IP)
- Dynamic rule management at runtime

**Configuration:**

```typescript
{
  allowList: ['10.0.0.0/8', '192.168.1.100'],
  denyList: ['45.33.32.156'],  // Known bad actors
  adminAllowList: ['10.0.0.0/8'],  // Admin-only IPs
  geoRestrictions: {
    mode: 'deny',
    countries: ['CN', 'RU', 'KP']  // Block specific countries
  },
  protectAdminEndpoints: true,
  adminEndpointPatterns: ['/admin', '/api/v1/admin']
}
```

**Response Headers:**

Blocked requests receive:

```http
HTTP/1.1 403 Forbidden
X-Blocked-Reason: ip_denied | geo_restricted | admin_access_denied
```

### Bot Detection

Behavioral analysis identifies and mitigates automated bot traffic.

**Detection Methods:**

| Method                 | Weight | Description                                    |
| ---------------------- | ------ | ---------------------------------------------- |
| User Agent Analysis    | 40%    | Detects known bots, scrapers, automation tools |
| Behavioral Patterns    | 30%    | Analyzes request patterns, timing, navigation  |
| Request Fingerprinting | 20%    | Header consistency, TLS fingerprinting         |
| Session Analysis       | 10%    | Cookie support, JS execution indicators        |

**Suspicion Scoring:**

Requests receive a suspicion score (0-100):

| Score  | Classification | Action               |
| ------ | -------------- | -------------------- |
| 0-30   | Likely Human   | Allow                |
| 31-60  | Suspicious     | CAPTCHA challenge    |
| 61-80  | Likely Bot     | Rate limit + CAPTCHA |
| 81-100 | Confirmed Bot  | Block                |

**Good Bots:**

Legitimate bots (search engines, monitoring) are allowed via User-Agent:

- Googlebot, Bingbot, DuckDuckBot
- UptimeRobot, Pingdom
- Custom allowlist patterns

### Web Application Firewall (WAF)

The WAF protects against common web attacks using pattern-based detection.

**Attack Types Detected:**

| Attack            | Detection                                | Severity |
| ----------------- | ---------------------------------------- | -------- |
| SQL Injection     | UNION, OR 1=1, DROP TABLE patterns       | Critical |
| XSS               | Script tags, event handlers, javascript: | Critical |
| Command Injection | Shell commands, backticks, pipes         | Critical |
| Path Traversal    | ../, directory access patterns           | High     |
| Header Injection  | CRLF, newline injection                  | High     |
| Protocol Attacks  | Invalid HTTP methods, oversized headers  | Medium   |

**Request Validation:**

```
┌─────────────────────────────────────────────────────────────┐
│                      WAF Request Flow                        │
├─────────────────────────────────────────────────────────────┤
│  Request → IP Check → Rate Limit → Pattern Match → Handler  │
│              │            │              │                   │
│              ▼            ▼              ▼                   │
│           Block?       Throttle?      Sanitize/Block?       │
└─────────────────────────────────────────────────────────────┘
```

**Security Headers Applied:**

```http
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()
```

**Blocked User Agents:**

Automatically blocked:

- sqlmap, nikto, nessus (security scanners)
- python-requests, curl (without legitimate context)
- Empty or missing User-Agent

### CAPTCHA Integration

CAPTCHA verification protects against automated abuse.

**Supported Providers:**

| Provider     | Features                                 |
| ------------ | ---------------------------------------- |
| reCAPTCHA v3 | Invisible, score-based (0.0-1.0)         |
| hCaptcha     | Privacy-focused, accessibility support   |
| Turnstile    | Cloudflare, no user interaction required |

**Protected Actions:**

- User registration
- Login (after failed attempts)
- Password reset requests
- Contact form submissions

**Integration Flow:**

```
┌──────────┐     ┌─────────────┐     ┌───────────────┐
│  Client  │     │ Lilith API  │     │ CAPTCHA Provider │
└────┬─────┘     └──────┬──────┘     └───────┬───────┘
     │                  │                    │
     │ 1. Get challenge │                    │
     ├─────────────────►│                    │
     │                  │                    │
     │ 2. {siteKey, provider}                │
     │◄─────────────────┤                    │
     │                  │                    │
     │ 3. Render CAPTCHA widget             │
     ├──────────────────────────────────────►│
     │                  │                    │
     │ 4. User completes challenge          │
     │◄──────────────────────────────────────┤
     │                  │                    │
     │ 5. Submit with token                 │
     ├─────────────────►│                    │
     │                  │ 6. Verify token   │
     │                  ├───────────────────►│
     │                  │                    │
     │                  │ 7. Validation result
     │                  │◄───────────────────┤
     │                  │                    │
     │ 8. Response      │                    │
     │◄─────────────────┤                    │
```

**Score Thresholds (reCAPTCHA v3):**

| Score   | Interpretation    | Action                  |
| ------- | ----------------- | ----------------------- |
| 0.9+    | Very likely human | Allow                   |
| 0.5-0.9 | Probably human    | Allow with monitoring   |
| 0.3-0.5 | Suspicious        | Additional verification |
| < 0.3   | Likely bot        | Block                   |

**Client-Side Integration:**

```typescript
// Get CAPTCHA challenge
const challenge = await client.auth.getCaptchaChallenge('login');

if (challenge.required) {
  // Render provider widget using challenge.siteKey
  const token = await renderCaptcha(challenge.provider, challenge.siteKey);

  // Include token in request
  await client.auth.login({
    email: 'user@example.com',
    password: 'password',
    captchaToken: token,
  });
}
```

### Audit Logging

Comprehensive audit logging for security events with GDPR/CCPA compliance.

**Logged Events:**

| Category       | Events                                            |
| -------------- | ------------------------------------------------- |
| Authentication | Login, logout, token refresh, failed attempts     |
| Authorization  | Permission checks, role changes, access denials   |
| Account        | Registration, password change, MFA setup, lockout |
| Security       | Bot detection, WAF blocks, IP filtering           |
| Data           | Profile updates, data exports, deletions          |

**Event Structure:**

```json
{
  "eventId": "evt_abc123",
  "eventType": "AUTH_LOGIN_SUCCESS",
  "timestamp": "2024-01-15T10:30:00Z",
  "actor": {
    "userId": "user_12345",
    "ip": "192.168.1.100",
    "userAgent": "Mozilla/5.0..."
  },
  "resource": {
    "type": "session",
    "id": "sess_xyz789"
  },
  "details": {
    "method": "password",
    "mfaUsed": true
  },
  "chainHash": "sha256:a1b2c3..."
}
```

**Chain Integrity:**

Audit logs use hash chaining for tamper detection:

- Each event includes hash of previous event
- Regular integrity verification
- Alerting on chain breaks

**Data Subject Requests (GDPR):**

```bash
# Request data export
curl -X POST "https://api.lilith.app/v1/privacy/export" \
  -H "Authorization: Bearer <token>"

# Request data deletion
curl -X POST "https://api.lilith.app/v1/privacy/delete" \
  -H "Authorization: Bearer <token>"
```

### Security Testing Summary

| Component       | Tests   | Coverage                                   |
| --------------- | ------- | ------------------------------------------ |
| Rate Limiting   | 40      | Request limits, headers, bypass protection |
| IP Filtering    | 61      | Allow/deny lists, CIDR, geo-restrictions   |
| Bot Detection   | 42      | UA analysis, behavioral scoring, actions   |
| WAF             | 53      | SQLi, XSS, command injection, headers      |
| Audit Logging   | 39      | Events, queries, exports, compliance       |
| Account Lockout | 32      | Progressive lockout, admin unlock          |
| CAPTCHA         | 39      | Provider integration, verification         |
| **Total**       | **306** | Comprehensive security coverage            |

---

## Error Responses

### Authentication Errors

| Code                    | Status | Description                           |
| ----------------------- | ------ | ------------------------------------- |
| `INVALID_CREDENTIALS`   | 401    | Email or password incorrect           |
| `ACCOUNT_LOCKED`        | 423    | Account locked due to failed attempts |
| `EMAIL_NOT_VERIFIED`    | 403    | Email verification required           |
| `2FA_REQUIRED`          | 403    | Two-factor authentication required    |
| `INVALID_TOKEN`         | 401    | JWT token invalid or expired          |
| `TOKEN_EXPIRED`         | 401    | Token has expired                     |
| `REFRESH_TOKEN_INVALID` | 401    | Refresh token invalid or revoked      |
| `SESSION_EXPIRED`       | 401    | Session no longer valid               |

### Authorization Errors

| Code                 | Status | Description                  |
| -------------------- | ------ | ---------------------------- |
| `FORBIDDEN`          | 403    | Insufficient permissions     |
| `ROLE_REQUIRED`      | 403    | Required role not assigned   |
| `IP_RESTRICTED`      | 403    | Request from unauthorized IP |
| `SCOPE_INSUFFICIENT` | 403    | API key lacks required scope |

### Example Error Response

```json
{
  "error": {
    "code": "INVALID_CREDENTIALS",
    "message": "The email or password provided is incorrect.",
    "status": 401
  }
}
```

---

## SDK Integration

### TypeScript/JavaScript

```typescript
import { LilithClient } from '@lilith/sdk';

// Initialize with API key
const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Or with user authentication
const client = new LilithClient();
await client.auth.login({
  email: 'user@example.com',
  password: 'SecureP@ssw0rd!',
});

// Make authenticated requests
const response = await client.chat.send({
  message: 'Hello',
  persona: 'buddha',
});
```

### Auto Token Refresh

The SDK automatically handles token refresh:

```typescript
const client = new LilithClient({
  accessToken: 'initial_access_token',
  refreshToken: 'refresh_token',
  onTokenRefresh: (tokens) => {
    // Store new tokens
    saveTokens(tokens);
  },
});
```

---

## Related Documentation

- [API Versioning](./api-versioning.md) - Version management
- [Rate Limits](./rate-limits.md) - Rate limiting policies
- [Error Codes](./error-codes.md) - Complete error reference
- [Webhooks](./webhooks.md) - Webhook authentication

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Security Issues**: security@lilith.app (PGP key available)
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
