first commit

This commit is contained in:
2026-01-10 04:57:43 +00:00
parent 16a76a2cd6
commit 232968de1e
131 changed files with 43262 additions and 0 deletions

308
STRUCTURE.md Normal file
View File

@@ -0,0 +1,308 @@
# 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! 🚀**