# API Key Authentication

This document describes the API key authentication feature added to the task management application for MCP (Model Context Protocol) integration.

## Overview

The application now supports two authentication methods:
1. **JWT Tokens** - Existing authentication for web/mobile clients
2. **API Keys** - New authentication for programmatic access (MCP integration)

## API Key Features

### Security
- **256-bit keys**: Generated using `crypto.randomBytes(32).toString('hex')`
- **64-character hex strings**: Easy to identify and validate
- **Unique per user**: Each user can have only one active API key
- **Last used tracking**: Timestamps are updated on each API key usage
- **Secure storage**: Plain text storage in database (as per requirements)

### Database Schema

Three new columns added to the `Users` table:
```sql
api_key VARCHAR(64) UNIQUE NULL
api_key_created_at TIMESTAMP NULL
api_key_last_used TIMESTAMP NULL
```

## API Endpoints

### Generate API Key
**POST** `/api/user/generate-api-key`

**Authentication**: JWT token required

**Response**:
```json
{
  "success": true,
  "message": "API key generated successfully",
  "data": {
    "api_key": "a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456",
    "created_at": "2024-01-10T10:30:00.000Z",
    "warning": "Store this API key securely. You will not be able to see it again."
  }
}
```

### Get API Key Info
**GET** `/api/user/api-key-info`

**Authentication**: JWT token required

**Response**:
```json
{
  "success": true,
  "data": {
    "has_api_key": true,
    "created_at": "2024-01-10T10:30:00.000Z",
    "last_used": "2024-01-10T15:45:30.000Z"
  }
}
```

### Revoke API Key
**DELETE** `/api/user/revoke-api-key`

**Authentication**: JWT token required

**Response**:
```json
{
  "success": true,
  "message": "API key revoked successfully"
}
```

## Using API Keys

### Authorization Header Format

API keys are used in the same `Authorization` header as JWT tokens:

```http
Authorization: Bearer a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456
```

### Authentication Logic

The middleware automatically detects the authentication method:
- **64 characters**: Treated as API key
- **Less than 64 characters**: Treated as JWT token

### Example Usage

```bash
# Using curl with API key
curl -H "Authorization: Bearer a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456" \
     https://api.yourapp.com/api/plans/my-plans

# Using curl with JWT token
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
     https://api.yourapp.com/api/plans/my-plans
```

## Security Considerations

1. **API Key Storage**: Store API keys securely on the client side
2. **HTTPS Only**: Always use HTTPS when transmitting API keys
3. **Key Rotation**: Regularly generate new API keys
4. **Monitoring**: Monitor `api_key_last_used` for suspicious activity
5. **Revocation**: Immediately revoke compromised keys

## Implementation Details

### Files Modified/Created

1. **Migration**: `src/migrations/20250110000000-add-api-key-to-users.js`
2. **User Model**: Updated `src/models/User.ts`
3. **Utilities**: `src/utils/apiKeyUtils.ts`
4. **Middleware**: Updated `src/middleware/auth.ts`
5. **Controller**: Updated `src/controllers/userController.ts`
6. **Routes**: Updated `src/routes/userRoutes.ts`
7. **Types**: `src/types/apiKey.ts`

### Backward Compatibility

The implementation is fully backward compatible:
- Existing JWT authentication continues to work unchanged
- No breaking changes to existing API endpoints
- Existing users can continue using the application normally

## Migration

To apply the database changes:

```bash
npx sequelize-cli db:migrate
```

To rollback if needed:

```bash
npx sequelize-cli db:migrate:undo
``` 