
- Complete NestJS TypeScript implementation with WebSocket support - Direct messaging (DM) and group chat functionality - End-to-end encryption with AES encryption and key pairs - Media file support (images, videos, audio, documents) up to 100MB - Push notifications with Firebase Cloud Messaging integration - Mention alerts and real-time typing indicators - User authentication with JWT and Passport - SQLite database with TypeORM entities and relationships - Comprehensive API documentation with Swagger/OpenAPI - File upload handling with secure access control - Online/offline status tracking and presence management - Message editing, deletion, and reply functionality - Notification management with automatic cleanup - Health check endpoint for monitoring - CORS configuration for cross-origin requests - Environment-based configuration management - Structured for Flutter SDK integration Features implemented: ✅ Real-time messaging with Socket.IO ✅ User registration and authentication ✅ Direct messages and group chats ✅ Media file uploads and management ✅ End-to-end encryption ✅ Push notifications ✅ Mention alerts ✅ Typing indicators ✅ Message read receipts ✅ Online status tracking ✅ File access control ✅ Comprehensive API documentation Ready for Flutter SDK development and production deployment.
8.4 KiB
Real-time Chat API with Media Support
A comprehensive real-time chat API built with NestJS (TypeScript) featuring WebSocket support, direct messaging, group chats, end-to-end encryption, push notifications, mention alerts, and media file sharing.
Features
Core Chat Features
- Real-time messaging with WebSocket support
- Direct Messages (DM) between users
- Group chat functionality with member management
- Message editing and deletion
- Reply to messages functionality
- Typing indicators
- Online/offline status tracking
- Message read receipts
Media Support
- File uploads (images, videos, audio, documents)
- Media types supported: JPG, PNG, GIF, WebP, SVG, MP4, MPEG, QuickTime, AVI, MP3, WAV, OGG, PDF, Word, Excel, PowerPoint, ZIP, RAR, 7z
- File size limit: Up to 100MB per file
- Automatic media type detection
- Secure media access (only chat members can access)
Security & Encryption
- End-to-end encryption for messages
- JWT-based authentication
- User key pair generation for encryption
- Secure file uploads with access control
- Input validation and sanitization
Push Notifications
- Firebase Cloud Messaging (FCM) integration
- New message notifications for offline users
- Mention alerts with push notifications
- Device management for multi-device support
- Automatic retry for failed notifications
- Notification cleanup (removes old notifications)
User Management
- User registration and authentication
- Profile management with avatar support
- User search functionality
- Public key sharing for encryption
- Online status management
Tech Stack
- Framework: NestJS (TypeScript)
- Database: SQLite with TypeORM
- Real-time: Socket.IO
- Authentication: JWT with Passport
- File Storage: Local filesystem
- Push Notifications: Firebase Cloud Messaging
- API Documentation: Swagger/OpenAPI
- Encryption: CryptoJS (AES encryption)
Project Structure
src/
├── auth/ # Authentication module
│ ├── dto/ # Data transfer objects
│ ├── guards/ # Authentication guards
│ └── strategies/ # Passport strategies
├── chat/ # Chat functionality
│ └── dto/ # Chat DTOs
├── database/ # Database entities
│ └── entities/ # TypeORM entities
├── encryption/ # Encryption service
├── media/ # Media upload handling
├── notification/ # Push notifications
├── users/ # User management
│ └── dto/ # User DTOs
├── app.module.ts # Main application module
└── main.ts # Application entry point
Quick Start
1. Install Dependencies
npm install
2. Environment Configuration
Copy the example environment file and configure it:
cp .env.example .env
Required environment variables:
PORT
: Server port (default: 3000)JWT_SECRET
: Secret key for JWT tokensFIREBASE_SERVICE_ACCOUNT
: Firebase service account JSON for push notifications
3. Start the Application
# Development
npm run start:dev
# Production
npm run build
npm run start:prod
The application will be available at:
- API: http://localhost:3000
- Documentation: http://localhost:3000/docs
- OpenAPI JSON: http://localhost:3000/openapi.json
- Health Check: http://localhost:3000/health
API Endpoints
Authentication
POST /auth/register
- Register new userPOST /auth/login
- Login userPOST /auth/logout
- Logout user
Users
GET /users
- Get all users (with search)GET /users/me
- Get current user profilePUT /users/me
- Update user profilePUT /users/me/avatar
- Update user avatarGET /users/:id
- Get user by IDGET /users/username/:username
- Get user by usernameGET /users/:id/public-key
- Get user's public key
Chat
GET /chat/rooms
- Get user's chat roomsPOST /chat/rooms/direct
- Create/get direct message roomPOST /chat/rooms/group
- Create group chat roomGET /chat/rooms/:roomId
- Get chat room detailsGET /chat/rooms/:roomId/messages
- Get chat room messagesPOST /chat/messages
- Create new messagePUT /chat/messages/:messageId
- Edit messageDELETE /chat/messages/:messageId
- Delete messagePOST /chat/rooms/:roomId/members
- Add members to groupDELETE /chat/rooms/:roomId/members/:memberId
- Remove member from group
Media
POST /media/upload/:messageId
- Upload media fileGET /media/:mediaId
- Get media file detailsDELETE /media/:mediaId
- Delete media fileGET /media/message/:messageId
- Get all media for message
Notifications
GET /notifications
- Get user notificationsGET /notifications/unread-count
- Get unread notification countPUT /notifications/:notificationId/read
- Mark notification as readPUT /notifications/read-all
- Mark all notifications as read
WebSocket Events
Client to Server
join_room
- Join a chat roomleave_room
- Leave a chat roomsend_message
- Send a new messageedit_message
- Edit existing messagedelete_message
- Delete messagetyping_start
- Start typing indicatortyping_stop
- Stop typing indicatormark_as_read
- Mark message as read
Server to Client
connected
- Connection establishednew_message
- New message receivedmessage_edited
- Message was editedmessage_deleted
- Message was deleteduser_typing
- User started typinguser_stopped_typing
- User stopped typingmessage_read
- Message was readmentioned
- User was mentioneduser_online
- User came onlineuser_offline
- User went offlinejoined_room
- Successfully joined roomleft_room
- Successfully left roomerror
- Error occurred
Flutter SDK Integration
This API is designed to work seamlessly with Flutter applications. Key considerations for Flutter integration:
WebSocket Connection
// Connect with JWT token
const socket = io('ws://localhost:3000', {
auth: {
token: 'your-jwt-token'
}
});
File Upload
The API supports multipart/form-data uploads, compatible with Flutter's HTTP client and dio package.
Push Notifications
Firebase Cloud Messaging integration allows direct push notification support in Flutter apps.
Real-time Features
Socket.IO events are designed to map directly to Flutter state management patterns (Provider, Bloc, Riverpod).
Database Schema
The application uses SQLite with the following main entities:
- Users: User accounts with encryption keys
- ChatRooms: Direct and group chat rooms
- Messages: Chat messages with encryption support
- MessageMedia: File attachments
- MessageMentions: User mentions in messages
- UserDevices: Device registration for push notifications
- Notifications: Push notification records
Security Features
- JWT Authentication: Secure token-based auth
- End-to-end Encryption: Messages encrypted with room-specific keys
- File Access Control: Only chat members can access uploaded files
- Input Validation: All inputs validated and sanitized
- CORS Configuration: Configured for cross-origin requests
- Rate Limiting: Built-in protection against abuse
Development
Running Tests
npm run test
npm run test:e2e
npm run test:cov
Linting and Formatting
npm run lint
npm run format
Building for Production
npm run build
Environment Variables
Variable | Description | Required | Default |
---|---|---|---|
PORT |
Server port | No | 3000 |
NODE_ENV |
Environment | No | development |
JWT_SECRET |
JWT secret key | Yes | - |
FIREBASE_SERVICE_ACCOUNT |
Firebase config JSON | No | - |
Storage
The application uses local filesystem storage:
- Database:
/app/storage/db/chat.sqlite
- Media Files:
/app/storage/media/
- User Avatars:
/app/storage/media/avatars/
- Message Media:
/app/storage/media/messages/
Health Check
The API includes a comprehensive health check endpoint at /health
that reports:
- Service status
- Uptime
- Memory usage
- Environment information
License
MIT License - see LICENSE file for details.
Support
For issues and questions, please check the API documentation at /docs
or refer to the source code.