Skip to content

Repository files navigation

Starlette WebSocket Chat Server

CI License: MIT

Async, room-based WebSocket chat server built with Python and Starlette featuring real-time message broadcasting, WebRTC Video & Voice Signaling Gateway (webrtc_offer, webrtc_answer, webrtc_ice, webrtc_hangup), Read Receipts & Delivery Status Badges ( / ✓✓), Full-Text Message Search REST APIs (GET /search, GET /search/dm), Media File Attachments (POST /upload, GET /uploads/{id}), End-to-End Encryption (E2EE) zero-knowledge payload relay, an Admin Web Dashboard (/admin), room moderation REST APIs (kick/ban/purge), 1-on-1 private direct messaging (DM), online user presence tracking, user profile avatars, Prometheus metrics instrumentation (/metrics), sliding-window rate limiting, typing indicators, emoji reactions, room isolation, Redis Pub/Sub horizontal scaling, JWT token authentication (RBAC), asynchronous SQLite chat message persistence, Docker containerization, automated CI testing, and a built-in interactive browser client.

Stack

  • Language: Python 3.9+ (Tested on Python 3.9, 3.10, 3.11, 3.12)
  • Framework: Starlette
  • ASGI Server: Uvicorn
  • WebRTC Signaling Gateway: Real-time SDP offer/answer exchange & ICE candidate relay
  • Read Receipts Protocol: Two-phase ACK protocol (read_receipt -> receipt_update)
  • Search Engine: SQLite Full-Text Search (FTS & LIKE indexing)
  • Media Attachments: python-multipart multipart REST uploader & FileResponse server
  • Cryptography & E2EE: AES-256-GCM authenticated encryption & PBKDF2HMAC key derivation (cryptography)
  • Administration & Moderation: RBAC role verification, Kick/Ban socket controls, Room message purging
  • Direct Messaging: Target user socket routing (user_connections) & SQLite persistence (direct_messages)
  • Metrics & Observability: Prometheus Client (prometheus-client)
  • Rate Limiting: Sliding-window algorithm
  • Pub/Sub Scaling: Broadcaster, Redis
  • Authentication: PyJWT (HS256)
  • Database: SQLite (aiosqlite async driver)
  • Protocol: WebSockets (websockets library) — Protocol v2
  • Deployment: Docker, Docker Compose
  • Testing & CI: pytest, pytest-asyncio, Starlette TestClient (httpx), GitHub Actions

Setup

  1. Clone the repository:

    git clone https://github.com/breakingthebot/websocket-chat-server-build65.git
    cd websocket-chat-server-build65
  2. Create and activate a virtual environment:

    python -m venv venv
    # On Windows PowerShell / CMD:
    .\venv\Scripts\activate
    # On Linux/macOS:
    source venv/bin/activate
  3. Install dependencies:

    pip install -e .[dev]

Environment Variables

Refer to .env.example:

  • HOST: Server bind address (default: 127.0.0.1)
  • PORT: Server bind port (default: 8000)
  • ADMIN_KEY: Password for accessing the Admin Control Panel (default: adminpass)
  • RATE_LIMIT_MAX: Max allowed messages per sliding window (default: 5)
  • REDIS_URL: Redis connection URL for Pub/Sub backplane (default: memory://)
  • JWT_SECRET: Secret key for signing and verifying JWT tokens
  • CHAT_DB_PATH: SQLite database file path (default: chat_history.db)
  • UPLOAD_DIR: Local storage directory for media attachments (default: uploads)
  • LOG_LEVEL: Logging verbosity (INFO, DEBUG)
  • DEBUG: Application debug mode (True, False)

Running Locally

Before running commands, activate the virtual environment:

# Windows PowerShell / CMD:
.\venv\Scripts\activate

# Linux / macOS:
source venv/bin/activate

Once activated, run the chat server using the CLI entrypoint:

starlette-chat --host 127.0.0.1 --port 8000 --db-path chat_history.db --rate-limit 5 --reload

Check the installed version:

starlette-chat --version

Open your browser to http://127.0.0.1:8000 to access the interactive web chat client!

WebRTC Video & Voice Signaling Gateway

The server acts as a WebRTC signaling gateway for establishing low-latency 1-on-1 peer-to-peer video and voice calls.

  • Signaling Protocol:
    • webrtc_offer: SDP session description offer sent to target peer socket.
    • webrtc_answer: SDP session description answer sent back to caller socket.
    • webrtc_ice: Asynchronous ICE candidate exchange over WebSocket.
    • webrtc_hangup: Peer call termination notification.
  • Embedded Web Client UI: Select Private DM, enter a target username, and click 🎥 Call. Accept incoming call prompts to establish live local and remote WebRTC video streams!

Read Receipts & Message Delivery Status ( / ✓✓)

Real-time delivery status and read receipts tracking across rooms and 1-on-1 private DMs.

  • Status Badges: (sent), ✓✓ (delivered), ✓✓ (read).

Search & Full-Text Query REST API

  • Public Room Message Search: GET /search?q=keyword&room=general&sender=Alice&limit=50.
  • Private DM Search: GET /search/dm?q=secret&limit=50.

Media File Attachments & File Upload API

  • Multipart Upload Endpoint: POST /upload accepting multipart/form-data.
  • Media File Server Endpoint: GET /uploads/{file_id}.

End-to-End Encryption (E2EE Signal Mode)

The server supports zero-knowledge client-side End-to-End Encryption (E2EE) using AES-256-GCM symmetric encryption.

Admin Web Dashboard & Moderation API (/admin)

Access the interactive Dark Mode Admin Control Panel at http://127.0.0.1:8000/admin.

Continuous Integration (CI)

GitHub Actions automatically executes the complete test matrix on every push and pull_request to the main branch.

To run the test suite locally:

pytest -v

Architecture Notes

This project implements an asynchronous WebSocket server using Starlette's native ASGI router, WebRTC video/voice signaling gateway, two-phase read receipt ACK protocol, Full-Text Message Search REST APIs, media file attachment uploading and serving, E2EE zero-knowledge relaying, RBAC admin moderation APIs, 1-on-1 direct message routing, Prometheus metrics collection, sliding-window rate limiting, Redis Pub/Sub horizontal scaling, JWT authorization, a custom connection manager, and an asynchronous SQLite persistence engine.

Data Handling & Privacy

  • Data Posture: Chat room messages, reactions, DMs, read receipts, and uploaded files are stored locally in isolated SQLite and file directories (chat_history.db, uploads/).
  • Data Collection: Username identity is verified via JWT tokens. No passwords or credentials are saved.
  • Sharing: Zero third-party telemetry, tracking, or data sharing.

About

Async Starlette WebSocket chat server featuring room isolation, real-time message broadcasting, connection management, and REST inspection endpoints.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages