Skip to content
MsParadoxPublic

Latest commit

Β 

History

4 Commits

Folders and files

Repository files navigation

CodeSync

CodeSync is a production, real-time collaborative coding platform: many people edit one file at once with conflict-free CRDT sync, run code in 7 languages, practice DSA against a hidden-test judge, and run timed technical interviews.

πŸ”— Try it now β†’ code-sync-chi-lemon.vercel.app


🧭 Contents


🎬 Demo

CodeSyncDemoVideoo.mp4

▢️ A 35-second walkthrough lives here once recorded β€” meanwhile, the real thing is one click away: open the live app.


🌟 Why CodeSync

Most "collab editor" apps break the moment two people type at once, or quietly disable code execution in the cloud. CodeSync solves both:

🧠 Conflict-free editing A server-authoritative Yjs CRDT per room β€” concurrent edits merge with zero conflicts, survive reconnects, and resync offline changes automatically.
βš™οΈ Execution that deploys anywhere A pluggable engine runs untrusted code in a hardened Docker sandbox or a remote Judge0 API β€” switchable with one env var, so the same code ships to a free PaaS or a self-hosted VM.
🎯 Built for real use Interview mode with hidden tests + timer, a LeetCode-style practice judge with streaks and a leaderboard, session replay, and role-based rooms.
πŸ’Έ Card Free Vercel + Render + MongoDB Atlas + Upstash + keyless Judge0 β€” a public, full-featured deploy that needs no credit card.
πŸ”— Live 🧩 Languages πŸ”Œ Engine πŸ—„οΈ Data ⚑ Realtime
Vercel 7 Docker Β· Judge0 Mongo Β· Redis Socket.IO + Yjs

πŸš€ Feature tour

πŸ‘₯ Collaboration

  • Real-time multi-cursor editing (Yjs CRDT)
  • Live cursors, selections & typing indicators
  • Per-room chat
  • Presence with auto-expiring heartbeats
  • Roles: owner Β· editor Β· viewer
  • Public & private (password) rooms

⚑ Code execution

  • 7 languages: JS Β· TS Β· Python Β· C++ Β· Java Β· Go Β· Rust
  • stdin support + execution history & stats
  • Per-run sandbox: no network, capped RAM/CPU/PIDs
  • Pluggable engine β€” Docker or Judge0
  • Live result broadcast to all participants

🎯 Interview & practice

  • Interview mode: problem + countdown + hidden tests
  • Candidate submissions stored & reviewable
  • Practice judge: Run (samples) / Submit (hidden tests)
  • Verdicts: AC Β· WA Β· TLE Β· MLE Β· CE Β· RE
  • Solved tracking + daily streak

🧩 Platform

  • Leaderboard (weighted: EasyΓ—1 Β· MedΓ—3 Β· HardΓ—5)
  • Session replay β€” scrub a whole editing session
  • Learn hub (DSA notes + Big-O)
  • Profiles + dashboard (activity, language stats)
  • Silent JWT refresh β€” sessions never drop mid-task

πŸ”Œ The dual execution engine

This is CodeSync's signature design. Running untrusted code is the only Docker/VM-bound part of the system β€” so it's isolated behind one env var, EXEC_ENGINE. Every caller uses the same runCode() contract and never knows which engine is live.

🐳 EXEC_ENGINE=docker (default) ☁️ EXEC_ENGINE=judge0
How it runs One throwaway, network-isolated container per run A base64 HTTPS call to a Judge0 API
Isolation Strongest β€” full OS sandbox Off-box (no Docker socket exposed)
Needs a Docker host? βœ… Yes ❌ No
Best for Local dev Β· self-hosted VM Card-free PaaS (Vercel + Render)
flowchart LR
    A["callers<br/>/api/execute Β· practice judge Β· interview judge"] --> D{"executionService.js<br/>reads EXEC_ENGINE"}
    D -->|docker| E["runCodeDocker()<br/>dockerode β†’ sandbox container"]
    D -->|judge0| J["judge0Service.js<br/>fetch β†’ ce.judge0.com"]
    E --> R["unified result<br/>stdout Β· stderr Β· status Β· time"]
    J --> R
Loading
The shared contract & language matrix
runCode({ language, code, stdin = '' }) β†’ {
  stdout, stderr, exitCode, executionTimeMs,
  status   // success | error | timeout | oom | compile_error | runtime_error
}
Language Docker image Judge0 ID
JavaScript node:20-alpine 63
TypeScript codesync-ts (built) 74
Python python:3.12-alpine 71
C++ gcc:13 54
Java eclipse-temurin:21-jdk 62
Go golang:1.22-alpine 60
Rust rust:1.78-slim 73

🧱 Architecture

flowchart TB
    subgraph C["πŸ–₯️ Client Β· React + Vite"]
        MON["Monaco Editor"] <--> YJS["Yjs CRDT"]
        RDX["Redux Toolkit"]
    end

    subgraph S["βš™οΈ Server Β· Express + Socket.IO"]
        REST["REST API<br/>auth Β· rooms Β· execute Β· problems Β· users"]
        WS["Socket handlers<br/>room Β· yjs Β· cursor"]
        DOC["In-process Y.Doc<br/>server authority"]
        WS --> DOC
    end

    subgraph X["πŸ’Ύ State & Execution"]
        M[("MongoDB Atlas")]
        RE[("Upstash Redis")]
        ENG{{"EXEC_ENGINE"}}
        DK["🐳 Docker sandbox"]
        J0["☁️ Judge0 API"]
        ENG -->|docker| DK
        ENG -->|judge0| J0
    end

    YJS -.->|"WSS Β· binary updates"| WS
    RDX -.->|"HTTPS Β· JWT"| REST
    REST --> ENG
    S --> M
    S --> RE
Loading

MongoDB collections: User Β· Room Β· Problem Β· Snapshot Β· Execution Β· SessionEvent (30-day TTL) Β· Submission (90-day TTL). Redis: presence sets, heartbeats (90 s TTL), cursors, and the Socket.IO pub/sub adapter for horizontal scaling.

πŸ“– Deep dive: docs/ARCHITECTURE.md


πŸ”„ How real-time sync works

sequenceDiagram
    participant A as User A
    participant S as Server (Y.Doc)
    participant B as User B
    A->>A: type β†’ Yjs binary update
    A->>S: emit yjs-update (base64)
    Note over S: assertCanEdit Β· throttle 50/s<br/>Y.applyUpdate(serverDoc)
    S-->>B: broadcast yjs-update
    B->>B: Y.applyUpdate β†’ Monaco patches, no flicker
    Note over A,B: a new joiner gets the full encoded state β€” zero round-trips
Loading

πŸ›‘οΈ Security model

The Docker engine hardens every run in five layers:

Layer Control
🌐 Network NetworkMode: none β€” no outbound connections
πŸ“Š Resources 256 MB RAM (swap off) Β· 50% CPU Β· PidsLimit: 64 (fork-bomb safe)
πŸ“ Filesystem source via in-memory putArchive Β· writable only on tmpfs /tmp (noexec) + /build (exec) Β· container removed after run
πŸ”’ Privilege non-root uid 1000 Β· no-new-privileges
⏱️ Application 10 s wall-clock TLE · stdout 1 MB / stderr 256 KB caps · 100 KB code limit

Plus, platform-wide: JWT access (15 m) + refresh (7 d), bcrypt hashing, Helmet, strict CORS, and rate limits on API / auth / execution / room creation.

Tip

The Judge0 engine sidesteps the one known Docker trade-off (the mounted docker.sock) entirely by running code off-box β€” which is exactly what makes the card-free cloud deploy safe and simple.


🧰 Tech stack

Frontend β€” React 18 Β· Vite 5 Β· Redux Toolkit Β· React Router 6 Β· Monaco Editor Β· Yjs + y-monaco Β· Socket.IO-client Β· TailwindCSS Β· Axios

Backend β€” Node 20 (ESM) Β· Express 4 Β· Socket.IO 4 + Redis adapter Β· Mongoose 8 Β· ioredis Β· dockerode Β· jsonwebtoken Β· bcryptjs Β· zod Β· winston

Data & infra β€” MongoDB Atlas Β· Upstash Redis Β· Docker Β· Judge0 Β· Vercel Β· Render Β· nginx (VM route) Β· Let's Encrypt

Testing β€” Jest Β· Supertest Β· mongodb-memory-server


⚑ Quick start

Prerequisites: Node 20+, and Docker (only needed for the local Docker execution engine). Mongo + Redis can be local or free cloud (Atlas + Upstash).

Option A β€” Docker Compose (everything at once)

git clone https://github.com/MsParadox/CodeSync.git
cd CodeSync
docker compose up -d
# Frontend (via nginx) β†’ http://localhost      Backend β†’ http://localhost:4000

Option B β€” manual (two terminals)

# Terminal 1 β€” backend
cd server && cp .env.example .env      # fill MONGODB_URI, REDIS_URL, secrets
npm install && npm run dev             # β†’ http://localhost:4000

# Terminal 2 β€” frontend
cd client && cp .env.example .env      # see the env note below
npm install && npm run dev             # β†’ http://localhost:5173

Two gotchas that only bite in production β€” already handled, don't undo them:

  • VITE_API_URL must end in /api (routes are mounted under /api); VITE_SOCKET_URL must not (Socket.IO connects to the origin).
  • SPA deep links rely on client/vercel.json (rewrite all β†’ index.html), so refreshing /problems doesn't 404 on Vercel.

πŸ”‘ Environment variables

server/.env
NODE_ENV=development
PORT=4000                       # Render injects this in prod β€” don't hardcode there
MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/codesync
REDIS_URL=rediss://default:pass@host.upstash.io:6380   # rediss:// (TLS)
JWT_SECRET=<openssl rand -hex 32>
REFRESH_TOKEN_SECRET=<openssl rand -hex 32>
JWT_EXPIRES_IN=15m
REFRESH_TOKEN_EXPIRES_IN=7d
CLIENT_URL=http://localhost:5173            # the browser origin (CORS)

# Execution engine
EXEC_ENGINE=docker                          # docker | judge0
JUDGE0_API_URL=https://ce.judge0.com        # used when EXEC_ENGINE=judge0
EXECUTION_TIMEOUT_MS=10000
EXEC_MEMORY_MB=256
client/.env
VITE_API_URL=http://localhost:4000/api      # MUST end in /api
VITE_SOCKET_URL=http://localhost:4000       # origin, NO /api

🌐 Deployment

CodeSync ships two first-class routes from the same codebase:

Route Engine Hosts Card? Guide
☁️ Card-free PaaS judge0 Vercel + Render + Atlas + Upstash + Judge0 ❌ none DEPLOY_JUDGE0.md
🐳 Self-hosted VM docker Droplet + docker-compose + nginx + Let's Encrypt πŸ’³ Student Pack PRODUCTION_DEPLOYMENT.md

The live demo runs the card-free PaaS route β†’ code-sync-chi-lemon.vercel.app


πŸ§ͺ Testing

cd server && npm test     # Jest + Supertest, in-memory MongoDB (no external DB)

Suites cover auth (register/login/refresh), rooms (CRUD/join/archive), sockets (join/leave/chat/cursor/yjs), and execution across all 7 languages.


πŸ“‘ API reference

Auth Β· /api/auth
Method Endpoint Description
POST /register Create account β†’ access + refresh tokens
POST /login Email/password β†’ tokens
GET /me Current user
POST /refresh Exchange refresh token
POST /logout Stateless logout
Rooms Β· /api/rooms
Method Endpoint Description
GET / Β· /my/rooms List public / owned rooms
POST / Create room
GETΒ·PUTΒ·DELETE /:roomId Read / update / archive
GETΒ·POSTΒ·DELETE /:roomId/members… Manage roster & roles
GET /:roomId/snapshots Β· /replay History & session replay
GETΒ·PUT /:roomId/testcases Hidden tests (owner only)
POST /:roomId/submit Run against hidden tests
GET /:roomId/submissions Interview submissions
Execute & Problems Β· /api/execute Β· /api/problems
Method Endpoint Description
POST /api/execute Run code in the active engine
GET /api/execute/history Β· /stats Run history & aggregates
GET /api/problems Β· /:slug List / read problems
POST /api/problems/:slug/run Β· /submit Samples / hidden-test judge
GET /api/problems/meta/leaderboard Weighted leaderboard

πŸ”Œ Socket events

Client β†’ Server

join-room Β· leave-room Β· yjs-update Β· yjs-awareness Β· request-sync Β· cursor-update Β· selection-update Β· typing-start / typing-stop Β· chat-message Β· language-change Β· set-interview-mode Β· interview-submit Β· heartbeat

Server β†’ Client

room-joined Β· user-joined / user-left Β· participant-list Β· yjs-update Β· yjs-sync Β· yjs-awareness Β· cursor-update Β· selection-update Β· user-typing / user-stopped-typing Β· chat-message Β· language-changed Β· interview-mode-changed Β· interview-submitted Β· execution-started / execution-result Β· your-role-changed


πŸ“ Project structure

CodeSync/
β”œβ”€β”€ client/                       # React + Vite SPA
β”‚   └── src/
β”‚       β”œβ”€β”€ components/{Editor,Room}/   # Monaco, panels, modals
β”‚       β”œβ”€β”€ hooks/                # useYjs Β· useSocket
β”‚       β”œβ”€β”€ pages/                # Home Β· Room Β· Problems Β· Leaderboard Β· Learn Β· …
β”‚       β”œβ”€β”€ store/                # Redux slices (auth Β· room Β· problems)
β”‚       β”œβ”€β”€ services/api.js       # Axios + JWT refresh
β”‚       └── data/learn.js         # Learn hub content
β”‚
β”œβ”€β”€ server/                       # Node + Express + Socket.IO
β”‚   └── src/
β”‚       β”œβ”€β”€ routes/               # auth Β· rooms Β· execute Β· users Β· problems
β”‚       β”œβ”€β”€ socket/               # room Β· yjs Β· cursor handlers + auth
β”‚       β”œβ”€β”€ services/             # executionService Β· judge0Service Β· snapshotService
β”‚       β”œβ”€β”€ models/               # User Β· Room Β· Problem Β· Snapshot Β· Submission Β· …
β”‚       β”œβ”€β”€ seed/problems.js      # idempotent practice-problem seed
β”‚       └── utils/judge.js        # engine-agnostic judge
β”‚
β”œβ”€β”€ docs/                         # ARCHITECTURE Β· DEPLOY_JUDGE0 Β· PRODUCTION_DEPLOYMENT
β”œβ”€β”€ docker-compose.yml            # local stack
└── docker-compose.prod.yml       # VM stack (nginx + TLS)

πŸ‘€ Author

Mohit Sharma β€” Full-Stack Developer Β· Competitive Programmer

Live GitHub LinkedIn Email

If CodeSync helped or impressed you, consider leaving a ⭐ β€” it genuinely helps.

footer

Releases

Packages

Contributors

Languages