A production-ready backend application for tracking LeetCode daily challenges with automated evaluation, streak tracking, and penalty management.
- User Authentication: JWT-based authentication with secure password hashing
- Challenge Management: Create and join challenges with customizable rules
- LeetCode Integration: Fetch submissions from LeetCode GraphQL API
- Automated Evaluation: Daily cron jobs to evaluate challenge progress
- Streak Tracking: Track current and longest streaks
- Penalty System: Virtual penalty tracking for missed days
- Dashboard: Comprehensive progress overview and leaderboards
- Clean Architecture: Service-based structure with separation of concerns
- 🔒 Security Features: Centralized input sanitization and validation (see SECURITY.md)
This application implements comprehensive security measures to protect against common web vulnerabilities:
✅ Cross-Site Scripting (XSS) - Script tag removal and protocol validation
✅ HTML/Script Injection - Event handler stripping and tag sanitization
✅ Path Traversal - Directory traversal detection and blocking
✅ Malicious Protocol Injection - JavaScript/data protocol blocking
✅ Control Character Injection - Null byte and control character removal
✅ DoS via Large Inputs - Request size limits and length enforcement
✅ SQL Injection Detection - Pattern detection and logging
-
Centralized Sanitization Utility (src/utils/sanitizer.js)
- Specialized sanitizers for email, username, URL, filename, JSON
- Security threat detection and scanning
- Configurable length limits (10KB-100KB)
-
Global Security Middleware (src/middlewares/sanitization.middleware.js)
- Automatic input sanitization for body, query, and params
- Real-time security scanning with threat blocking
- Request payload size enforcement (100KB limit)
-
Controller-Level Field Sanitization
- Field-specific validation rules
- Type-safe sanitization
- Express-validator integration
Run the security test suite:
node test-sanitization.jsFor detailed security documentation, see SECURITY.md
- Runtime: Node.js
- Framework: Express.js
- Database: PostgreSQL
- ORM: Prisma
- Authentication: JWT (jsonwebtoken)
- Encryption: AES-256-GCM (crypto)
- Scheduling: node-cron
- HTTP Client: Axios
- Logging: Winston
- Validation: express-validator
src/
├── app.js # Express app setup
├── server.js # Server entry point
├── config/
│ ├── env.js # Environment configuration
│ ├── prisma.js # Prisma client setup
│ └── cron.js # Cron job manager
├── routes/
│ ├── auth.routes.js # Authentication routes
│ ├── challenge.routes.js # Challenge routes
│ └── dashboard.routes.js # Dashboard routes
├── controllers/
│ ├── auth.controller.js # Auth request handlers
│ ├── challenge.controller.js # Challenge request handlers
│ └── dashboard.controller.js # Dashboard request handlers
├── services/
│ ├── auth.service.js # Authentication business logic
│ ├── challenge.service.js # Challenge business logic
│ ├── leetcode.service.js # LeetCode API integration
│ ├── penalty.service.js # Penalty management
│ └── evaluation.service.js # Daily evaluation logic
├── middlewares/
│ ├── auth.middleware.js # JWT authentication
│ ├── error.middleware.js # Error handling
│ ├── rateLimiter.middleware.js # Rate limiting
│ └── sanitization.middleware.js # 🔒 Input sanitization
├── utils/
│ ├── jwt.js # JWT utilities
│ ├── encryption.js # Encryption utilities
│ ├── logger.js # Winston logger
│ └── sanitizer.js # 🔒 Security sanitizer
└── prisma/
└── schema.prisma # Database schema
│ ├── penalty.service.js # Penalty management │ └── evaluation.service.js # Daily evaluation logic ├── middlewares/ │ ├── auth.middleware.js # JWT authentication │ └── error.middleware.js # Error handling ├── utils/ │ ├── jwt.js # JWT utilities │ ├── encryption.js # Encryption utilities │ └── logger.js # Winston logger └── prisma/ └── schema.prisma # Database schema
## 🚦 Getting Started
### Prerequisites
- Node.js (v16 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn
### Installation
1. **Clone the repository**
```bash
cd "f:\DATA\College\Project and stuff\Leetcode streak"
-
Install dependencies
npm install
-
Set up environment variables
cp .env.example .env
Edit
.envand configure:DATABASE_URL: PostgreSQL connection stringJWT_SECRET: Generate withnode -e "console.log(require('crypto').randomBytes(32).toString('hex'))"ENCRYPTION_KEY: Generate withnode -e "console.log(require('crypto').randomBytes(32).toString('hex'))"APP_BASE_URL: Frontend/base URL used in password reset links (e.g.http://localhost:5173)PASSWORD_RESET_TOKEN_EXPIRY_MINUTES: Reset token validity window in minutes (default:60)- Other configuration as needed
-
Set up database
npm run prisma:generate npm run prisma:migrate
-
Start the server
# Development mode with auto-reload npm run dev # Production mode npm start
The server will start on http://localhost:3000 (or the port specified in .env).
POST /api/auth/register- Register new userPOST /api/auth/login- Login userPOST /api/auth/forgot-password- Request password reset linkPOST /api/auth/reset-password- Reset password with tokenGET /api/auth/profile- Get current user profile (protected)PUT /api/auth/profile- Update user profile (protected)
POST /api/challenges- Create new challenge (protected)GET /api/challenges- Get user's challenges (protected)GET /api/challenges/:id- Get challenge details (protected)POST /api/challenges/:id/join- Join a challenge (protected)PATCH /api/challenges/:id/status- Update challenge status (protected, owner only)
GET /api/dashboard- Get dashboard overview (protected)GET /api/dashboard/today- Get today's status (protected)GET /api/dashboard/challenge/:id- Get detailed challenge progress (protected)GET /api/dashboard/challenge/:id/leaderboard- Get challenge leaderboard (protected)
GET /health- Server health status
- User authentication and profile information
- LeetCode username mapping
- Challenge configuration and rules
- Start/end dates, difficulty filters, penalty amounts
- User participation in challenges
- Streak tracking and penalty totals
- Daily evaluation results
- Submission counts and problem tracking
- Penalty transaction history
Daily evaluation runs automatically based on DAILY_EVALUATION_TIME in .env:
# Run at 1:00 AM daily (recommended)
DAILY_EVALUATION_TIME=0 1 * * *
# For testing - run every 15 minutes
DAILY_EVALUATION_TIME=*/15 * * * *When creating a challenge, configure:
minSubmissionsPerDay: Minimum accepted submissions requireddifficultyFilter: Array of difficulties (Easy, Medium, Hard)uniqueProblemConstraint: Whether to count unique problems onlypenaltyAmount: Virtual penalty for missed days
- Password hashing with bcrypt (12 rounds)
- JWT-based authentication
- AES-256-GCM encryption for sensitive data
- Input validation on all endpoints
- SQL injection protection via Prisma ORM
- Environment variable validation on startup
- Email verification before account activation
- Service Layer: Add business logic in
src/services/ - Controller: Add request handlers in
src/controllers/ - Routes: Define endpoints in
src/routes/ - Validation: Add input validation in controllers
# Create migration
npm run prisma:migrate
# Regenerate Prisma Client
npm run prisma:generate
# Open Prisma Studio (DB GUI)
npm run prisma:studioUses Winston for structured logging:
- Console logs with colors (development)
- File logs:
logs/combined.log,logs/error.log - Exception/rejection logs
- Verify PostgreSQL is running
- Check
DATABASE_URLin.env - Ensure database exists:
createdb leetcode_tracker
- LeetCode may rate limit requests
- Consider adding delays between requests
- Check
CRON_ENABLED=truein.env - Verify cron expression syntax
- Check logs for error messages
-
Environment
- Set
NODE_ENV=production - Use strong secrets for
JWT_SECRETandENCRYPTION_KEY - Configure
CORS_ORIGINto your frontend URL
- Set
-
Database
- Use production PostgreSQL instance
- Run migrations:
npm run prisma:migrate
-
Process Management
- Use PM2 or similar for process management
- Enable clustering for high availability
-
Monitoring
- Monitor logs in
logs/directory - Set up error alerting
- Monitor cron job execution
- Monitor logs in
ISC
Built with ❤️ for the LeetCode community