# TurboTrades Project Structure Clean and simple structure with everything in the root directory. ## ๐Ÿ“ Directory Tree ``` TurboTrades/ โ”œโ”€โ”€ config/ # Configuration files โ”‚ โ”œโ”€โ”€ database.js # MongoDB connection handler โ”‚ โ”œโ”€โ”€ index.js # Environment variables loader โ”‚ โ””โ”€โ”€ passport.js # Steam OAuth strategy setup โ”‚ โ”œโ”€โ”€ middleware/ # Custom Express/Fastify middleware โ”‚ โ””โ”€โ”€ auth.js # JWT authentication & authorization โ”‚ โ”œโ”€โ”€ models/ # MongoDB/Mongoose schemas โ”‚ โ””โ”€โ”€ User.js # User schema (Steam, 2FA, email, bans) โ”‚ โ”œโ”€โ”€ routes/ # API route handlers โ”‚ โ”œโ”€โ”€ auth.js # Authentication routes (Steam login, logout, refresh) โ”‚ โ”œโ”€โ”€ marketplace.example.js # Example marketplace implementation โ”‚ โ”œโ”€โ”€ user.js # User profile & settings routes โ”‚ โ””โ”€โ”€ websocket.js # WebSocket management routes โ”‚ โ”œโ”€โ”€ utils/ # Utility functions & helpers โ”‚ โ”œโ”€โ”€ jwt.js # JWT token generation & verification โ”‚ โ””โ”€โ”€ websocket.js # WebSocket manager with user mapping โ”‚ โ”œโ”€โ”€ .env # Environment variables (local config) โ”œโ”€โ”€ .env.example # Environment variables template โ”œโ”€โ”€ .gitignore # Git ignore rules โ”œโ”€โ”€ index.js # Main server entry point โญ โ”œโ”€โ”€ package.json # Dependencies & npm scripts โ”‚ โ””โ”€โ”€ Documentation/ โ”œโ”€โ”€ ARCHITECTURE.md # System architecture & diagrams โ”œโ”€โ”€ COMMANDS.md # Command reference cheatsheet โ”œโ”€โ”€ PROJECT_SUMMARY.md # High-level project overview โ”œโ”€โ”€ QUICKSTART.md # 5-minute setup guide โ”œโ”€โ”€ README.md # Main documentation โ”œโ”€โ”€ STRUCTURE.md # This file โ”œโ”€โ”€ WEBSOCKET_GUIDE.md # WebSocket integration guide โ””โ”€โ”€ test-client.html # WebSocket test interface ``` ## ๐ŸŽฏ File Purposes ### Core Files **`index.js`** - Main server entry point - Initializes Fastify server - Registers all plugins (CORS, Helmet, WebSocket, etc.) - Connects to MongoDB - Registers all routes - Starts the server ### Configuration (`config/`) **`config/index.js`** - Central configuration - Loads environment variables from `.env` - Exports config object used throughout the app - Provides sensible defaults **`config/database.js`** - Database connection - Connects to MongoDB using Mongoose - Handles connection errors and retries - Graceful shutdown support **`config/passport.js`** - Authentication strategy - Configures passport-steam strategy - Handles Steam OAuth flow - Creates/updates users on login ### Middleware (`middleware/`) **`middleware/auth.js`** - Authentication & authorization - `authenticate()` - Requires valid JWT token - `optionalAuthenticate()` - Optional JWT verification - `requireStaffLevel()` - Check staff permissions - `requireVerifiedEmail()` - Require verified email - `require2FA()` - Require two-factor auth - `verifyRefreshTokenMiddleware()` - Verify refresh tokens ### Models (`models/`) **`models/User.js`** - User database schema - Steam profile data (ID, username, avatar) - Marketplace data (balance, trade URL) - Email system (address, verification) - Security (bans, 2FA, staff level) - Timestamps (createdAt, updatedAt) ### Routes (`routes/`) **`routes/auth.js`** - Authentication endpoints - `GET /auth/steam` - Start Steam login - `GET /auth/steam/return` - OAuth callback - `GET /auth/me` - Get current user - `POST /auth/refresh` - Refresh access token - `POST /auth/logout` - Logout user - `GET /auth/verify` - Verify token validity **`routes/user.js`** - User management endpoints - `GET /user/profile` - Get user profile - `PATCH /user/trade-url` - Update trade URL - `PATCH /user/email` - Update email address - `GET /user/verify-email/:token` - Verify email - `GET /user/balance` - Get balance - `GET /user/stats` - Get user statistics - `PATCH /user/intercom` - Update intercom ID - `GET /user/:steamId` - Public user profile **`routes/websocket.js`** - WebSocket management - `GET /ws` - WebSocket connection endpoint - `GET /ws/stats` - Connection statistics - `POST /ws/broadcast` - Broadcast to all (admin) - `POST /ws/send/:userId` - Send to specific user - `GET /ws/status/:userId` - Check online status **`routes/marketplace.example.js`** - Example implementation - Shows how to create marketplace routes - Demonstrates WebSocket broadcasting - Example purchase flow with notifications ### Utils (`utils/`) **`utils/jwt.js`** - JWT token utilities - `generateAccessToken()` - Create access token (15min) - `generateRefreshToken()` - Create refresh token (7 days) - `generateTokenPair()` - Create both tokens - `verifyAccessToken()` - Verify access token - `verifyRefreshToken()` - Verify refresh token - `isTokenExpired()` - Check if token expired **`utils/websocket.js`** - WebSocket manager - `handleConnection()` - Process new connections - `broadcastPublic()` - Send to all clients - `broadcastToAuthenticated()` - Send to authenticated users - `sendToUser()` - Send to specific user - `isUserConnected()` - Check if user is online - User-to-socket mapping - Heartbeat/ping-pong system - Automatic cleanup of dead connections ## ๐Ÿ”„ Data Flow ### Authentication Flow ``` Client โ†’ /auth/steam โ†’ Steam โ†’ /auth/steam/return โ†’ Generate JWT โ†’ Set Cookies โ†’ Client ``` ### API Request Flow ``` Client โ†’ Nginx โ†’ Fastify โ†’ Middleware โ†’ Route Handler โ†’ Database โ†’ Response ``` ### WebSocket Flow ``` Client โ†’ /ws โ†’ Authenticate โ†’ Map User โ†’ Send/Receive Messages โ†’ Broadcast ``` ## ๐Ÿ“ฆ Key Dependencies ```json { "fastify": "High-performance web framework", "mongoose": "MongoDB ODM", "passport-steam": "Steam OAuth authentication", "jsonwebtoken": "JWT token creation/verification", "ws": "WebSocket implementation", "@fastify/cookie": "Cookie parsing & setting", "@fastify/cors": "CORS support", "@fastify/helmet": "Security headers", "@fastify/rate-limit": "Rate limiting", "@fastify/websocket": "WebSocket plugin for Fastify" } ``` ## ๐Ÿš€ Getting Started 1. **Install dependencies** ```bash npm install ``` 2. **Configure environment** ```bash cp .env.example .env # Edit .env with your Steam API key ``` 3. **Start MongoDB** ```bash mongod ``` 4. **Run the server** ```bash npm run dev ``` ## ๐Ÿ“ Adding New Features ### Adding a new route 1. Create file in `routes/` (e.g., `routes/trades.js`) 2. Define your endpoints with proper middleware 3. Import and register in `index.js` ```javascript // routes/trades.js export default async function tradesRoutes(fastify, options) { fastify.get('/trades', { preHandler: authenticate }, async (req, reply) => { // Your logic here }); } // index.js import tradesRoutes from './routes/trades.js'; await fastify.register(tradesRoutes); ``` ### Adding a new model 1. Create file in `models/` (e.g., `models/Listing.js`) 2. Define Mongoose schema 3. Export the model ```javascript // models/Listing.js import mongoose from 'mongoose'; const ListingSchema = new mongoose.Schema({ itemName: String, price: Number, seller: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }, { timestamps: true }); export default mongoose.model('Listing', ListingSchema); ``` ### Adding middleware 1. Create or update file in `middleware/` 2. Export your middleware function 3. Use in routes with `preHandler` ```javascript // middleware/custom.js export const myMiddleware = async (request, reply) => { // Your logic }; // In routes fastify.get('/protected', { preHandler: [authenticate, myMiddleware] }, handler); ``` ### Adding utilities 1. Create file in `utils/` (e.g., `utils/email.js`) 2. Export utility functions 3. Import where needed ```javascript // utils/email.js export const sendVerificationEmail = async (email, token) => { // Email logic }; // In routes import { sendVerificationEmail } from '../utils/email.js'; ``` ## ๐Ÿงช Testing ```bash # Health check curl http://localhost:3000/health # Test authenticated endpoint curl http://localhost:3000/auth/me \ -H "Authorization: Bearer YOUR_TOKEN" # Test WebSocket open test-client.html ``` ## ๐Ÿ“š Documentation Files - **README.md** - Start here for complete overview - **QUICKSTART.md** - Get running in 5 minutes - **WEBSOCKET_GUIDE.md** - Detailed WebSocket integration - **ARCHITECTURE.md** - System design & diagrams - **COMMANDS.md** - Command reference guide - **PROJECT_SUMMARY.md** - High-level summary - **STRUCTURE.md** - This file (project organization) ## ๐ŸŽฏ Why This Structure? โœ… **Simple** - No nested `src/` folder, everything at root level โœ… **Clear** - Organized by function (routes, models, utils) โœ… **Scalable** - Easy to add new features โœ… **Standard** - Follows Node.js conventions โœ… **Clean** - Separation of concerns โœ… **Maintainable** - Easy to navigate and understand --- **Ready to build your marketplace! ๐Ÿš€**