# Aphrodite Domain - API Documentation

> Complete API reference for all Aphrodite microservices, protocols, and
> integrations.

---

## Overview

The Aphrodite domain provides a comprehensive suite of APIs for building adult
entertainment streaming applications. This documentation covers all public and
internal APIs across multiple protocols.

## API Categories

### REST APIs

HTTP/HTTPS endpoints for synchronous request-response operations.

| Service            | Base Path | Port | Documentation                                          |
| ------------------ | --------- | ---- | ------------------------------------------------------ |
| User Service       | `/api/v1` | 3000 | [User API](./rest/user-service.md)                     |
| Content Service    | `/api/v1` | 7001 | [Content API](./rest/content-service.md)               |
| Payment Service    | `/api/v1` | 4000 | [Payment API](./rest/payment-service.md)               |
| Analytics Service  | `/api/v1` | 7000 | [Analytics API](./rest/analytics-service.md)           |
| Moderation Service | `/api/v1` | 7002 | [Moderation API](./rest/moderation-service.md)         |
| Recommendation     | `/api/v1` | 7004 | [Recommendation API](./rest/recommendation-service.md) |

### WebSocket APIs

Real-time bidirectional communication via Socket.io.

| Service              | Port | Documentation                                          |
| -------------------- | ---- | ------------------------------------------------------ |
| Chat Service         | 5000 | [Chat WebSocket](./websocket/chat.md)                  |
| Notification Service | 7003 | [Notification WebSocket](./websocket/notifications.md) |
| Stream Service       | 5000 | [Stream WebSocket](./websocket/stream.md)              |

### gRPC APIs

High-performance RPC for service-to-service communication.

| Service        | Port  | Documentation                   |
| -------------- | ----- | ------------------------------- |
| Stream Service | 50051 | [Stream gRPC](./grpc/stream.md) |

### Device Protocols

Interactive device integration APIs.

| Device/Protocol | Type          | Documentation                              |
| --------------- | ------------- | ------------------------------------------ |
| Lovense         | REST + Events | [Lovense Protocol](./devices/lovense.md)   |
| Buttplug.io     | WebSocket     | [Buttplug Protocol](./devices/buttplug.md) |
| Handy           | REST          | [Handy Protocol](./devices/handy.md)       |
| Kiiroo          | Proprietary   | [Kiiroo Protocol](./devices/kiiroo.md)     |
| OhMiBod         | BLE           | [OhMiBod Protocol](./devices/ohmibod.md)   |
| Funscript       | File Format   | [Funscript Format](./devices/funscript.md) |

### External Integrations

Third-party service integrations.

| Category       | Documentation                                        |
| -------------- | ---------------------------------------------------- |
| Payments       | [Payment Providers](./external/payments.md)          |
| Notifications  | [Notification Services](./external/notifications.md) |
| Storage & CDN  | [Storage Services](./external/storage.md)            |
| Moderation     | [Moderation Services](./external/moderation.md)      |
| Authentication | [OAuth Providers](./external/auth.md)                |

---

## Authentication

### JWT Token Authentication

All APIs (except public endpoints) require JWT Bearer token authentication.

```http
Authorization: Bearer <access_token>
```

#### Token Types

| Token Type    | Expiration | Purpose                    |
| ------------- | ---------- | -------------------------- |
| Access Token  | 15 minutes | API request authentication |
| Refresh Token | 7 days     | Obtain new access tokens   |

#### Token Refresh Flow

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

{
  "refreshToken": "<refresh_token>"
}

Response:
{
  "accessToken": "<new_access_token>",
  "refreshToken": "<new_refresh_token>",
  "expiresIn": 900
}
```

### WebSocket Authentication

WebSocket connections authenticate via token in the connection handshake:

```typescript
const socket = io('wss://api.aphrodite.example.com', {
  auth: {
    token: '<access_token>',
  },
});
```

### API Key Authentication

Some service-to-service communications use API key authentication:

```http
X-API-Key: <api_key>
```

---

## Request/Response Formats

### Content Types

| Content Type             | Usage                 |
| ------------------------ | --------------------- |
| `application/json`       | Standard API requests |
| `multipart/form-data`    | File uploads          |
| `application/x-protobuf` | gRPC messages         |

### Standard Response Envelope

All REST APIs return responses in a standard envelope:

#### Success Response

```json
{
  "success": true,
  "data": { ... },
  "meta": {
    "timestamp": "2026-01-18T12:00:00.000Z",
    "requestId": "req_abc123"
  }
}
```

#### Error Response

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid email format",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address"
      }
    ]
  },
  "meta": {
    "timestamp": "2026-01-18T12:00:00.000Z",
    "requestId": "req_abc123"
  }
}
```

### Pagination

List endpoints support cursor-based pagination:

```http
GET /api/v1/users?cursor=<cursor>&limit=20
```

Response includes pagination metadata:

```json
{
  "success": true,
  "data": [...],
  "pagination": {
    "cursor": "next_cursor_value",
    "hasMore": true,
    "total": 150
  }
}
```

---

## Error Codes

### HTTP Status Codes

| Code | Meaning               | Description                         |
| ---- | --------------------- | ----------------------------------- |
| 200  | OK                    | Request succeeded                   |
| 201  | Created               | Resource created successfully       |
| 204  | No Content            | Request succeeded, no response body |
| 400  | Bad Request           | Invalid request parameters          |
| 401  | Unauthorized          | Missing or invalid authentication   |
| 403  | Forbidden             | Insufficient permissions            |
| 404  | Not Found             | Resource not found                  |
| 409  | Conflict              | Resource conflict (duplicate, etc.) |
| 422  | Unprocessable Entity  | Validation error                    |
| 429  | Too Many Requests     | Rate limit exceeded                 |
| 500  | Internal Server Error | Server error                        |
| 503  | Service Unavailable   | Service temporarily unavailable     |

### Application Error Codes

| Code                            | Description                       |
| ------------------------------- | --------------------------------- |
| `AUTH_INVALID_TOKEN`            | JWT token is invalid or expired   |
| `AUTH_INSUFFICIENT_PERMISSIONS` | User lacks required permissions   |
| `VALIDATION_ERROR`              | Request validation failed         |
| `RESOURCE_NOT_FOUND`            | Requested resource does not exist |
| `RESOURCE_CONFLICT`             | Resource already exists           |
| `RATE_LIMIT_EXCEEDED`           | Too many requests                 |
| `PAYMENT_FAILED`                | Payment processing failed         |
| `DEVICE_CONNECTION_FAILED`      | Device connection error           |
| `STREAM_NOT_LIVE`               | Stream is not currently live      |
| `CONTENT_BLOCKED`               | Content blocked by moderation     |

---

## Rate Limiting

### Default Limits

| Endpoint Type      | Limit       | Window   |
| ------------------ | ----------- | -------- |
| Public endpoints   | 60 req/min  | 1 minute |
| Authenticated      | 120 req/min | 1 minute |
| Upload endpoints   | 10 req/min  | 1 minute |
| WebSocket messages | 100 msg/min | 1 minute |
| Payment endpoints  | 30 req/min  | 1 minute |

### Rate Limit Headers

```http
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 115
X-RateLimit-Reset: 1737194400
```

### Handling Rate Limits

When rate limited, the API returns:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 45

{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please retry after 45 seconds."
  }
}
```

---

## Versioning

### API Version

All APIs are versioned via URL path:

```
/api/v1/users
/api/v2/users (future)
```

### Version Lifecycle

| Status     | Description                          |
| ---------- | ------------------------------------ |
| Current    | Actively developed and supported     |
| Deprecated | Still functional but will be removed |
| Sunset     | No longer available                  |

Deprecation notices are provided via response headers:

```http
Deprecation: true
Sunset: Sat, 01 Jan 2027 00:00:00 GMT
Link: </api/v2/users>; rel="successor-version"
```

---

## WebSocket Event Patterns

### Event Naming Convention

Events follow a namespace pattern:

```
<domain>:<action>
```

Examples:

- `room:join` - Join a chat room
- `message:send` - Send a message
- `notification:received` - Notification received

### Event Acknowledgments

Socket.io supports acknowledgment callbacks:

```typescript
// Client
socket.emit('message:send', payload, (response) => {
  if (response.success) {
    console.log('Message sent:', response.messageId);
  }
});

// Server response
callback({ success: true, messageId: 'msg_123' });
```

### Error Events

Errors are emitted as events:

```typescript
socket.on('error', (error) => {
  console.error('Socket error:', error.code, error.message);
});
```

---

## Health Checks

All services expose health check endpoints:

### Liveness Probe

```http
GET /healthz

Response:
{
  "status": "ok",
  "timestamp": "2026-01-18T12:00:00.000Z"
}
```

### Readiness Probe

```http
GET /readyz

Response:
{
  "status": "ready",
  "dependencies": {
    "database": "connected",
    "redis": "connected",
    "kafka": "connected"
  }
}
```

---

## SDKs and Client Libraries

### Official Libraries

| Language     | Package             | Repository              |
| ------------ | ------------------- | ----------------------- |
| TypeScript   | `@aphrodite/client` | `libs/aphrodite/client` |
| React        | `@aphrodite/react`  | `libs/aphrodite/react`  |
| React Native | `@aphrodite/mobile` | `libs/aphrodite/mobile` |

### Client Initialization

```typescript
import { AphroditeClient } from '@aphrodite/client';

const client = new AphroditeClient({
  baseUrl: 'https://api.aphrodite.example.com',
  apiVersion: 'v1',
  auth: {
    getToken: async () => await getAccessToken(),
    onTokenRefresh: (token) => storeToken(token),
  },
});
```

---

## Webhooks

### Webhook Delivery

Webhooks are delivered via HTTP POST with:

- JSON payload
- Signature header for verification
- Retry logic (3 attempts with exponential backoff)

### Webhook Signature Verification

```typescript
import crypto from 'crypto';

function verifyWebhookSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}
```

### Webhook Events

| Event Type          | Description                    |
| ------------------- | ------------------------------ |
| `payment.completed` | Payment successfully processed |
| `payment.failed`    | Payment processing failed      |
| `payment.refunded`  | Payment was refunded           |
| `stream.started`    | Stream went live               |
| `stream.ended`      | Stream ended                   |
| `user.verified`     | User identity verified         |
| `content.moderated` | Content moderation completed   |

---

## Testing

### Sandbox Environment

A sandbox environment is available for testing:

```
Base URL: https://sandbox-api.aphrodite.example.com
```

### Test Credentials

| Resource        | Test Value               |
| --------------- | ------------------------ |
| Test User Email | `test@aphrodite.example` |
| Test Card       | `4242424242424242`       |
| Test Device ID  | `test_device_001`        |

---

## Support

### API Status

Check API status at: `https://status.aphrodite.example.com`

### Developer Resources

- API Changelog: [CHANGELOG.md](../CHANGELOG.md)
- Migration Guide: [MIGRATION.md](../MIGRATION.md)
- SDK Documentation: [SDK.md](../SDK.md)

---

## Document History

| Date       | Version | Changes                   |
| ---------- | ------- | ------------------------- |
| 2026-01-18 | 1.0.0   | Initial API documentation |
