Skip to content

ErfanZmp/Nitrochat

Repository files navigation

Nitrochat

A lightweight, secure, end-to-end encrypted chatroom application designed for deployment on local servers. Built with emphasis on privacy, security, and ease of deployment.

🌟 Features

Core Functionality

  • Real-time Messaging: WebSocket-based instant messaging with sub-second latency
  • Multiple Chatrooms: Create and join unlimited rooms with unique IDs
  • Message Replies: Thread conversations with reply functionality
  • Online Status: Real-time user presence tracking
  • Message History: Load older messages on demand with infinite scroll
  • Responsive Design: Optimized for desktop, tablet, and mobile devices

Security & Privacy

  • End-to-End Encryption: AES-GCM 256-bit encryption on client-side
  • Zero Knowledge: Server never sees unencrypted messages
  • Challenge-Response Authentication: No plaintext password transmission
  • Session Management: Secure token-based sessions (24-hour expiry)
  • HTTPS Support: SSL/TLS for local network deployment
  • Key Derivation: PBKDF2 with 100,000 iterations

Optional Features

  • Ollama Integration: Connect local LLM models for AI-powered responses
  • Auto-Reconnection: Graceful handling of network interruptions
  • RTL Support: Bidirectional text support (LTR/RTL)

🏗️ Architecture

┌─────────────┐         ┌─────────────┐         ┌──────────────┐
│   Browser   │◄───────►│   FastAPI   │◄───────►│              │
│  (Client)   │  WSS/   │   Server    │   SQL   │ SQL Database │
│   + Crypto  │  HTTPS  │   + Auth    │         │              │
└─────────────┘         └─────────────┘         └──────────────┘

Technology Stack:

  • Frontend: Vanilla JavaScript, Web Crypto API, DOMPurify
  • Backend: FastAPI, Python 3.10+
  • Database: PostgreSQL with asyncpg
  • Real-time: WebSockets
  • Security: HTTPS (mkcert for local), challenge-response auth

📋 Prerequisites

  • Python 3.10 or higher
  • PostgreSQL 12 or higher
  • Node.js (optional, for mkcert)
  • Modern web browser with Web Crypto API support

⚡ Quick Start

Get up and running in 5 minutes:

# 1. Clone and enter directory
git clone https://github.com/ErfanZmp/chatroom.git
cd chatroom

# 2. Install dependencies
pip install -r requirements.txt

# 3. Create database
createdb chatdb

# 4. Configure environment
echo 'DATABASE_URL=postgresql://postgres:yourpassword@localhost/chatdb' > .env

# 5. Run migrations
python migrate.py migrate

# 6. Start server
uvicorn app:app --reload --host 0.0.0.0 --port 8000

Access at: http://localhost:8000

Using Make (optional):

make setup  # Install deps + run migrations
make dev    # Start development server

🚀 Detailed Installation

1. Clone Repository

git clone https://github.com/ErfanZmp/chatroom.git
cd chatroom

2. Set Up Python Environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Configure Database

Create a PostgreSQL database and configure the connection:

createdb chatdb

Create .env file:

DATABASE_URL=postgresql://postgres:yourpassword@localhost/chatdb

4. Initialize Database

Run database migrations to create tables:

python migrate.py migrate

This will create:

  • chatroom table - stores room metadata and hashed keys
  • chat_message table - stores encrypted messages
  • Required indexes for performance
  • schema_migrations table - tracks applied migrations

Alternative: Manual SQL

If you prefer manual setup, run the SQL in migrations/001_initial_schema.sql:

psql -d chatdb -f migrations/001_initial_schema.sql

5. Set Up HTTPS (Optional, for Local Network)

Install mkcert:

# macOS
brew install mkcert

# Linux
sudo apt install mkcert  # or equivalent

# Windows
choco install mkcert

The start-ssl.sh script will automatically generate certificates for your local IP.

🎯 Usage

Development Mode (HTTP)

uvicorn app:app --reload --host 0.0.0.0 --port 8000

Access at: http://localhost:8000

Production Mode (HTTPS)

chmod +x start-ssl.sh
./start-ssl.sh

Access at: https://your-local-ip:8000

Creating a Chatroom

  1. Open the application in your browser
  2. Enter a Display Name (your username)
  3. Enter a Room ID (unique identifier)
  4. Enter a Room Key (passphrase for encryption)
  5. Click Join

Note: The first user to join creates the room. Others must use the exact same Room ID and Room Key to enter.

Using Ollama Integration (Optional)

  1. Install Ollama locally
  2. Pull a model: ollama pull llama2
  3. Start Ollama: ollama serve
  4. Access chatroom via: https://your-ip:8000/ai
  5. Enter Ollama port (default: 11434)
  6. Send messages in format: <model> <prompt>

Example: llama2 What is the meaning of life?

🔒 Security Considerations

What's Encrypted

✅ All message content
✅ Message history
✅ User-generated content

What's NOT Encrypted

❌ Usernames (needed for display)
❌ Timestamps (needed for ordering)
❌ Room IDs (needed for routing)
❌ Online status (needed for presence)

Best Practices

  • Use strong, unique room keys (20+ characters recommended)
  • Don't share room keys over insecure channels
  • Use HTTPS in production environments
  • Regularly update dependencies
  • Deploy behind a firewall for internal use only

Known Limitations

  • Metadata (usernames, message count, timestamps) is visible to server
  • No perfect forward secrecy (PFS)
  • Stored credentials in localStorage (can be migrated to sessionStorage)

📁 Project Structure

chatroom/
├── app.py                 # FastAPI backend
├── requirements.txt       # Python dependencies
├── .env                   # Environment variables (create this)
├── start-ssl.sh          # HTTPS setup script
├── static/
│   ├── index.html        # Frontend UI
│   ├── script/
│   │   ├── chat.js       # Client-side logic
│   │   ├── contextMenu.js
│   │   ├── purify.min.js # XSS sanitization
│   └── style/
│       └── style.css     # Styling
└── README.md

🔧 Configuration

Environment Variables

# Database
DATABASE_URL=postgresql://user:pass@host:port/dbname

# Optional: Session Configuration
SESSION_EXPIRY=86400      # 24 hours in seconds
CHALLENGE_EXPIRY=300      # 5 minutes in seconds

# Optional: Auto-delete messages at midnight
MIDNIGHT_CLEANUP=false  # Set to 'true' to enable

Message Auto-Deletion: When MIDNIGHT_CLEANUP=true, all messages in the chat_message table are automatically deleted daily at 00:00 server time. Useful for temporary/ephemeral chat scenarios.

Client Configuration

Edit constants in static/script/chat.js:

const maxReconnectAttempts = 5;
const baseReconnectDelay = 1000;    // milliseconds
const maxReconnectDelay = 30000;    // milliseconds
const SESSION_EXPIRY = 86400;        // seconds

🗄️ Database Management

Migration Commands

# Apply all pending migrations
python migrate.py migrate

# Check migration status
python migrate.py status

# Rollback last migration
python migrate.py rollback

Schema Overview

Tables:

  • chatroom - Room metadata (chat_id, key_hash, created_at)
  • chat_message - Encrypted messages (id, chat_id, username, message, sent_at, reply_to)
  • schema_migrations - Tracks applied migrations

Indexes:

  • Fast message retrieval by room and timestamp
  • Optimized reply thread lookups
  • Room creation time queries

See migrations/README.md for detailed schema documentation.

🌐 Deployment

Local Network Deployment

  1. Configure firewall to allow port 8000
  2. Run with start-ssl.sh to enable HTTPS
  3. Share the local IP and room credentials with users
  4. Ensure PostgreSQL is accessible

Docker Deployment (Optional)

Create Dockerfile:

FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Run:

docker build -t nitrochat .
docker run -p 8000:8000 --env-file .env nitrochat

🤝 Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow PEP 8 for Python code
  • Use meaningful variable names
  • Add comments for complex logic
  • Test security features thoroughly

🐛 Troubleshooting

WebSocket Connection Fails

  • Check firewall settings
  • Verify HTTPS certificates are trusted
  • Ensure server is bound to correct IP (0.0.0.0)

Database Connection Error

  • Verify PostgreSQL is running: pg_isready
  • Check DATABASE_URL in .env
  • Ensure database and tables exist
  • Start PostgreSQL if needed:
    • macOS: brew services start postgresql
    • Linux: sudo service postgresql start

Permission Denied (Database)

# Ensure user has database creation privileges
psql -U postgres -c "ALTER USER yourusername CREATEDB;"

Migration Issues

  • Already applied error: Database is already initialized
  • Reset database:
    python migrate.py rollback  # or
    dropdb chatdb && createdb chatdb && python migrate.py migrate
  • Check status: python migrate.py status

Encryption/Decryption Errors

  • Verify all users use identical Room Key
  • Check browser console for Web Crypto API errors
  • Ensure HTTPS is enabled (required for crypto APIs)

Session Expiry Issues

  • Sessions expire after 24 hours
  • Clear localStorage and re-login
  • Check system time synchronization

📄 License

This project is open source and available under the MIT License.

🙏 Acknowledgments

  • FastAPI for the excellent web framework
  • PostgreSQL for reliable data storage
  • Web Crypto API for browser-native encryption
  • Ollama for local LLM integration

📞 Support

For issues, questions, or contributions:


⚠️ Disclaimer: This software is provided "as is" without warranty. Use in production environments at your own risk. Always perform security audits before deploying in sensitive contexts.

About

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors