A production-ready, full-stack MERN secure chat application with end-to-end encryption, JWT authentication, and mandatory two-factor authentication (2FA)
Quick Start โข Features โข Demo โข Installation โข API Docs โข Security โข Deployment
Get SafeTalk running in under 5 minutes:
# 1. Clone the repository
git clone https://github.com/Omsiddh/SafeTalk.git
cd SafeTalk
# 2. Setup Backend
cd server
npm install
cp .env.example .env # Edit with your MongoDB URI and email config
npm run dev # Starts on http://localhost:5000
# 3. Setup Frontend (new terminal)
cd ../client
npm install
cp .env.example .env # Edit with API endpoints
npm run dev # Starts on http://localhost:5173
# 4. Open http://localhost:5173 and create your account!Requirements: Node.js 20+, MongoDB 7+, and a valid SMTP email account.
SafeTalk is a modern, secure messaging platform that prioritizes user privacy through end-to-end encryption. Built with the MERN stack and TypeScript, it combines the real-time capabilities of Socket.io with encryption to ensure your conversations remain truly private.
๐ข Status: Active Development
๐ Version: 1.0.0
๐
Last Updated: November 2025
โ
Production Ready: Core features complete
- โ Authentication System: Complete with JWT & 2FA
- โ End-to-End Encryption: RSA-2048 + AES-256-GCM implementation
- โ Real-time Messaging: Socket.io WebSocket connections
- โ Admin Panel: User management and analytics
- โ Security Features: Rate limiting, account lockout, security headers
- โ Responsive UI: Modern WhatsApp-inspired interface
- โ Email System: OTP delivery and notifications
- Zero-Knowledge Architecture: Your messages are encrypted on your device before being sent
- No Plaintext Storage: Server never has access to unencrypted messages
- Modern Stack: Built with the latest technologies and best practices
- Production Ready: Comprehensive security measures and error handling
SafeTalk implements industry-standard security measures to ensure your conversations remain private:
- ๐ End-to-End Encryption: RSA-2048 + AES-256-GCM encryption
- ๐ก๏ธ Mandatory 2FA: Email OTP or TOTP (Google Authenticator/Authy)
- ๐ Zero-Knowledge Architecture: Server never sees plaintext messages
- ๐ JWT Authentication: RS256 signing with secure refresh tokens
- โก Password Security: Argon2id hashing with unique salts
- ๐ ๏ธ Security Headers: Helmet.js + rate limiting + CORS protection
- ๐ Perfect Forward Secrecy: New encryption key for every message
- ๐ซ Account Lockout: Automatic protection against brute force attacks
- Quick Start
- Overview
- Features
- Tech Stack
- Security Architecture
- Installation
- Configuration
- Usage
- API Documentation
- Security Mechanisms
- Deployment
- Testing
- Development
- Changelog
- Contributing
- License
- Acknowledgments
- โ User Registration & Authentication: Secure account creation with mandatory 2FA setup
- โ Real-time Messaging: Instant message delivery with Socket.io WebSocket connections
- โ Contact Management: Search and add users by username or email
- โ Message History: Encrypted conversation storage with efficient retrieval
- โ Typing Indicators: Real-time typing status updates for better UX
- โ Read Receipts: Message delivery and read confirmation system
- โ Online Status: Real-time user presence indicators
- โ Responsive UI: WhatsApp-inspired interface with Tailwind CSS
- โ Profile Management: Update profile information and security settings
- โ End-to-End Encryption: Messages encrypted client-side, decrypted only by recipient
- โ RSA Key Management: Automatic 2048-bit key pair generation and secure storage
- โ AES Message Encryption: Per-message AES-256 keys for perfect forward secrecy
- โ Two-Factor Authentication: Choose between Email OTP or Authenticator App (TOTP)
- โ Account Security: Rate limiting, failed login tracking, automatic account lockout
- โ Secure Headers: CSP, HSTS, X-Frame-Options, and more via Helmet.js
- โ Password Strength: Enforced complexity requirements and strength validation
- โ Session Management: Secure JWT tokens with httpOnly refresh cookies
- โ Input Validation: Comprehensive validation and sanitization using Joi
- โ CSRF Protection: Token-based protection against cross-site request forgery
- โ Clean Interface: Modern, intuitive chat interface with smooth animations
- โ Real-time Updates: Live message delivery and instant status updates
- โ Search Functionality: Fast user and conversation search
- โ Responsive Design: Seamless experience on desktop, tablet, and mobile
- โ Toast Notifications: User-friendly error and success feedback
- โ Loading States: Clear loading indicators for better UX
- โ Error Handling: Graceful error handling with helpful messages
- โ Offline Support: Graceful handling of connection issues
- โ Dashboard Statistics: Real-time system metrics and user analytics
- โ User Management: Search, filter, ban, unlock, and manage users
- โ Role Management: Promote/demote users to admin
- โ Activity Monitoring: Track logins, messages, and system activity
- โ Analytics: Visual charts for user growth and message activity
- โ Action Logging: Complete audit trail of admin actions
- โ Security Controls: Ban/unban users, unlock accounts, delete users
- โ Detailed User Views: Complete user profiles with message statistics
๐ View Admin Panel Documentation - Complete guide to admin features
| Technology | Purpose | Version |
|---|---|---|
| React | UI library for building interactive interfaces | 19.2.0 |
| TypeScript | Type-safe JavaScript for better code quality | 5.9.3 |
| Vite | Lightning-fast build tool and dev server | 7.1.9 |
| Tailwind CSS | Utility-first CSS framework for styling | 4.1.14 |
| React Router | Client-side routing and navigation | 6.30.1 |
| Socket.io Client | Real-time bidirectional communication | 4.8.1 |
| Lucide React | Beautiful & consistent icon library | 0.294.0 |
| React Hot Toast | Elegant toast notifications | 2.6.0 |
| Crypto-JS | Client-side AES encryption | 4.2.0 |
| Node Forge | RSA encryption and key management | 1.3.1 |
| Technology | Purpose | Version |
|---|---|---|
| Node.js | JavaScript runtime environment | 20+ |
| Express.js | Fast, minimalist web framework | 4.21.2 |
| MongoDB | NoSQL database for flexible data storage | 8.19.1 |
| Mongoose | Elegant MongoDB object modeling | 8.19.1 |
| Socket.io | Real-time server-client communication | 4.8.1 |
| JWT | Secure token-based authentication | 9.0.2 |
| Technology | Purpose | Version |
|---|---|---|
| Argon2 | Advanced password hashing (PHC winner) | 0.31.2 |
| Node Forge | RSA encryption and key management | 1.3.1 |
| Crypto-JS | AES-256-GCM message encryption | 4.2.0 |
| Speakeasy | TOTP implementation for 2FA | 2.0.0 |
| Helmet.js | HTTP security headers middleware | 7.2.0 |
| Express Rate Limit | API rate limiting and DoS protection | 7.5.1 |
| Technology | Purpose | Version |
|---|---|---|
| Nodemailer | Email sending for OTP delivery | 6.10.1 |
| QRCode | QR code generation for TOTP setup | 1.5.4 |
| Joi | Object schema validation and sanitization | 17.13.3 |
| CORS | Cross-origin resource sharing | 2.8.5 |
| Dotenv | Environment variable management | 16.6.1 |
| ESLint | Code linting and quality assurance | 9.37.0 |
| Nodemon | Development server with hot reload | 3.1.10 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ End-to-End Encryption Flow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. KEY GENERATION (During Registration)
โโโโโโโโโโโโโโโ
โ Client โ โ Generates RSA-2048 key pair
โโโโโโโโโโโโโโโ
โ
โโโ Public Key โ Stored in MongoDB
โโโ Private Key โ Encrypted with password hash, stored locally
2. MESSAGE ENCRYPTION (Sending)
โโโโโโโโโโโโโโโ
โ Sender โ
โโโโโโโโโโโโโโโ
โ
โโโ Generate random AES-256 key
โโโ Encrypt message with AES-GCM (ciphertext + IV)
โโโ Fetch recipient's public RSA key
โโโ Encrypt AES key with RSA-OAEP
โโโ Send {ciphertext, iv, encryptedAesKey} to server
3. MESSAGE STORAGE (Server - Zero Knowledge)
โโโโโโโโโโโโโโโ
โ Server โ โ Stores encrypted data (no plaintext)
โโโโโโโโโโโโโโโ
โ
โโโ MongoDB: {ciphertext, iv, encryptedAesKey}
4. MESSAGE DECRYPTION (Receiving)
โโโโโโโโโโโโโโโ
โ Recipient โ
โโโโโโโโโโโโโโโ
โ
โโโ Decrypt AES key using private RSA key
โโโ Decrypt ciphertext using AES key + IV
โโโ Display plaintext message
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Authentication & Authorization Flow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. REGISTRATION
User Input โ Validation โ Argon2id Hashing โ 2FA Setup โ Account Created
2. LOGIN (Phase 1: Credentials)
Email + Password โ Argon2id Verify โ Generate Session Token โ Request 2FA
3. LOGIN (Phase 2: Two-Factor)
Email OTP / TOTP Code โ Verify โ Issue JWT + Refresh Token โ Login Success
4. SESSION MANAGEMENT
โโโโโโโโโโโโโโโโโโโโ
โ Access Token โ โ Short-lived (1 hour), used for API requests
โ (JWT) โ
โโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโ
โ Refresh Token โ โ Long-lived (7 days), httpOnly cookie
โ (JWT) โ โ Used to get new access token
โโโโโโโโโโโโโโโโโโโโ
5. TOKEN REFRESH
Expired Access Token โ Send Refresh Token โ Validate โ Issue New Access Token
| Feature | Implementation | Purpose |
|---|---|---|
| Password Hashing | Argon2id with unique salt | Protect against rainbow table attacks |
| Key Derivation | PBKDF2 for private key encryption | Secure key storage |
| Perfect Forward Secrecy | New AES key per message | Past messages safe if key compromised |
| Rate Limiting | Express Rate Limit | Prevent brute force attacks |
| Account Lockout | Failed attempt tracking | Automatic protection against attacks |
| HTTPS Enforcement | TLS 1.3 | Encrypted data in transit |
| Security Headers | Helmet.js | XSS, Clickjacking, MIME sniffing protection |
| Input Validation | Joi schemas | Prevent injection attacks |
| CORS Protection | Origin whitelist | Prevent unauthorized API access |
Ensure you have the following installed on your system:
| Requirement | Minimum Version | Recommended | Download |
|---|---|---|---|
| Node.js | v18.0.0 | v20.x LTS | nodejs.org |
| MongoDB | v6.0 | v7.x | mongodb.com |
| npm | v9.0.0 | v10.x | (Comes with Node.js) |
| Git | v2.x | Latest | git-scm.com |
git clone https://github.com/Omsiddh/SafeTalk.git
cd SafeTalk# Navigate to server directory
cd server
# Install dependencies
npm install
# Create environment file
copy .env.template .env
# Edit .env with your configuration (see Configuration section)
# Start development server
npm run dev
# OR for production
npm startThe backend server will start on http://localhost:5000
# Navigate to client directory (from project root)
cd client
# Install dependencies
npm install
# Create environment file
copy .env.template .env
# Edit .env with your configuration
# Start development server
npm run devThe frontend will start on http://localhost:5173
Open your browser and navigate to:
http://localhost:5173
Create a .env file in the server/ directory:
# ========================================
# Database Configuration
# ========================================
MONGODB_URI=mongodb://localhost:27017/safetalk
# For MongoDB Atlas: mongodb+srv://username:password@cluster.mongodb.net/safetalk
# ========================================
# JWT Configuration
# ========================================
# Generate secure secrets: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters-long
JWT_REFRESH_SECRET=your-super-secret-refresh-key-minimum-32-characters-long
JWT_EXPIRE=1h
JWT_REFRESH_EXPIRE=7d
# ========================================
# Server Configuration
# ========================================
PORT=5000
NODE_ENV=development
CLIENT_URL=http://localhost:5173
# ========================================
# Email Configuration (Gmail Example)
# ========================================
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-16-digit-app-password
# ========================================
# Application Settings
# ========================================
APP_NAME=SafeTalk
FRONTEND_URL=http://localhost:5173
# ========================================
# Security Settings (Optional)
# ========================================
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=15m
RATE_LIMIT_WINDOW=15m
RATE_LIMIT_MAX=100Create a .env file in the client/ directory:
# ========================================
# API Configuration
# ========================================
VITE_API_BASE_URL=http://localhost:5000/api
VITE_SOCKET_URL=http://localhost:5000
# ========================================
# App Configuration
# ========================================
VITE_APP_NAME=SafeTalk
VITE_APP_VERSION=1.0.0
# ========================================
# Feature Flags (Optional)
# ========================================
VITE_ENABLE_DEBUG=false
VITE_ENABLE_ANALYTICS=false-
Enable 2FA on your Gmail account
- Go to Google Account Security
- Enable 2-Step Verification
-
Generate App Password
- Visit App Passwords
- Select "Mail" and "Other (Custom name)"
- Enter "SafeTalk" and generate
- Copy the 16-character password to
EMAIL_PASS
-
Configure .env
EMAIL_HOST=smtp.gmail.com EMAIL_PORT=587 EMAIL_SECURE=false EMAIL_USER=your-email@gmail.com EMAIL_PASS=your-16-digit-app-password
Outlook/Office 365
EMAIL_HOST=smtp.office365.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@outlook.com
EMAIL_PASS=your-passwordSendGrid
EMAIL_HOST=smtp.sendgrid.net
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=apikey
EMAIL_PASS=your-sendgrid-api-key# Install MongoDB Community Edition
# Windows: Download from mongodb.com
# macOS: brew install mongodb-community
# Linux: Follow official docs
# Start MongoDB service
# Windows: Net start MongoDB
# macOS/Linux: sudo systemctl start mongod
# Use in .env
MONGODB_URI=mongodb://localhost:27017/safetalk- Create account at MongoDB Atlas
- Create a free cluster
- Configure database access (create user)
- Configure network access (add your IP or 0.0.0.0/0 for development)
- Get connection string from "Connect" โ "Connect your application"
- Update
.env:MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/safetalk?retryWrites=true&w=majority
# For JWT_SECRET and JWT_REFRESH_SECRET
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"- Use strong, unique secrets for JWT tokens
- Enable HTTPS/TLS in production
- Use environment-specific MongoDB databases
- Set
NODE_ENV=production - Configure proper CORS origins (not wildcard)
- Use secure email provider with authentication
- Enable rate limiting with appropriate limits
- Set up proper logging and monitoring
- Regular security audits and updates
Terminal 1 - Backend:
cd server
npm run devOutput: Server running on http://localhost:5000
Terminal 2 - Frontend:
cd client
npm run devOutput: Local: http://localhost:5173
- Navigate to
http://localhost:5173 - Click "Register" or "Sign Up"
- Fill in your details:
- Email address (valid email required for OTP)
- Username (unique, alphanumeric)
- Strong password (min 8 chars, uppercase, lowercase, number, special char)
- Choose 2FA method:
- Email OTP: Receive codes via email
- Authenticator App: Use Google Authenticator, Authy, or similar
- Complete registration process
Option A: Email OTP
- Verification codes sent to your registered email
- Valid for 3 minutes
- Automatic setup, no additional configuration needed
Option B: Authenticator App (TOTP)
- Scan QR code with your authenticator app
- Or manually enter the secret key
- Enter the 6-digit code to verify setup
- Save backup codes (if provided)
- Enter your email and password
- Complete 2FA verification
- Access the secure chat interface
- Click the search icon or search bar
- Type username or email address
- Select user from results
- Start conversation by sending a message
- Select a conversation from the sidebar
- Type your message in the input box
- Press Enter or click Send button
- Messages are automatically encrypted before sending
| Feature | Description |
|---|---|
| ๐ข Online Status | Green dot indicates user is online |
| โจ๏ธ Typing Indicators | See when someone is typing |
| โ Sent Confirmation | Single check mark |
| โโ Delivered Status | Double check marks |
| ๐๏ธ Read Receipts | Blue check marks |
- View History: Scroll up to load older messages
- Search Messages: Use search to find specific conversations
- Delete Messages: (Feature can be implemented)
- Block Users: (Feature can be implemented)
- โ Use a unique, strong password (12+ characters)
- โ Include uppercase, lowercase, numbers, and symbols
- โ Don't reuse passwords from other services
- โ Consider using a password manager
- โ Use authenticator app instead of email OTP when possible
- โ Keep backup codes in a secure location
- โ Never share your 2FA codes with anyone
- โ Report suspicious 2FA requests immediately
- โ Always log out on shared or public computers
- โ Keep your devices and browsers updated
- โ Verify you're on the correct URL before logging in
- โ Don't click suspicious links claiming to be from SafeTalk
- โ Enable screen lock on your devices
Can't receive email OTP codes
- Check spam/junk folder
- Verify email address is correct
- Wait 3 minutes and request a new code
- Check server email configuration
- Try authenticator app instead
Messages not sending
- Check internet connection
- Verify you're logged in
- Check if recipient exists
- Refresh the page
- Check browser console for errors
Can't connect to Socket.io
- Verify backend server is running
- Check VITE_SOCKET_URL in client/.env
- Check browser console for WebSocket errors
- Try disabling browser extensions
- Check firewall settings
2FA setup issues
- Ensure time is synchronized on your device
- Try manual entry instead of QR code
- Verify authenticator app is up to date
- Contact support for account recovery
POST /api/auth/register
Content-Type: application/json
Request Body:
{
"email": "user@example.com",
"username": "johndoe",
"password": "SecurePass123!",
"twoFAMethod": "email" // or "totp"
}
Response (201 Created):
{
"success": true,
"message": "Registration successful",
"data": {
"userId": "64abc123...",
"email": "user@example.com",
"username": "johndoe",
"twoFAMethod": "email"
}
}POST /api/auth/login
Content-Type: application/json
Request Body:
{
"email": "user@example.com",
"password": "SecurePass123!"
}
Response (200 OK):
{
"success": true,
"message": "Please verify 2FA",
"requiresTwoFA": true,
"userId": "64abc123...",
"twoFAMethod": "email"
}POST /api/auth/verify-2fa
Content-Type: application/json
Request Body:
{
"userId": "64abc123...",
"code": "123456"
}
Response (200 OK):
{
"success": true,
"message": "Login successful",
"accessToken": "eyJhbGciOiJSUzI1NiIs...",
"user": {
"id": "64abc123...",
"email": "user@example.com",
"username": "johndoe"
}
}
Note: Refresh token is set as httpOnly cookiePOST /api/auth/refresh
Cookie: refreshToken=<refresh_token>
Response (200 OK):
{
"success": true,
"accessToken": "eyJhbGciOiJSUzI1NiIs..."
}POST /api/auth/logout
Authorization: Bearer <access_token>
Response (200 OK):
{
"success": true,
"message": "Logged out successfully"
}POST /api/messages/send
Authorization: Bearer <access_token>
Content-Type: application/json
Request Body:
{
"receiverId": "64def456...",
"ciphertext": "U2FsdGVkX1...",
"iv": "1a2b3c4d5e6f...",
"encryptedAesKey": "encrypted_base64_key..."
}
Response (201 Created):
{
"success": true,
"message": "Message sent successfully",
"data": {
"messageId": "64ghi789...",
"senderId": "64abc123...",
"receiverId": "64def456...",
"timestamp": "2025-10-20T10:30:00.000Z",
"status": "sent"
}
}GET /api/messages/conversation/{userId}
Authorization: Bearer <access_token>
Query Parameters:
- page (optional): Page number for pagination (default: 1)
- limit (optional): Messages per page (default: 50)
Response (200 OK):
{
"success": true,
"data": {
"messages": [
{
"id": "64ghi789...",
"senderId": "64abc123...",
"receiverId": "64def456...",
"ciphertext": "U2FsdGVkX1...",
"iv": "1a2b3c4d5e6f...",
"encryptedAesKey": "encrypted_base64_key...",
"timestamp": "2025-10-20T10:30:00.000Z",
"status": "read"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalMessages": 234,
"hasMore": true
}
}
}PUT /api/messages/read/{conversationId}
Authorization: Bearer <access_token>
Response (200 OK):
{
"success": true,
"message": "Messages marked as read"
}GET /api/users/profile
Authorization: Bearer <access_token>
Response (200 OK):
{
"success": true,
"data": {
"id": "64abc123...",
"email": "user@example.com",
"username": "johndoe",
"publicKey": "-----BEGIN PUBLIC KEY-----...",
"twoFAMethod": "email",
"createdAt": "2025-01-15T08:00:00.000Z",
"lastLogin": "2025-10-20T10:00:00.000Z"
}
}GET /api/users/search?query=john
Authorization: Bearer <access_token>
Query Parameters:
- query (required): Search term (username or email)
- limit (optional): Max results (default: 20)
Response (200 OK):
{
"success": true,
"data": [
{
"id": "64def456...",
"username": "johndoe",
"email": "john@example.com",
"publicKey": "-----BEGIN PUBLIC KEY-----...",
"isOnline": true
}
]
}GET /api/users/{userId}
Authorization: Bearer <access_token>
Response (200 OK):
{
"success": true,
"data": {
"id": "64def456...",
"username": "johndoe",
"publicKey": "-----BEGIN PUBLIC KEY-----...",
"isOnline": true,
"lastSeen": "2025-10-20T10:25:00.000Z"
}
}PUT /api/users/profile
Authorization: Bearer <access_token>
Content-Type: application/json
Request Body:
{
"username": "newusername",
"email": "newemail@example.com"
}
Response (200 OK):
{
"success": true,
"message": "Profile updated successfully"
}// Connect to Socket.io server
const socket = io('http://localhost:5000', {
auth: { token: accessToken }
});
// Join a conversation room
socket.emit('join_conversation', {
conversationId: 'user1_user2'
});
// Send a message
socket.emit('send_message', {
receiverId: '64def456...',
ciphertext: 'U2FsdGVkX1...',
iv: '1a2b3c4d5e6f...',
encryptedAesKey: 'encrypted_base64_key...'
});
// Start typing indicator
socket.emit('typing_start', {
conversationId: 'user1_user2'
});
// Stop typing indicator
socket.emit('typing_stop', {
conversationId: 'user1_user2'
});
// Mark message as read
socket.emit('message_read', {
messageId: '64ghi789...',
conversationId: 'user1_user2'
});// Receive new message
socket.on('new_message', (data) => {
// data: { message, sender }
console.log('New message:', data);
});
// Message sent confirmation
socket.on('message_sent', (data) => {
// data: { messageId, timestamp, status }
console.log('Message sent:', data);
});
// User typing notification
socket.on('user_typing', (data) => {
// data: { userId, username, isTyping }
console.log('User typing:', data);
});
// User online status
socket.on('user_online', (data) => {
// data: { userId, username }
console.log('User online:', data);
});
// User offline status
socket.on('user_offline', (data) => {
// data: { userId, lastSeen }
console.log('User offline:', data);
});
// Message read receipt
socket.on('message_read', (data) => {
// data: { messageId, readBy, readAt }
console.log('Message read:', data);
});
// Error handling
socket.on('error', (error) => {
console.error('Socket error:', error);
});All protected endpoints require a valid JWT access token in the Authorization header:
Authorization: Bearer <access_token>
Tokens are issued after successful 2FA verification and expire after 1 hour. Use the refresh token endpoint to obtain a new access token.
Standard error response format:
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": {} // Optional additional information
}
}Common HTTP status codes:
400- Bad Request (validation errors)401- Unauthorized (authentication required)403- Forbidden (insufficient permissions)404- Not Found429- Too Many Requests (rate limited)500- Internal Server Error
// 1. Generate random AES key (256-bit)
const aesKey = CryptoJS.lib.WordArray.random(256/8);
// 2. Encrypt message with AES-256-GCM
const encrypted = CryptoJS.AES.encrypt(
messageText,
aesKey,
{ mode: CryptoJS.mode.GCM }
);
// 3. Get recipient's RSA public key
const recipientPublicKey = await fetchPublicKey(recipientId);
// 4. Encrypt AES key with RSA-OAEP
const encryptedAesKey = forge.pki.publicKeyEncrypt(
aesKey.toString(),
recipientPublicKey,
'RSA-OAEP'
);
// 5. Send encrypted payload to server
{
ciphertext: encrypted.ciphertext.toString(Base64),
iv: encrypted.iv.toString(Base64),
encryptedAesKey: btoa(encryptedAesKey)
}// 1. Decrypt AES key using RSA private key
const aesKey = forge.pki.privateKeyDecrypt(
atob(encryptedAesKey),
privateKey,
'RSA-OAEP'
);
// 2. Decrypt message with AES key
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: CryptoJS.enc.Base64.parse(ciphertext) },
CryptoJS.enc.Hex.parse(aesKey),
{ iv: CryptoJS.enc.Base64.parse(iv) }
);
// 3. Convert to plaintext
const plaintext = decrypted.toString(CryptoJS.enc.Utf8);// Registration - Hash password
const hashedPassword = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3, // 3 iterations
parallelism: 4, // 4 parallel threads
hashLength: 32, // 32-byte hash
saltLength: 16 // 16-byte salt
});
// Login - Verify password
const isValid = await argon2.verify(hashedPassword, password);// Generate Access Token (RS256)
const accessToken = jwt.sign(
{ userId, email, username },
privateKey,
{
algorithm: 'RS256',
expiresIn: '1h',
issuer: 'SafeTalk'
}
);
// Generate Refresh Token
const refreshToken = jwt.sign(
{ userId, tokenId: uuidv4() },
refreshSecret,
{
expiresIn: '7d',
issuer: 'SafeTalk'
}
);// Generate 6-digit OTP
const otp = crypto.randomInt(100000, 999999).toString();
// Hash OTP before storing
const hashedOtp = await argon2.hash(otp);
// Store with expiration
await EmailOTP.create({
userId,
hashedOtp,
expiresAt: new Date(Date.now() + 3 * 60 * 1000) // 3 minutes
});
// Send via email
await sendEmail({
to: userEmail,
subject: 'SafeTalk - Verification Code',
text: `Your verification code is: ${otp}`
});// Generate secret during setup
const secret = speakeasy.generateSecret({
name: `SafeTalk (${email})`,
issuer: 'SafeTalk',
length: 32
});
// Generate QR code for scanning
const qrCode = await QRCode.toDataURL(secret.otpauth_url);
// Verify TOTP code
const isValid = speakeasy.totp.verify({
secret: secret.base32,
encoding: 'base32',
token: userEnteredCode,
window: 1 // Allow 30-second time drift
});// Global rate limiter
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Max 100 requests
message: 'Too many requests',
standardHeaders: true,
legacyHeaders: false
});
// Strict limiter for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5, // Max 5 attempts
skipSuccessfulRequests: true
});// Track failed attempts
const MAX_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
if (user.failedLoginAttempts >= MAX_ATTEMPTS) {
const lockoutEnd = new Date(
user.lastFailedLogin.getTime() + LOCKOUT_DURATION
);
if (new Date() < lockoutEnd) {
throw new Error('Account temporarily locked');
}
}
// Reset on successful login
user.failedLoginAttempts = 0;
user.lastFailedLogin = null;app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", process.env.CLIENT_URL],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"]
}
},
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true
},
frameguard: { action: 'deny' },
noSniff: true,
xssFilter: true,
referrerPolicy: { policy: 'no-referrer' }
}));app.use(cors({
origin: process.env.CLIENT_URL,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['Content-Range', 'X-Content-Range']
}));// Registration validation
const registerSchema = Joi.object({
email: Joi.string()
.email()
.required()
.max(255),
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.min(8)
.max(128)
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/)
.required()
.messages({
'string.pattern.base': 'Password must contain uppercase, lowercase, number, and special character'
}),
twoFAMethod: Joi.string()
.valid('email', 'totp')
.required()
});
// Sanitize input
const sanitizedData = validator.escape(userInput);| Practice | Implementation | Benefit |
|---|---|---|
| Password Hashing | Argon2id with salt | Resistant to rainbow tables and brute force |
| Encryption at Rest | Private keys encrypted with user password | Keys protected even if database compromised |
| Encryption in Transit | HTTPS/TLS 1.3 | Network traffic encrypted |
| Token Expiration | Short-lived access tokens | Limited window for token theft |
| HttpOnly Cookies | Refresh tokens in httpOnly cookies | Protected from XSS attacks |
| CSRF Protection | SameSite cookie attribute | Prevents cross-site request forgery |
| Input Validation | Joi schema validation | Prevents injection attacks |
| Output Encoding | Automatic escaping | Prevents XSS attacks |
| Rate Limiting | Per-endpoint limits | Prevents DoS and brute force |
| Account Lockout | Failed attempt tracking | Automatic brute force protection |
| Security Headers | Comprehensive Helmet.js config | Multiple layer protection |
| Zero Knowledge | Server never sees plaintext | Maximum privacy |
| Perfect Forward Secrecy | New AES key per message | Past messages protected |
| Audit Logging | Comprehensive activity logs | Security monitoring |
- npm audit: Check for vulnerable dependencies
- Snyk: Automated security testing
- OWASP ZAP: Web application security scanner
- Burp Suite: Security testing platform
- Dependabot: Automated dependency updates
# Check for vulnerabilities
npm audit
npm audit fix
# Update dependencies
npm update
# Check outdated packages
npm outdatedSafeTalk/
โ
โโโ ๐ README.md # Project documentation
โโโ ๐ LICENSE # MIT License
โโโ ๐ .gitignore # Git ignore rules
โ
โโโ ๐ server/ # Backend Node.js application
โ โโโ ๐ package.json # Backend dependencies & scripts
โ โโโ ๐ .env.template # Environment variables template
โ โโโ ๐ .env # Environment configuration (gitignored)
โ โ
โ โโโ ๐ src/ # Source code
โ โ โโโ ๐ server.js # Main Express server & app initialization
โ โ โโโ ๐ socket.js # Socket.io configuration & handlers
โ โ โ
โ โ โโโ ๐ config/ # Configuration files
โ โ โ โโโ ๐ database.js # MongoDB connection setup
โ โ โ โโโ ๐ index.js # General app configuration
โ โ โ
โ โ โโโ ๐ middleware/ # Express middleware
โ โ โ โโโ ๐ auth.js # JWT authentication middleware
โ โ โ โโโ ๐ rateLimiter.js # Rate limiting middleware
โ โ โ โโโ ๐ validation.js # Request validation middleware
โ โ โ
โ โ โโโ ๐ models/ # Mongoose data models
โ โ โ โโโ ๐ User.js # User schema (credentials, keys, 2FA)
โ โ โ โโโ ๐ Message.js # Message schema (encrypted data)
โ โ โ โโโ ๐ EmailOTP.js # Email OTP schema (temp codes)
โ โ โ
โ โ โโโ ๐ routes/ # API route handlers
โ โ โ โโโ ๐ auth.js # Authentication routes
โ โ โ โโโ ๐ users.js # User management routes
โ โ โ โโโ ๐ messages.js # Message operations routes
โ โ โ โโโ ๐ debug.js # Development/debug routes
โ โ โ
โ โ โโโ ๐ utils/ # Utility functions
โ โ โโโ ๐ crypto.js # RSA encryption utilities
โ โ โโโ ๐ jwt.js # JWT token generation/verification
โ โ โโโ ๐ totp.js # TOTP/2FA utilities
โ โ โโโ ๐ email.js # Email sending (Nodemailer)
โ โ โโโ ๐ validation.js # Input validation schemas (Joi)
โ โ
โ โโโ ๐ scripts/ # Utility scripts
โ โโโ ๐ generateToken.js # Generate test JWT tokens
โ โโโ ๐ checkUser.js # Check user in database
โ
โโโ ๐ client/ # Frontend React application
โโโ ๐ package.json # Frontend dependencies & scripts
โโโ ๐ .env.template # Environment variables template
โโโ ๐ .env # Environment configuration (gitignored)
โโโ ๐ vite.config.ts # Vite build configuration
โโโ ๐ tsconfig.json # TypeScript configuration
โโโ ๐ tsconfig.app.json # App-specific TS config
โโโ ๐ tsconfig.node.json # Node-specific TS config
โโโ ๐ eslint.config.js # ESLint configuration
โโโ ๐ index.html # HTML entry point
โโโ ๐ README.md # Client documentation
โ
โโโ ๐ public/ # Static assets
โ โโโ ๐ผ๏ธ favicon.ico # App icon
โ โโโ ๐ผ๏ธ logo.png # SafeTalk logo
โ
โโโ ๐ src/ # Source code
โโโ ๐ main.tsx # React app entry point
โโโ ๐ App.jsx # Main app component & routing
โโโ ๐ TestApp.jsx # Test/development component
โโโ ๐ index.css # Global styles (Tailwind)
โ
โโโ ๐ pages/ # Page-level components
โ โโโ ๐ Login.jsx # Login page
โ โโโ ๐ Register.jsx # Registration page
โ โโโ ๐ Setup2FA.jsx # 2FA setup (TOTP/Email)
โ โโโ ๐ Verify2FA.jsx # 2FA verification page
โ โโโ ๐ RegenerateTOTP.jsx # TOTP regeneration
โ โโโ ๐ ChatRoom.jsx # Main chat interface
โ โโโ ๐ Profile.jsx # User profile page
โ
โโโ ๐ components/ # Reusable components
โ โโโ ๐ ChatList.jsx # Conversation list sidebar
โ โโโ ๐ MessageBubble.jsx # Individual message display
โ โโโ ๐ InputBox.jsx # Message input component
โ
โโโ ๐ context/ # React Context providers
โ โโโ ๐ AuthContext.jsx # Authentication state management
โ
โโโ ๐ hooks/ # Custom React hooks
โ โโโ ๐ useSocket.js # Socket.io connection hook
โ
โโโ ๐ utils/ # Utility functions
โโโ ๐ api.js # API client & HTTP requests
โโโ ๐ crypto.js # Client-side encryption (RSA/AES)
โโโ ๐ socket.js # Socket.io client setup
server.js: Express app initialization, middleware setup, route mountingsocket.js: WebSocket event handlers for real-time messagingmodels/User.js: User schema with password hashing, public keys, 2FA settingsmodels/Message.js: Message schema storing encrypted contentmiddleware/auth.js: JWT verification and authenticationutils/crypto.js: RSA key generation and encryption helpersutils/jwt.js: Token generation, signing, and verification
App.jsx: Main component with React Router setuppages/ChatRoom.jsx: Main chat interface with message list and inputcomponents/ChatList.jsx: Sidebar with user list and conversationsutils/crypto.js: Client-side RSA and AES encryption/decryptioncontext/AuthContext.jsx: Global authentication state and user datahooks/useSocket.js: Socket.io connection management and event handling
We welcome contributions to SafeTalk! Whether you're fixing bugs, improving documentation, or adding new features, your help is appreciated.
-
Fork the Repository
# Click the 'Fork' button on GitHub # Then clone your fork git clone https://github.com/your-username/SafeTalk.git cd SafeTalk
-
Create a Feature Branch
git checkout -b feature/amazing-feature # Or for bug fixes git checkout -b fix/bug-description -
Make Your Changes
- Write clean, readable code
- Follow existing code style and conventions
- Add comments for complex logic
- Update documentation as needed
-
Test Your Changes
# Run backend tests cd server npm test # Run frontend tests cd client npm test # Test manually in browser npm run dev
-
Commit Your Changes
git add . git commit -m "feat: add amazing feature" # Or git commit -m "fix: resolve bug with message encryption"
-
Push to Your Fork
git push origin feature/amazing-feature
-
Open a Pull Request
- Go to the original SafeTalk repository
- Click "New Pull Request"
- Select your fork and branch
- Provide a clear description of your changes
- Link any related issues
Follow the Conventional Commits specification:
<type>(<scope>): <subject>
<body>
<footer>
Types:
feat: New featurefix: Bug fixdocs: Documentation changesstyle: Code style changes (formatting, missing semicolons, etc.)refactor: Code refactoringperf: Performance improvementstest: Adding or updating testschore: Maintenance taskssecurity: Security improvements
Examples:
feat(auth): add OAuth2 login support
fix(chat): resolve message duplication issue
docs(readme): update installation instructions
security(crypto): upgrade to RSA-4096 encryption- JavaScript/TypeScript: Follow ESLint configuration
- Indentation: 2 spaces
- Quotes: Single quotes for JS/TS
- Semicolons: Use semicolons
- Naming: camelCase for variables/functions, PascalCase for components/classes
- โ Write self-documenting code with clear variable names
- โ Keep functions small and focused (single responsibility)
- โ Add JSDoc comments for complex functions
- โ Handle errors gracefully with try-catch blocks
- โ Validate all user inputs
- โ Write unit tests for new features
- โ Update documentation for API changes
โ ๏ธ Never commit sensitive data (.env files, keys, passwords)โ ๏ธ Always validate and sanitize user inputsโ ๏ธ Use parameterized queries to prevent SQL injectionโ ๏ธ Follow OWASP security best practicesโ ๏ธ Test security features thoroughlyโ ๏ธ Report security vulnerabilities privately (see Security Policy)
Found a bug? Help us fix it!
Before reporting:
- Search existing issues to avoid duplicates
- Verify the bug exists in the latest version
- Collect relevant information (error messages, logs, screenshots)
Creating a bug report:
- Go to Issues
- Click "New Issue" โ "Bug Report"
- Fill out the template with:
- Clear, descriptive title
- Steps to reproduce
- Expected behavior
- Actual behavior
- Environment (OS, browser, Node.js version)
- Screenshots or error logs
- Possible solution (if you have one)
Have an idea for a new feature?
- Check if the feature has been requested before
- Create a new issue with "Feature Request" label
- Describe:
- The problem you're trying to solve
- Your proposed solution
- Alternative solutions considered
- Additional context or mockups
# Backend tests
cd server
npm test
# Frontend tests
cd client
npm test
# Run with coverage
npm test -- --coverage- Write unit tests for utility functions
- Write integration tests for API endpoints
- Test error cases and edge conditions
- Aim for high code coverage (>80%)
Before submitting your PR, make sure:
- Code follows the project's style guidelines
- Self-review of code completed
- Comments added for complex logic
- Documentation updated (README, API docs, etc.)
- No new warnings or errors
- Tests added/updated and all passing
- Changes are backward compatible (or breaking changes documented)
- Commit messages follow convention
- Branch is up-to-date with main
- Automated Checks: CI/CD runs tests and linters
- Maintainer Review: Project maintainers review code
- Feedback: Address any requested changes
- Approval: Once approved, PR will be merged
- Release: Changes included in next release
Contributors will be:
- Listed in the project's contributors section
- Mentioned in release notes for significant contributions
- Given credit in relevant documentation
- Discord: Join our community (link coming soon)
- Email: contact@safetalk.com (set up if needed)
- Discussions: Use GitHub Discussions for questions
- Issues: For bug reports and feature requests
- Group Chats: Create and manage group conversations
- Voice Messages: Record and send audio messages
- File Sharing: Send encrypted files and documents
- Message Reactions: React to messages with emojis
- Message Editing: Edit sent messages
- Message Deletion: Delete messages for everyone
- User Status: Custom status messages and availability
- Dark Mode: Toggle between light and dark themes
- Voice Calls: Peer-to-peer encrypted voice calls
- Video Calls: Peer-to-peer encrypted video calls
- Screen Sharing: Share screen during calls
- Message Search: Search through conversation history
- Media Gallery: View shared photos and videos
- Push Notifications: Real-time notifications
- Mobile Apps: iOS and Android applications
- Self-Destructing Messages: Auto-delete after time period
- Message Forwarding: Forward messages to other users
- Backup & Restore: Encrypted backup of conversations
- Multi-Device Support: Sync across multiple devices
- Advanced Admin Panel: User management and analytics
- Blockchain Integration: Decentralized identity verification
- Federation Support: Connect with other SafeTalk instances
- Desktop Applications: Native Electron apps
- End-to-End Encrypted Calls: WebRTC with encryption
- Compliance Certifications: SOC 2, ISO 27001
- Open Protocol: Standardized protocol for interoperability
- Socket.io reconnection handling needs improvement
- Large file encryption performance optimization needed
- Message pagination could be smoother
- Mobile responsive design refinements
Have ideas for SafeTalk? We'd love to hear them!
- Open a Feature Request
- Join our Discussions
| Metric | Value | Notes |
|---|---|---|
| Message Latency | ~50-100ms | Including encryption overhead |
| Concurrent Users | 1000+ | Per server instance |
| Database Operations | <10ms | Average query time |
| File Size Limit | 10MB | Configurable |
| Messages/Second | 500+ | Per server instance |
- Horizontal Scaling: Deploy multiple server instances
- Load Balancing: Use NGINX or cloud load balancers
- Database Sharding: Partition data across multiple MongoDB instances
- Caching: Implement Redis for session storage and caching
- CDN: Use CDN for static assets
- Message Queue: Implement RabbitMQ for async processing
Initial Release
- โ User registration and authentication
- โ End-to-end encryption (RSA + AES)
- โ Two-factor authentication (Email OTP & TOTP)
- โ Real-time messaging with Socket.io
- โ Typing indicators and read receipts
- โ User search and contact management
- โ Responsive UI with Tailwind CSS
- โ Security headers and rate limiting
- โ JWT-based session management
- โ Comprehensive API documentation
- Added TOTP authentication support
- Improved encryption performance
- Enhanced error handling
- UI/UX improvements
- Initial alpha release
- Basic messaging functionality
- Email OTP authentication
- Simple encryption implementation
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2025 SafeTalk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
What this means:
- โ Commercial use allowed
- โ Modification allowed
- โ Distribution allowed
- โ Private use allowed
โ ๏ธ Liability limitedโ ๏ธ Warranty not provided
# 1. Clone repository
git clone https://github.com/Omsiddh/SafeTalk.git
cd SafeTalk/server
# 2. Install dependencies
npm install --production
# 3. Create production environment file
cp .env.example .env
# Edit .env with production values
# 4. Build and start
npm start# 1. Navigate to client directory
cd client
# 2. Install dependencies
npm install
# 3. Create production environment
cp .env.example .env
# Configure production API endpoints
# 4. Build for production
npm run build
# 5. Preview build (optional)
npm run previewBackend (Server):
# Install Heroku CLI
# Login to Heroku
heroku login
# Create app
heroku create safetalk-server
# Configure environment variables
heroku config:set NODE_ENV=production
heroku config:set MONGODB_URI=your-mongodb-atlas-uri
heroku config:set JWT_SECRET=your-production-secret
heroku config:set EMAIL_USER=your-email
heroku config:set EMAIL_PASS=your-app-password
# Deploy
git subtree push --prefix server heroku mainFrontend (Client):
# Build and deploy to Netlify/Vercel
npm run build
# Upload dist/ folder to hosting servicePrerequisites:
# Update system
sudo apt update && sudo apt upgrade -y
# Install Node.js 20+
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Install MongoDB
sudo apt-get install -y mongodb
# Install PM2 (Process Manager)
sudo npm install -g pm2
# Install Nginx (Reverse Proxy)
sudo apt-get install -y nginxDeployment Script:
# Clone and setup
git clone https://github.com/Omsiddh/SafeTalk.git
cd SafeTalk
# Backend setup
cd server
npm install --production
cp .env.example .env
# Configure .env file
# Start with PM2
pm2 start src/server.js --name "safetalk-server"
pm2 startup
pm2 save
# Frontend setup
cd ../client
npm install
npm run build
# Copy to web directory
sudo cp -r dist/* /var/www/safetalk/Nginx Configuration:
# /etc/nginx/sites-available/safetalk
server {
listen 80;
server_name your-domain.com;
# Frontend
location / {
root /var/www/safetalk;
try_files $uri $uri/ /index.html;
}
# Backend API
location /api/ {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
# Socket.io WebSocket
location /socket.io/ {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Docker Compose Setup:
# docker-compose.yml
version: '3.8'
services:
mongodb:
image: mongo:7
container_name: safetalk-mongo
restart: unless-stopped
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=securepassword
volumes:
- mongodb_data:/data/db
ports:
- "27017:27017"
backend:
build: ./server
container_name: safetalk-server
restart: unless-stopped
environment:
- NODE_ENV=production
- MONGODB_URI=mongodb://admin:securepassword@mongodb:27017/safetalk?authSource=admin
depends_on:
- mongodb
ports:
- "5000:5000"
frontend:
build: ./client
container_name: safetalk-client
restart: unless-stopped
ports:
- "80:80"
depends_on:
- backend
volumes:
mongodb_data:Server Dockerfile:
# server/Dockerfile
FROM node:20-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy source code
COPY src/ ./src/
# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
# Change ownership
RUN chown -R nodejs:nodejs /app
USER nodejs
# Expose port
EXPOSE 5000
# Start application
CMD ["npm", "start"]Client Dockerfile:
# client/Dockerfile
FROM node:20-alpine as builder
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy source code
COPY . .
# Build application
RUN npm run build
# Production image
FROM nginx:alpine
# Copy built files
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Expose port
EXPOSE 80
# Start nginx
CMD ["nginx", "-g", "daemon off;"]- Strong JWT Secrets: Generate cryptographically secure secrets
- Environment Variables: Never commit secrets to version control
- Database Security: Use strong credentials and connection strings
- HTTPS/TLS: Enable SSL certificates (Let's Encrypt recommended)
- CORS Configuration: Whitelist only trusted domains
- Rate Limiting: Adjust limits based on expected traffic
- Firewall: Configure iptables/ufw to block unnecessary ports
- SSH Security: Disable password auth, use key-based authentication
- System Updates: Keep OS and packages updated
- Process Management: Use PM2 or similar for process monitoring
- Log Management: Configure log rotation and monitoring
- Backup Strategy: Regular database and file backups
- Input Validation: All user inputs validated and sanitized
- Error Handling: No sensitive information in error messages
- Security Headers: Helmet.js configured properly
- Content Security Policy: Strict CSP headers
- Session Security: Secure cookie settings
- Admin Access: Secure admin panel access
// server/src/routes/health.js
import express from 'express';
import mongoose from 'mongoose';
const router = express.Router();
router.get('/health', (req, res) => {
const health = {
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
database: mongoose.connection.readyState === 1 ? 'Connected' : 'Disconnected',
memory: process.memoryUsage(),
version: process.env.npm_package_version || '1.0.0'
};
res.status(200).json(health);
});
export default router;# Install monitoring tools
npm install --save express-prom-bundle prom-client
# Set up Prometheus metrics
# Configure Grafana dashboards
# Set up alerting for critical metrics# .github/workflows/deploy.yml
name: Deploy SafeTalk
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
services:
mongodb:
image: mongo:7
ports:
- 27017:27017
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: |
server/package-lock.json
client/package-lock.json
- name: Install Backend Dependencies
run: |
cd server
npm ci
- name: Install Frontend Dependencies
run: |
cd client
npm ci
- name: Run Tests
run: |
cd server
npm test
cd ../client
npm test
- name: Build Frontend
run: |
cd client
npm run build
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to production
run: |
# Add deployment commands here
echo "Deploying to production..."cd server
# Install test dependencies
npm install --save-dev jest supertest
# Run unit tests
npm test
# Run integration tests
npm run test:integration
# Run tests with coverage
npm run test:coveragecd client
# Install test dependencies
npm install --save-dev @testing-library/react @testing-library/jest-dom vitest
# Run unit tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageserver/
tests/
unit/
crypto.test.js
auth.test.js
validation.test.js
integration/
auth.api.test.js
messages.api.test.js
admin.api.test.js
fixtures/
testUsers.js
testMessages.js
client/
src/
__tests__/
components/
ChatList.test.tsx
MessageBubble.test.tsx
utils/
crypto.test.ts
api.test.ts
pages/
Login.test.tsx
ChatRoom.test.tsx
- Test individual functions and components
- Mock external dependencies
- Cover edge cases and error scenarios
- Aim for 80%+ code coverage
- Test API endpoints end-to-end
- Test authentication flows
- Test real database operations
- Test Socket.io connections
- Test authentication bypass attempts
- Test injection vulnerabilities
- Test rate limiting effectiveness
- Test encryption/decryption flows
| Tool | Version | Purpose |
|---|---|---|
| Node.js | 20+ | Runtime environment |
| npm | 10+ | Package manager |
| MongoDB | 7+ | Database |
| Git | 2.x | Version control |
| VS Code | Latest | Recommended IDE |
VS Code Extensions:
{
"recommendations": [
"ms-vscode.vscode-typescript-next",
"bradlc.vscode-tailwindcss",
"ms-vscode.vscode-json",
"mongodb.mongodb-vscode",
"ms-vscode.vscode-eslint",
"esbenp.prettier-vscode"
]
}ESLint Configuration:
// .eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
es2020: true,
node: true,
},
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}Backend Development:
# Start development server with hot reload
npm run dev
# Start production server
npm start
# Run linting
npm run lint
# Fix linting issues
npm run lint:fix
# Run tests
npm test
# Generate API documentation
npm run docsFrontend Development:
# Start development server
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview
# Run type checking
npm run type-check
# Run linting
npm run lint// Enable debug logging
process.env.DEBUG = 'safetalk:*';
// Debug specific modules
process.env.DEBUG = 'safetalk:auth,safetalk:socket';
// VS Code launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Server",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/server/src/server.js",
"env": {
"NODE_ENV": "development",
"DEBUG": "safetalk:*"
},
"skipFiles": ["<node_internals>/**"]
}
]
}// Enable debug mode in development
if (import.meta.env.DEV) {
window.safetalkDebug = {
auth: () => console.log('Auth state:', useAuth()),
socket: () => console.log('Socket state:', useSocket()),
crypto: {
testEncryption: () => {
// Test encryption/decryption
}
}
};
}// Use explicit types
interface UserProfile {
id: string;
username: string;
email: string;
lastLogin?: Date;
}
// Use enums for constants
enum MessageStatus {
SENT = 'sent',
DELIVERED = 'delivered',
READ = 'read'
}
// Use async/await over Promises
const fetchUser = async (id: string): Promise<UserProfile> => {
try {
const response = await api.get(`/users/${id}`);
return response.data;
} catch (error) {
throw new Error(`Failed to fetch user: ${error.message}`);
}
};// Use functional components with TypeScript
interface ChatMessageProps {
message: Message;
isOwn: boolean;
onDelete?: (messageId: string) => void;
}
const ChatMessage: React.FC<ChatMessageProps> = ({
message,
isOwn,
onDelete
}) => {
// Component implementation
return (
<div className={`message ${isOwn ? 'own' : 'other'}`}>
{/* Message content */}
</div>
);
};
export default ChatMessage;# Main branches
main # Production-ready code
develop # Development branch
# Feature branches
feature/auth-improvements
feature/message-reactions
feature/group-chat
# Hotfix branches
hotfix/security-patch
hotfix/critical-bug-fix# Commit message format
<type>(<scope>): <description>
[optional body]
[optional footer(s)]
# Examples
feat(auth): add two-factor authentication
fix(chat): resolve message ordering issue
docs(readme): update installation instructions
test(crypto): add encryption unit tests
refactor(api): improve error handling- โ Complete authentication system with JWT and 2FA
- โ End-to-end encrypted messaging
- โ Real-time communication with Socket.io
- โ Admin panel with user management
- โ Responsive UI with modern design
- โ Production-ready security features
- โ React 19.2.0 with TypeScript
- โ Node.js with Express.js backend
- โ MongoDB with Mongoose ODM
- โ Socket.io for real-time features
- โ Vite 7.1.9 for development and building
- โ Tailwind CSS 4.1.14 for styling
- โ RSA-2048 + AES-256-GCM encryption
- โ Argon2id password hashing
- โ Rate limiting and account lockout
- โ Security headers with Helmet.js
- โ CSRF protection and input validation
- โ Comprehensive README with setup instructions
- โ API documentation with examples
- โ Security architecture explanations
- โ Deployment guides for multiple platforms
- ๐ Group chat functionality
- ๐ File and image sharing
- ๐ Message reactions and replies
- ๐ Push notifications
- ๐ Mobile app (React Native)
- ๐ Video and voice calls
- ๐ Screen sharing
- ๐ Message search and archiving
- ๐ Backup and export features
- ๐ Advanced admin analytics
- ๐ Federated messaging (ActivityPub)
- ๐ Blockchain-based identity verification
- ๐ Advanced cryptographic features
- ๐ Self-hosted server clustering
- ๐ Enterprise features
- React Team - For the powerful UI library
- Node.js Foundation - For the JavaScript runtime
- MongoDB - For the flexible NoSQL database
- Socket.io Team - For real-time communication
- Tailwind CSS - For the utility-first CSS framework
- Vite Team - For the lightning-fast build tool
- Argon2 Team - Password hashing champion
- Forge Team - JavaScript cryptography library
- CryptoJS - Client-side encryption utilities
- Speakeasy - TOTP implementation
- Helmet.js - Security headers middleware
- OWASP - For comprehensive security guidelines
- Security Community - For continuous research and improvements
- Open Source Community - For incredible tools and libraries
- GitHub Community - For hosting and collaboration tools
- All contributors who help improve SafeTalk
- Beta testers who provided valuable feedback
- Security researchers who help identify vulnerabilities
- Users who trust SafeTalk with their private communications
If you encounter issues or have questions:
- ๐ Check Documentation: Review this README and inline documentation
- ๐ Search Issues: Check if your question has been answered in GitHub Issues
- ๐ฌ GitHub Discussions: Ask questions in Discussions
- ๐ Report Bugs: Create a Bug Report
- ๐ก Request Features: Submit a Feature Request
Do NOT report security vulnerabilities publicly.
If you discover a security vulnerability:
- Email: Send details to security@safetalk.com (set up if needed)
- Include: Description, steps to reproduce, potential impact
- Wait: We'll respond within 48 hours
- Disclosure: Responsible disclosure after fix is deployed
- GitHub: @Omsiddh
- Project: SafeTalk Repository
- Issues: Report Issues
- Discussions: Community Discussions
- Documentation: Full API Docs
- Changelog: Version History
- Contributing: Contribution Guide
- License: MIT License
Your privacy is our priority. Your security is our mission.
Built with โค๏ธ by developers who care about privacy and security.
ยฉ 2025 SafeTalk. All rights reserved.
End-to-end encrypted messaging for everyone, everywhere.