Skip to content

A production-ready, security-focused real-time chat application built with the MERN stack, implementing industry-standard security practices and modern web technologies.

License

Notifications You must be signed in to change notification settings

yashpatil118/SecureChat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

39 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Secure Real-Time Chat Application

A production-ready, security-focused real-time chat application built with the MERN stack, implementing industry-standard security practices and modern web technologies.

πŸ” Security Features

Authentication & Authorization

  • JWT (JSON Web Tokens) for stateless authentication
    • Secure token generation and validation
    • HTTP-only cookies to prevent XSS attacks
    • Token expiration and refresh mechanisms
    • Protected API endpoints with middleware authentication

Data Protection

  • Password Security

    • Bcrypt hashing algorithm for password encryption
    • Salting with configurable rounds for enhanced security
    • No plain-text password storage
  • Message Encryption

    • Messages encrypted using bcrypt before storage
    • Secure transmission over encrypted channels
    • Protection against data breach exposure

Input Validation & Sanitization

  • Client-Side Validation

    • Real-time input validation on login and signup forms
    • Format verification (email, password strength)
    • Prevention of malformed data submission
  • Server-Side Validation

    • Comprehensive input sanitization
    • SQL injection prevention
    • XSS (Cross-Site Scripting) attack mitigation
    • Data type and format verification

Access Control

  • Private Routing

    • Protected routes requiring authentication
    • Automatic redirection for unauthorized access
    • Route guards preventing URL manipulation
  • Role-Based Access Control

    • User session management
    • Authorization checks on sensitive operations
    • Secure API endpoint protection

Network Security

  • Socket.io Security

    • Secure WebSocket connections
    • Origin validation
    • Connection authentication
    • Protection against socket hijacking
  • CORS Configuration

    • Restricted cross-origin requests
    • Whitelisted domains only
    • Secure headers implementation

πŸ› οΈ Tech Stack

Core Technologies

  • Frontend: React.js with Hooks
  • Backend: Node.js + Express.js
  • Database: MongoDB with Mongoose ODM
  • Real-time: Socket.io
  • Styling: TailwindCSS + DaisyUI

Security Libraries

  • bcryptjs: Password hashing and encryption
  • jsonwebtoken: JWT authentication
  • cookie-parser: Secure cookie handling
  • express-validator: Input validation middleware

State Management

  • Zustand: Lightweight global state management
  • React Context: Real-time user status management

βš™οΈ Environment Configuration

Create a .env file in the root directory with the following variables:

# Server Configuration
PORT=5000
NODE_ENV=production

# Database
MONGO_DB_URI=<your mongodbcluster uri>

# Security
JWT_SECRET=your_super_secure_random_string_min_32_chars

Security Notes for Environment Variables:

  • JWT_SECRET: Use a cryptographically strong random string (minimum 32 characters)
  • MONGO_DB_URI: Never commit to version control; use environment-specific values
  • NODE_ENV: Set to 'production' for deployment to enable security optimizations

πŸ“¦ Installation & Setup

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB Atlas account or local MongoDB installation
  • npm or yarn package manager

Installation Steps

  1. Clone the repository

    git clone https://github.com/yashpatil118/SecureChat.git
    cd SecureChat
  2. Install dependencies

    npm install
  3. Configure environment variables

    cp .env.example .env
    # Edit .env with your secure credentials
  4. Build the application

    npm run build
  5. Start the application

    # Production mode
    npm start
    
    # Development mode
    npm run dev

πŸš€ Features

Core Functionality

  • Real-time Messaging: Instant message delivery using Socket.io
  • User Authentication: Secure signup and login system
  • Online Status: Real-time user presence indicators
  • Message History: Persistent chat storage with MongoDB
  • User Profiles: Customizable user information
  • Private Conversations: One-on-one messaging

Security Implementations

  • Session Management: Secure user sessions with automatic timeout
  • HTTPS Ready: Configured for SSL/TLS encryption
  • Rate Limiting: Protection against brute-force attacks
  • Error Handling: Secure error messages without information leakage
  • Audit Logging: Track authentication events and suspicious activities

πŸ—οΈ Project Structure

message-app/
β”‚
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ auth.controller.js        # Authentication logic (signup, login, logout)
β”‚   β”‚   β”œβ”€β”€ message.controller.js     # Message handling with encryption
β”‚   β”‚   └── user.controller.js        # User management & retrieval
β”‚   β”‚
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   └── connectToMongoDB.js       # Secure MongoDB connection
β”‚   β”‚
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── protectRoute.js           # JWT validation & route protection
β”‚   β”‚
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ conversation.model.js     # Conversation schema
β”‚   β”‚   β”œβ”€β”€ message.model.js          # Message schema with encryption
β”‚   β”‚   └── user.model.js             # User schema with password hashing
β”‚   β”‚
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ auth.routes.js            # Authentication endpoints
β”‚   β”‚   β”œβ”€β”€ message.routes.js         # Protected message routes
β”‚   β”‚   └── user.routes.js            # Protected user routes
β”‚   β”‚
β”‚   β”œβ”€β”€ socket/
β”‚   β”‚   └── socket.js                 # Secure Socket.io configuration
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   └── generateToken.js          # JWT token generation utility
β”‚   β”‚
β”‚   └── server.js                     # Express server setup
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ public/
β”‚   β”‚   β”œβ”€β”€ bg.png                    # Background image
β”‚   β”‚   └── vite.svg                  # Vite logo
β”‚   β”‚
β”‚   └── src/
β”‚       β”œβ”€β”€ assets/
β”‚       β”‚   └── sounds/
β”‚       β”‚       └── notification.mp3   # Message notification sound
β”‚       β”‚
β”‚       β”œβ”€β”€ components/
β”‚       β”‚   β”œβ”€β”€ messages/
β”‚       β”‚   β”‚   β”œβ”€β”€ Message.jsx        # Individual message component
β”‚       β”‚   β”‚   β”œβ”€β”€ MessageContainer.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ MessageInput.jsx   # Input with validation
β”‚       β”‚   β”‚   └── Messages.jsx       # Message list display
β”‚       β”‚   β”‚
β”‚       β”‚   β”œβ”€β”€ sidebar/
β”‚       β”‚   β”‚   β”œβ”€β”€ Conversation.jsx   # Conversation item
β”‚       β”‚   β”‚   β”œβ”€β”€ Conversations.jsx  # Conversations list
β”‚       β”‚   β”‚   β”œβ”€β”€ LogoutButton.jsx   # Secure logout
β”‚       β”‚   β”‚   β”œβ”€β”€ SearchInput.jsx    # Search with validation
β”‚       β”‚   β”‚   └── Sidebar.jsx        # Main sidebar
β”‚       β”‚   β”‚
β”‚       β”‚   └── skeletons/
β”‚       β”‚       └── MessageSkeleton.jsx # Loading state
β”‚       β”‚
β”‚       β”œβ”€β”€ context/
β”‚       β”‚   β”œβ”€β”€ AuthContext.jsx        # Authentication state management
β”‚       β”‚   └── SocketContext.jsx      # Socket.io connection context
β”‚       β”‚
β”‚       β”œβ”€β”€ hooks/
β”‚       β”‚   β”œβ”€β”€ useGetConversations.js # Fetch conversations
β”‚       β”‚   β”œβ”€β”€ useGetMessage.js       # Fetch messages
β”‚       β”‚   β”œβ”€β”€ useListenMessages.js   # Real-time message listener
β”‚       β”‚   β”œβ”€β”€ useLogin.js            # Login with validation
β”‚       β”‚   β”œβ”€β”€ useLogout.js           # Secure logout
β”‚       β”‚   β”œβ”€β”€ useSendMessage.js      # Send message with validation
β”‚       β”‚   └── useSignup.js           # Signup with validation
β”‚       β”‚
β”‚       β”œβ”€β”€ pages/
β”‚       β”‚   β”œβ”€β”€ home/
β”‚       β”‚   β”‚   └── Home.jsx           # Protected home page
β”‚       β”‚   β”œβ”€β”€ login/
β”‚       β”‚   β”‚   └── Login.jsx          # Login page with validation
β”‚       β”‚   └── signup/
β”‚       β”‚       β”œβ”€β”€ GenderCheckbox.jsx # Gender selection
β”‚       β”‚       └── SignUp.jsx         # Signup with validation
β”‚       β”‚
β”‚       β”œβ”€β”€ utils/
β”‚       β”‚   β”œβ”€β”€ emojis.js              # Emoji utilities
β”‚       β”‚   └── extractTime.js         # Time formatting
β”‚       β”‚
β”‚       β”œβ”€β”€ zustand/
β”‚       β”‚   └── useConversation.js     # Global state management
β”‚       β”‚
β”‚       β”œβ”€β”€ App.jsx                    # Main app with routing
β”‚       β”œβ”€β”€ main.jsx                   # App entry point
β”‚       └── index.css                  # Global styles
β”‚
β”œβ”€β”€ .env                               # Environment variables (ignored)
β”œβ”€β”€ .gitignore                         # Git ignore file
└── package.json                       # Project dependencies

πŸ”’ Security-Critical Files

Backend Security Layer

  • protectRoute.js: JWT middleware for authentication
  • generateToken.js: Secure token generation with expiry
  • user.model.js: Password hashing with bcrypt pre-save hooks
  • auth.controller.js: Input validation & authentication logic

Frontend Security Layer

  • AuthContext.jsx: Protected authentication state
  • useLogin.js / useSignup.js: Client-side validation hooks
  • All pages/: Private routing implementation

πŸ”’ Security Best Practices Implemented

  1. Password Policy

    • Minimum 6 characters length
    • Complexity requirements enforced
    • Bcrypt encryption
  2. JWT Security

    • Short-lived access tokens
    • HTTP-only cookie storage
    • Secure flag in production
    • Token validation on every request
  3. Input Validation

    • Whitelist approach for allowed characters
    • Length restrictions on all inputs
    • Email format validation
    • Prevention of NoSQL injection
  4. Error Handling

    • Generic error messages to users
    • Detailed logs for administrators
    • No stack traces in production
    • Proper status codes
  5. Database Security

    • Connection string encryption
    • Prepared statements (Mongoose queries)
    • Limited user permissions
    • Regular backup procedures

πŸ› Error Handling

Client-Side

  • Form validation with user-friendly messages
  • Network error handling with retry mechanisms
  • Graceful degradation for failed features
  • Toast notifications for user feedback

Server-Side

  • Comprehensive try-catch blocks
  • Async error handling middleware
  • Database connection error management
  • Socket.io error listeners

🌐 Deployment

Production Checklist

  • Set NODE_ENV=production
  • Use strong JWT_SECRET
  • Enable HTTPS/SSL
  • Configure CORS properly
  • Set secure cookie flags
  • Enable rate limiting
  • Configure MongoDB security
  • Set up monitoring and alerts
  • Regular security audits
  • Dependency vulnerability scanning

Recommended Platforms

  • Backend: Heroku, DigitalOcean, AWS EC2
  • Database: MongoDB Atlas (with IP whitelist)
  • Frontend: Vercel, Netlify

🀝 Contributing

When contributing, please ensure:

  • All security tests pass
  • No sensitive data in commits
  • Follow secure coding guidelines
  • Update security documentation

πŸ“„ License

MIT License - See LICENSE file for details

πŸ”— Resources


Note: This application implements security best practices, but no system is 100% secure. Regular security audits, dependency updates, and monitoring are essential for maintaining a secure application.

About

A production-ready, security-focused real-time chat application built with the MERN stack, implementing industry-standard security practices and modern web technologies.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •