# License Server API Documentation

## Overview

The License Server provides a comprehensive API for managing software licenses, validating license keys, and tracking usage. The system consists of four main services:

1. **Auth Service** - JWT token management and API authentication
2. **License API** - License validation and activation
3. **Admin API** - License management and administration
4. **Analytics Service** - Usage analytics and anomaly detection

## Base URLs

- Auth Service: `http://localhost:5001`
- License API: `http://localhost:5002`
- Analytics Service: `http://localhost:5003`
- Admin API: `http://localhost:5004`

## Authentication

### API Key Authentication

Most endpoints require an API key in the `X-API-Key` header:

```
X-API-Key: sk_your_api_key_here
```

### JWT Authentication

Some endpoints use JWT bearer tokens:

```
Authorization: Bearer your_jwt_token_here
```

## Auth Service Endpoints

### Create Access Token

Create JWT access token for license validation.

**POST** `/api/v1/auth/token`

**Headers:**
- `X-API-Key: required`

**Request Body:**
```json
{
  "license_id": "string",
  "hardware_id": "string"
}
```

**Response:**
```json
{
  "access_token": "string",
  "refresh_token": "string",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### Refresh Token

Refresh an expired access token.

**POST** `/api/v1/auth/refresh`

**Request Body:**
```json
{
  "refresh_token": "string"
}
```

### Verify Token

Verify token validity.

**POST** `/api/v1/auth/verify`

**Headers:**
- `Authorization: Bearer <token>`

### Create API Key (Admin)

Create new API key for client applications.

**POST** `/api/v1/auth/api-key`

**Headers:**
- `X-Admin-Secret: required`

**Request Body:**
```json
{
  "client_name": "string",
  "allowed_endpoints": ["array", "of", "endpoints"]
}
```

## License API Endpoints

### Validate License

Validate a license key with hardware ID.

**POST** `/api/v1/license/validate`

**Headers:**
- `X-API-Key: required`

**Request Body:**
```json
{
  "license_key": "string",
  "hardware_id": "string",
  "app_version": "string (optional)"
}
```

**Response:**
```json
{
  "valid": true,
  "license_id": "string",
  "expires_at": "2024-12-31T23:59:59Z",
  "features": ["feature1", "feature2"],
  "limits": {
    "max_devices": 5,
    "current_devices": 2
  }
}
```

### Activate License

Activate license on a new device.

**POST** `/api/v1/license/activate`

**Headers:**
- `X-API-Key: required`

**Request Body:**
```json
{
  "license_key": "string",
  "hardware_id": "string",
  "device_name": "string (optional)",
  "os_info": {
    "name": "Windows",
    "version": "10"
  }
}
```

### Heartbeat

Record license heartbeat (requires JWT).

**POST** `/api/v1/license/heartbeat`

**Headers:**
- `Authorization: Bearer <token>`

**Request Body:**
```json
{
  "session_data": {
    "custom": "data"
  }
}
```

### Create Offline Token

Generate offline validation token.

**POST** `/api/v1/license/offline-token`

**Headers:**
- `Authorization: Bearer <token>`

**Request Body:**
```json
{
  "duration_hours": 24
}
```

### Validate Offline Token

Validate an offline token.

**POST** `/api/v1/license/validate-offline`

**Request Body:**
```json
{
  "token": "string"
}
```

## Admin API Endpoints

### Create License

Create a new license.

**POST** `/api/v1/admin/licenses`

**Headers:**
- `X-Admin-API-Key: required`

**Request Body:**
```json
{
  "customer_id": "string",
  "max_devices": 5,
  "expires_in_days": 365,
  "features": ["feature1", "feature2"],
  "is_test": false,
  "metadata": {
    "custom": "data"
  }
}
```

### Get License

Get license details with statistics.

**GET** `/api/v1/admin/licenses/{license_id}`

**Headers:**
- `X-Admin-API-Key: required`

### Update License

Update license properties.

**PATCH** `/api/v1/admin/licenses/{license_id}`

**Headers:**
- `X-Admin-API-Key: required`

**Request Body:**
```json
{
  "max_devices": 10,
  "is_active": true,
  "expires_at": "2025-12-31T23:59:59Z",
  "features": ["new_feature"],
  "metadata": {}
}
```

### Delete License

Soft delete (deactivate) a license.

**DELETE** `/api/v1/admin/licenses/{license_id}`

**Headers:**
- `X-Admin-API-Key: required`

### List Licenses

Search and list licenses with filters.

**GET** `/api/v1/admin/licenses`

**Headers:**
- `X-Admin-API-Key: required`

**Query Parameters:**
- `customer_id`: Filter by customer
- `is_active`: Filter by active status
- `is_test`: Filter test licenses
- `created_after`: Filter by creation date
- `created_before`: Filter by creation date
- `expires_after`: Filter by expiration
- `expires_before`: Filter by expiration
- `page`: Page number (default: 1)
- `per_page`: Items per page (default: 50, max: 100)

### Get License Devices

Get all devices for a license.

**GET** `/api/v1/admin/licenses/{license_id}/devices`

**Headers:**
- `X-Admin-API-Key: required`

### Deactivate Device

Deactivate a specific device.

**POST** `/api/v1/admin/licenses/{license_id}/devices/deactivate`

**Headers:**
- `X-Admin-API-Key: required`

**Request Body:**
```json
{
  "hardware_id": "string",
  "reason": "string (optional)"
}
```

### Transfer License

Transfer license between devices.

**POST** `/api/v1/admin/licenses/{license_id}/transfer`

**Headers:**
- `X-Admin-API-Key: required`

**Request Body:**
```json
{
  "from_hardware_id": "string",
  "to_hardware_id": "string"
}
```

### Get License Events

Get activation events for a license.

**GET** `/api/v1/admin/licenses/{license_id}/events`

**Headers:**
- `X-Admin-API-Key: required`

**Query Parameters:**
- `hours`: Hours to look back (default: 24)

### Get License Usage

Get usage statistics for a license.

**GET** `/api/v1/admin/licenses/{license_id}/usage`

**Headers:**
- `X-Admin-API-Key: required`

**Query Parameters:**
- `days`: Days to analyze (default: 30)

### Bulk Create Licenses

Create multiple licenses at once.

**POST** `/api/v1/admin/licenses/bulk-create`

**Headers:**
- `X-Admin-API-Key: required`

**Request Body:**
```json
{
  "licenses": [
    {
      "customer_id": "string",
      "max_devices": 5,
      "expires_in_days": 365
    }
  ]
}
```

### Get Statistics

Get overall license statistics.

**GET** `/api/v1/admin/statistics`

**Headers:**
- `X-Admin-API-Key: required`

## Analytics Service Endpoints

### Analyze Patterns

Analyze usage patterns for a license.

**GET** `/api/v1/analytics/licenses/{license_id}/patterns`

**Headers:**
- `X-API-Key: required`

**Query Parameters:**
- `days`: Days to analyze (default: 30)

### Detect Anomalies

Manually trigger anomaly detection.

**POST** `/api/v1/analytics/licenses/{license_id}/anomalies/detect`

**Headers:**
- `X-API-Key: required`

### Get Risk Score

Calculate risk score for a license.

**GET** `/api/v1/analytics/licenses/{license_id}/risk-score`

**Headers:**
- `X-API-Key: required`

### Generate Usage Report

Generate usage report for all licenses.

**GET** `/api/v1/analytics/reports/usage`

**Headers:**
- `X-API-Key: required`

**Query Parameters:**
- `days`: Days to include (default: 30)

### Get Dashboard Data

Get analytics dashboard data.

**GET** `/api/v1/analytics/dashboard`

**Headers:**
- `X-API-Key: required`

## Error Responses

All endpoints use standard HTTP status codes and return errors in this format:

```json
{
  "error": "Error message",
  "error_code": "ERROR_CODE",
  "details": {}
}
```

### Common Error Codes

- `LICENSE_NOT_FOUND` - License key not found
- `LICENSE_INACTIVE` - License is deactivated
- `LICENSE_EXPIRED` - License has expired
- `DEVICE_LIMIT_EXCEEDED` - Device limit reached
- `ALREADY_ACTIVATED` - Already activated on device
- `INVALID_TOKEN` - Invalid JWT token
- `RATE_LIMIT_EXCEEDED` - Rate limit exceeded

## Rate Limiting

API requests are rate limited based on API key configuration:

- Default: 60 requests per minute, 1000 per hour
- Rate limit headers are included in responses:
  - `X-RateLimit-Limit`: Requests per minute
  - `X-RateLimit-Remaining`: Remaining requests
  - `Retry-After`: Seconds until retry (on 429 errors)

## Webhooks

The system publishes events to RabbitMQ for real-time processing:

- `license.validated` - License validation successful
- `license.validation.failed` - License validation failed
- `license.activated` - New device activated
- `license.deactivated` - License deactivated
- `license.transferred` - License transferred
- `anomaly.detected` - Anomaly detected
- `device.deactivated` - Device deactivated

## SDK Examples

### Python

```python
import requests

# Initialize client
api_key = "sk_your_api_key"
base_url = "http://localhost:5002"

# Validate license
response = requests.post(
    f"{base_url}/api/v1/license/validate",
    headers={"X-API-Key": api_key},
    json={
        "license_key": "LIC-XXXXXXXXXXXX",
        "hardware_id": "device-123"
    }
)

if response.status_code == 200:
    data = response.json()
    if data["valid"]:
        print("License is valid!")
```

### JavaScript

```javascript
const apiKey = 'sk_your_api_key';
const baseUrl = 'http://localhost:5002';

// Validate license
fetch(`${baseUrl}/api/v1/license/validate`, {
    method: 'POST',
    headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        license_key: 'LIC-XXXXXXXXXXXX',
        hardware_id: 'device-123'
    })
})
.then(response => response.json())
.then(data => {
    if (data.valid) {
        console.log('License is valid!');
    }
});
```

## Best Practices

1. **Caching**: Validation results are cached for 5 minutes. Use heartbeats for real-time tracking.

2. **Offline Support**: Generate offline tokens for temporary offline validation.

3. **Security**: 
   - Always use HTTPS in production
   - Rotate API keys regularly
   - Monitor for anomalies

4. **Rate Limiting**: Implement exponential backoff on 429 errors.

5. **Error Handling**: Always check error codes and handle appropriately.

## Migration from v1

If migrating from a previous version:

1. Update API endpoints to v1 paths
2. Add API key authentication
3. Update response parsing for new format
4. Implement heartbeat for session tracking