# Chat Service

> Real-time chat service with End-to-End Encryption (E2EE) for GoodGo platform, built on ASP.NET Core SignalR.

## Overview

Chat Service provides secure real-time communication in the microservices system with:

- **End-to-End Encryption** - X3DH key exchange protocol with AES-256-GCM
- **Real-time Communication** - ASP.NET Core SignalR with WebSockets/SSE/Long Polling
- **Scalability** - Redis Backplane or Azure SignalR Service
- **User & Group Management** - Conversations, multi-device user mapping
- **AI Integration** - Smart chatbot with streaming response
- **High Performance** - MessagePack protocol
- **Resiliency** - Auto reconnect, Stateful Reconnect

## Requirements

| Requirement | Version |
|-------------|---------|
| .NET SDK | 10.0.101+ |
| Docker | 24.0+ |
| PostgreSQL | 16+ |
| Redis | 7+ |

## Quick Start

### 1. Configure Environment

```bash
# Copy environment template
cp .env.example .env

# Edit configuration
nano .env
```

### 2. Run with Docker

```bash
# Start all services
docker-compose up -d

# View logs
docker-compose logs -f chatservice-api
```

### 3. Run Locally

```bash
dotnet restore
dotnet build
dotnet run --project src/ChatService.API
```

## Feature Details

### A. End-to-End Encryption (E2EE)

| Feature | Description |
|---------|-------------|
| **X3DH Protocol** | Extended Triple Diffie-Hellman for key exchange |
| **Identity Keys** | Long-term Curve25519 identity key pair |
| **Signed Pre-Keys** | Rotated periodically (every 30 days) |
| **One-Time Pre-Keys** | Forward secrecy for initial messages |
| **AES-256-GCM** | Symmetric encryption for messages |

```csharp
// Server stores ONLY encrypted content - cannot decrypt without client's private key
public class Message
{
    public string EncryptedContent { get; }  // Base64 encoded
    public string Nonce { get; }              // IV for AES-GCM
    public string? AuthTag { get; }           // Authentication tag
}
```

### B. Real-time Communication

| Feature | Description |
|---------|-------------|
| **SignalR Hub** | Central hub handling all real-time connections |
| **Multi-Transport** | Auto-select WebSockets → SSE → Long Polling |
| **Streaming** | IAsyncEnumerable support for streaming AI responses |

### C. Scalability

| Solution | Use Case |
|----------|----------|
| **Redis Backplane** | On-premise, multi-instance deployment |
| **Azure SignalR Service** | Azure cloud, serverless scenarios |
| **Sticky Sessions** | Fallback when not using Azure SignalR |

### D. AI Integration

| Feature | Description |
|---------|-------------|
| **AI Assistant** | Chatbot in group (trigger: @gpt) |
| **Streaming Response** | Push response chunks in real-time |
| **Context History** | Save chat history for AI context |

## API Endpoints

### Conversations API

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/conversations` | Create new conversation |
| `GET` | `/api/conversations` | Get user's conversations |
| `GET` | `/api/conversations/{id}` | Get specific conversation |

### Messages API

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/messages` | Send encrypted message |
| `GET` | `/api/messages/conversation/{id}` | Get messages in conversation |
| `POST` | `/api/messages/read` | Mark messages as read |

### Keys API (E2EE)

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/keys/register` | Register E2EE key bundle |
| `POST` | `/api/keys/rotate` | Rotate signed pre-key |
| `POST` | `/api/keys/prekeys` | Upload one-time pre-keys |
| `GET` | `/api/keys/bundle/{userId}` | Get user's key bundle |
| `GET` | `/api/keys/my-bundle` | Get own key bundle status |

### SignalR Hub Methods

| Method | Direction | Description |
|--------|-----------|-------------|
| `JoinRoom` | Client → Server | Join conversation room |
| `LeaveRoom` | Client → Server | Leave conversation room |
| `SendMessage` | Client → Server | Send encrypted message |
| `SendTypingIndicator` | Client → Server | Send typing status |
| `MarkMessageRead` | Client → Server | Mark message as read |
| `StreamAIResponse` | Client → Server | Request AI streaming response |
| `ReceiveMessage` | Server → Client | Receive new message |
| `UserJoined` | Server → Client | User joined notification |
| `UserLeft` | Server → Client | User left notification |
| `TypingIndicator` | Server → Client | Typing indicator |
| `MessageDelivered` | Server → Client | Message delivered status |
| `MessageRead` | Server → Client | Message read status |

### Health Endpoints

| Endpoint | Purpose |
|----------|---------|
| `/health` | Full status |
| `/health/live` | Liveness probe |
| `/health/ready` | Readiness probe |

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `ASPNETCORE_ENVIRONMENT` | Environment | `Development` |
| `DATABASE_URL` | PostgreSQL connection | - |
| `REDIS_URL` | Redis connection | - |
| `AZURE_SIGNALR_CONNECTION` | Azure SignalR (optional) | - |
| `OPENAI_API_KEY` | OpenAI API key (optional) | - |

### appsettings.json

```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=chatservice;Username=postgres;Password=postgres",
    "Redis": "localhost:6379"
  },
  "SignalR": {
    "EnableMessagePack": true,
    "StatefulReconnectBufferSize": 32768
  },
  "AI": {
    "Provider": "OpenAI",
    "Model": "gpt-4",
    "MaxHistoryMessages": 20
  }
}
```

## Deployment

### Docker Build

```bash
docker build -t chatservice:latest .
docker run -p 5000:8080 --env-file .env chatservice:latest
```

### Kubernetes

See [ARCHITECTURE.md](./ARCHITECTURE.md) for detailed Kubernetes configuration with Sticky Sessions.

## References

- [ASP.NET Core SignalR](https://docs.microsoft.com/en-us/aspnet/core/signalr/)
- [Redis Backplane](https://docs.microsoft.com/en-us/aspnet/core/signalr/redis-backplane)
- [Azure SignalR Service](https://docs.microsoft.com/en-us/azure/azure-signalr/)
- [X3DH Protocol](https://signal.org/docs/specifications/x3dh/)

## License

Proprietary - GoodGo Platform
