# Tara API Authentication Guide

Complete guide to authentication and authorization in the Tara API.

## Overview

Tara API uses JWT (JSON Web Tokens) for authentication with a refresh token
rotation strategy for enhanced security. The system supports both email/password
authentication and OAuth providers (Apple, Google).

## Authentication Flow

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         Authentication Flow                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌──────────┐         ┌──────────┐         ┌──────────┐         ┌────────┐ │
│  │  Client  │         │   API    │         │  Redis   │         │   DB   │ │
│  └────┬─────┘         └────┬─────┘         └────┬─────┘         └───┬────┘ │
│       │                    │                    │                    │      │
│       │  POST /auth/login  │                    │                    │      │
│       │───────────────────>│                    │                    │      │
│       │                    │                    │   Verify User      │      │
│       │                    │───────────────────────────────────────>│      │
│       │                    │                    │                    │      │
│       │                    │  Generate Tokens   │                    │      │
│       │                    │───────────────────>│                    │      │
│       │                    │  Store Refresh     │                    │      │
│       │                    │                    │                    │      │
│       │  {accessToken,     │                    │                    │      │
│       │   refreshToken}    │                    │                    │      │
│       │<───────────────────│                    │                    │      │
│       │                    │                    │                    │      │
│       │  GET /users/me     │                    │                    │      │
│       │  Auth: Bearer xxx  │                    │                    │      │
│       │───────────────────>│                    │                    │      │
│       │                    │  Validate JWT      │                    │      │
│       │                    │  (no DB lookup)    │                    │      │
│       │  {user data}       │                    │                    │      │
│       │<───────────────────│                    │                    │      │
│       │                    │                    │                    │      │
│       │  Token Expired     │                    │                    │      │
│       │                    │                    │                    │      │
│       │  POST /auth/refresh│                    │                    │      │
│       │───────────────────>│                    │                    │      │
│       │                    │  Verify Refresh    │                    │      │
│       │                    │───────────────────>│                    │      │
│       │                    │  Rotate Token      │                    │      │
│       │                    │<───────────────────│                    │      │
│       │  {new tokens}      │                    │                    │      │
│       │<───────────────────│                    │                    │      │
│       │                    │                    │                    │      │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Token Types

### Access Token

- **Purpose**: Authenticate API requests
- **Lifetime**: 15 minutes (configurable)
- **Storage**: Client memory (never persistent storage)
- **Format**: JWT (HS256 or RS256)

Access token payload:

```json
{
  "sub": "usr_abc123",
  "email": "user@example.com",
  "name": "John Doe",
  "role": "user",
  "subscription": "premium",
  "iat": 1705315800,
  "exp": 1705316700,
  "iss": "tara-api",
  "aud": "tara-app"
}
```

### Refresh Token

- **Purpose**: Obtain new access tokens
- **Lifetime**: 30 days (configurable)
- **Storage**: Secure, HttpOnly cookie or secure storage
- **Format**: JWT with rotation tracking
- **Rotation**: Single-use, rotated on each refresh

Refresh token payload:

```json
{
  "sub": "usr_abc123",
  "jti": "ref_xyz789",
  "family": "fam_abc123",
  "iat": 1705315800,
  "exp": 1707907800,
  "iss": "tara-api",
  "aud": "tara-refresh"
}
```

## Email/Password Authentication

### Registration

```http
POST /api/v1/auth/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePassword123!",
  "name": "John Doe",
  "acceptedTerms": true,
  "marketingConsent": false
}
```

**Password Requirements:**

- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character

**Response (201 Created):**

```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "user@example.com",
      "name": "John Doe",
      "emailVerified": false,
      "createdAt": "2024-01-15T10:30:00.000Z"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 900,
    "tokenType": "Bearer"
  }
}
```

### Login

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

{
  "email": "user@example.com",
  "password": "SecurePassword123!",
  "deviceId": "device_xyz789",
  "deviceName": "iPhone 15 Pro",
  "platform": "ios"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "user@example.com",
      "name": "John Doe",
      "emailVerified": true,
      "subscription": {
        "tier": "premium",
        "expiresAt": "2024-12-15T00:00:00.000Z"
      },
      "streak": {
        "current": 15,
        "longest": 45
      }
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 900,
    "tokenType": "Bearer"
  }
}
```

### Logout

```http
POST /api/v1/auth/logout
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
  "allDevices": false
}
```

**Options:**

- `allDevices: false` - Logout current device only
- `allDevices: true` - Logout all devices (invalidate all refresh tokens)

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "message": "Successfully logged out"
  }
}
```

## Token Refresh

### Refresh Access Token

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

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

{
  "refreshToken": "eyJhbGciOiJIUzI1NiIs..."
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 900,
    "tokenType": "Bearer"
  }
}
```

### Refresh Token Rotation

The API implements refresh token rotation for security:

1. Each refresh token can only be used once
2. Using a refresh token invalidates it and issues a new one
3. If a refresh token is reused (replay attack), the entire token family is
   invalidated
4. All sessions for the user are terminated on detected replay

```
┌──────────────────────────────────────────────────────────────────────────┐
│                    Refresh Token Rotation                                 │
├──────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  Login:                                                                   │
│  ┌─────────────────────────────────────────────────────────────────────┐ │
│  │  Refresh Token A (family: fam_1, jti: ref_a)                        │ │
│  └─────────────────────────────────────────────────────────────────────┘ │
│                                    │                                      │
│                                    ▼ (use once)                          │
│  Refresh 1:                                                               │
│  ┌─────────────────────────────────────────────────────────────────────┐ │
│  │  Refresh Token B (family: fam_1, jti: ref_b)                        │ │
│  │  Token A is invalidated                                              │ │
│  └─────────────────────────────────────────────────────────────────────┘ │
│                                    │                                      │
│                                    ▼ (use once)                          │
│  Refresh 2:                                                               │
│  ┌─────────────────────────────────────────────────────────────────────┐ │
│  │  Refresh Token C (family: fam_1, jti: ref_c)                        │ │
│  │  Token B is invalidated                                              │ │
│  └─────────────────────────────────────────────────────────────────────┘ │
│                                                                           │
│  Replay Attack (reusing Token A):                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐ │
│  │  ❌ Token A already used                                             │ │
│  │  ❌ All tokens in family fam_1 invalidated                          │ │
│  │  ❌ User must re-authenticate                                        │ │
│  └─────────────────────────────────────────────────────────────────────┘ │
│                                                                           │
└──────────────────────────────────────────────────────────────────────────┘
```

## OAuth Authentication

### Supported Providers

| Provider | Endpoint                    | Scopes             |
| -------- | --------------------------- | ------------------ |
| Apple    | `/api/v1/auth/oauth/apple`  | `name`, `email`    |
| Google   | `/api/v1/auth/oauth/google` | `profile`, `email` |

### OAuth Flow

#### 1. Initiate OAuth

```http
GET /api/v1/auth/oauth/google?redirect_uri=tara://auth/callback&state=random_state
```

**Query Parameters:**

- `redirect_uri`: Where to redirect after authentication
- `state`: CSRF protection token (must be verified on callback)

**Response**: Redirect to OAuth provider

#### 2. Handle Callback

After user authenticates with the provider:

```http
GET /api/v1/auth/oauth/google/callback?code=auth_code&state=random_state
```

**Response**: Redirect to `redirect_uri` with tokens:

```
tara://auth/callback?access_token=eyJ...&refresh_token=eyJ...&expires_in=900
```

### Sign in with Apple (Mobile)

For iOS apps using native Sign in with Apple:

```http
POST /api/v1/auth/oauth/apple/mobile
Content-Type: application/json

{
  "identityToken": "eyJraWQiOi...",
  "authorizationCode": "abc123...",
  "user": {
    "email": "user@privaterelay.appleid.com",
    "name": {
      "firstName": "John",
      "lastName": "Doe"
    }
  },
  "deviceId": "device_xyz789",
  "deviceName": "iPhone 15 Pro"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "user@privaterelay.appleid.com",
      "name": "John Doe",
      "authProvider": "apple"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 900,
    "tokenType": "Bearer",
    "isNewUser": true
  }
}
```

### Sign in with Google (Mobile)

For mobile apps using Google Sign-In SDK:

```http
POST /api/v1/auth/oauth/google/mobile
Content-Type: application/json

{
  "idToken": "eyJhbGciOi...",
  "accessToken": "ya29.a0...",
  "deviceId": "device_xyz789",
  "deviceName": "Pixel 8 Pro"
}
```

## Password Management

### Forgot Password

Request a password reset email:

```http
POST /api/v1/auth/forgot-password
Content-Type: application/json

{
  "email": "user@example.com"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "message": "If an account exists, a reset email has been sent"
  }
}
```

### Reset Password

Reset password using the token from the email:

```http
POST /api/v1/auth/reset-password
Content-Type: application/json

{
  "token": "reset_token_from_email",
  "password": "NewSecurePassword123!",
  "confirmPassword": "NewSecurePassword123!"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "message": "Password reset successfully"
  }
}
```

### Change Password (Authenticated)

Change password while logged in:

```http
POST /api/v1/auth/change-password
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "currentPassword": "OldPassword123!",
  "newPassword": "NewSecurePassword123!",
  "confirmPassword": "NewSecurePassword123!",
  "logoutOtherDevices": true
}
```

## Email Verification

### Request Verification Email

```http
POST /api/v1/auth/resend-verification
Authorization: Bearer <access_token>
```

### Verify Email

```http
POST /api/v1/auth/verify-email
Content-Type: application/json

{
  "token": "verification_token_from_email"
}
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "message": "Email verified successfully",
    "user": {
      "id": "usr_abc123",
      "emailVerified": true
    }
  }
}
```

## Device Management

### Register Device

Devices are automatically registered during login. You can also explicitly
register:

```http
POST /api/v1/users/me/devices
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "deviceId": "device_xyz789",
  "deviceName": "iPhone 15 Pro",
  "platform": "ios",
  "osVersion": "17.2",
  "appVersion": "1.0.0",
  "pushToken": "fcm_token_or_apns_token"
}
```

### List Devices

```http
GET /api/v1/users/me/devices
Authorization: Bearer <access_token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "devices": [
      {
        "id": "dev_abc123",
        "deviceId": "device_xyz789",
        "deviceName": "iPhone 15 Pro",
        "platform": "ios",
        "lastUsed": "2024-01-15T10:30:00.000Z",
        "current": true
      },
      {
        "id": "dev_def456",
        "deviceId": "device_abc123",
        "deviceName": "iPad Pro",
        "platform": "ios",
        "lastUsed": "2024-01-14T08:00:00.000Z",
        "current": false
      }
    ]
  }
}
```

### Remove Device

```http
DELETE /api/v1/users/me/devices/dev_def456
Authorization: Bearer <access_token>
```

## Security Best Practices

### Client-Side Token Storage

**Mobile (iOS/Android):**

```typescript
// Use secure storage
import * as SecureStore from 'expo-secure-store';

await SecureStore.setItemAsync('refreshToken', refreshToken);
const token = await SecureStore.getItemAsync('refreshToken');
```

**Web:**

```typescript
// Access tokens: memory only
let accessToken: string | null = null;

// Refresh tokens: HttpOnly cookies (set by server)
// Never store in localStorage or sessionStorage
```

### Handling Token Expiration

```typescript
import { TaraClient } from '@tara/sdk';

const client = new TaraClient({
  baseUrl: 'https://api.tara.app',
  onTokenExpired: async () => {
    // Automatically refresh tokens
    const refreshToken = await SecureStore.getItemAsync('refreshToken');
    const { accessToken, refreshToken: newRefreshToken } =
      await client.auth.refresh(refreshToken);

    // Store new refresh token
    await SecureStore.setItemAsync('refreshToken', newRefreshToken);

    // Return new access token to retry the request
    return accessToken;
  },
  onAuthError: async () => {
    // Redirect to login on auth failure
    navigation.navigate('Login');
  },
});
```

### Preventing CSRF

For web applications:

1. Use `SameSite=Strict` cookies for refresh tokens
2. Include CSRF token in state parameter for OAuth
3. Verify origin header on sensitive endpoints

### Rate Limiting

Authentication endpoints have strict rate limits:

| Endpoint                | Limit       | Window |
| ----------------------- | ----------- | ------ |
| `/auth/login`           | 5 attempts  | 15 min |
| `/auth/register`        | 3 attempts  | 1 hour |
| `/auth/forgot-password` | 3 attempts  | 1 hour |
| `/auth/refresh`         | 30 requests | 1 min  |

After exceeding limits, requests return `429 Too Many Requests`.

## Error Codes

| Code                    | HTTP Status | Description                      |
| ----------------------- | ----------- | -------------------------------- |
| `INVALID_CREDENTIALS`   | 401         | Email or password incorrect      |
| `USER_NOT_FOUND`        | 404         | User does not exist              |
| `EMAIL_ALREADY_EXISTS`  | 409         | Email already registered         |
| `TOKEN_EXPIRED`         | 401         | Access token has expired         |
| `TOKEN_INVALID`         | 401         | Token is malformed or invalid    |
| `REFRESH_TOKEN_INVALID` | 401         | Refresh token invalid/revoked    |
| `REFRESH_TOKEN_REUSED`  | 401         | Replay attack detected           |
| `EMAIL_NOT_VERIFIED`    | 403         | Email verification required      |
| `ACCOUNT_DISABLED`      | 403         | Account has been disabled        |
| `OAUTH_ERROR`           | 400         | OAuth authentication failed      |
| `RATE_LIMITED`          | 429         | Too many authentication attempts |

## Troubleshooting

### "Token expired" errors

1. Implement automatic token refresh in your client
2. Check that device clock is synchronized
3. Verify refresh token hasn't been invalidated

### "Refresh token invalid" errors

1. Check if user logged out on another device
2. Verify the token hasn't been rotated (replay)
3. Token family may be invalidated due to security event

### OAuth failures

1. Verify redirect URI matches exactly
2. Check OAuth provider console for errors
3. Ensure state parameter matches original request

### Account locked

After 5 failed login attempts:

1. Wait 15 minutes for automatic unlock
2. Use "Forgot Password" to reset
3. Contact support for manual unlock
