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

361
QUICKSTART.md Normal file
View File

@@ -0,0 +1,361 @@
# Quick Start Guide
Get TurboTrades backend up and running in 5 minutes!
## Prerequisites
- Node.js 18+ installed
- MongoDB running locally or accessible remotely
- Steam API key ([Get one here](https://steamcommunity.com/dev/apikey))
## Step 1: Install Dependencies
```bash
npm install
```
## Step 2: Configure Environment
Create a `.env` file in the root directory:
```bash
cp .env.example .env
```
Edit `.env` with your settings:
```env
# Minimum required configuration
MONGODB_URI=mongodb://localhost:27017/turbotrades
STEAM_API_KEY=YOUR_STEAM_API_KEY_HERE
SESSION_SECRET=change-this-to-something-random
JWT_ACCESS_SECRET=change-this-to-something-random
JWT_REFRESH_SECRET=change-this-to-something-different
```
**Important**: Generate secure random secrets for production:
```bash
# On Linux/Mac
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# Or use this online: https://randomkeygen.com/
```
## Step 3: Start MongoDB
If MongoDB isn't running:
```bash
# Start MongoDB service
mongod
# Or with Docker
docker run -d -p 27017:27017 --name mongodb mongo:latest
```
## Step 4: Start the Server
```bash
# Development mode (auto-reload on file changes)
npm run dev
# Production mode
npm start
```
You should see:
```
✅ MongoDB connected successfully
✅ All plugins registered
✅ All routes registered
✅ Server running on http://0.0.0.0:3000
📡 WebSocket available at ws://0.0.0.0:3000/ws
🔐 Steam Login: http://0.0.0.0:3000/auth/steam
```
## Step 5: Test the API
### Check Health
```bash
curl http://localhost:3000/health
```
Response:
```json
{
"status": "ok",
"timestamp": 1234567890,
"uptime": 12.34,
"environment": "development"
}
```
### Test Steam Login
Open your browser and navigate to:
```
http://localhost:3000/auth/steam
```
This will redirect you to Steam for authentication. After logging in, you'll be redirected back with JWT tokens set as httpOnly cookies.
### Get Current User
```bash
curl http://localhost:3000/auth/me \
-H "Cookie: accessToken=YOUR_ACCESS_TOKEN"
```
Or from browser console after logging in:
```javascript
fetch('/auth/me', { credentials: 'include' })
.then(r => r.json())
.then(console.log);
```
## Step 6: Test WebSocket
Open browser console and run:
```javascript
const ws = new WebSocket('ws://localhost:3000/ws');
ws.onopen = () => console.log('✅ Connected');
ws.onmessage = (e) => console.log('📨 Received:', JSON.parse(e.data));
ws.onerror = (e) => console.error('❌ Error:', e);
// Send a ping
ws.send(JSON.stringify({ type: 'ping' }));
// You should receive a pong response
```
## Common Issues
### MongoDB Connection Error
**Error**: `MongoServerError: connect ECONNREFUSED`
**Solution**: Make sure MongoDB is running:
```bash
# Check if MongoDB is running
ps aux | grep mongod
# Or check the service
brew services list | grep mongodb # macOS
systemctl status mongod # Linux
```
### Steam Auth Not Working
**Error**: Redirect loop or "Invalid API Key"
**Solutions**:
1. Make sure your Steam API key is correct in `.env`
2. Check that `STEAM_REALM` and `STEAM_RETURN_URL` match your domain
3. For local development, use `http://localhost:3000` (not 127.0.0.1)
### Port Already in Use
**Error**: `EADDRINUSE: address already in use`
**Solution**: Either kill the process using port 3000 or change the port:
```bash
# Find process using port 3000
lsof -i :3000 # macOS/Linux
netstat -ano | find "3000" # Windows
# Kill the process
kill -9 <PID>
# Or change port in .env
PORT=3001
```
### CORS Errors
**Error**: `Access-Control-Allow-Origin` error in browser
**Solution**: Update `CORS_ORIGIN` in `.env` to match your frontend URL:
```env
CORS_ORIGIN=http://localhost:3000
```
## Next Steps
### 1. Explore the API
Check out all available endpoints in `README.md`
### 2. Implement 2FA
The user schema is ready for 2FA. You'll need to:
- Install `speakeasy` or `otplib`
- Create routes for enabling/disabling 2FA
- Verify TOTP codes during sensitive operations
### 3. Add Email Service
The schema includes email fields. Set up email service:
- Install `nodemailer`
- Configure SMTP settings in `.env`
- Create email templates
- Send verification emails
### 4. Create Item Models
Create models for:
- Items/Listings
- Transactions
- Trade history
- Inventory
Example in `models/Listing.js`:
```javascript
import mongoose from "mongoose";
const ListingSchema = new mongoose.Schema({
itemName: { type: String, required: true },
game: { type: String, enum: ['cs2', 'rust'], required: true },
price: { type: Number, required: true, min: 0 },
seller: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
status: { type: String, enum: ['active', 'sold', 'cancelled'], default: 'active' },
assetId: String,
description: String,
createdAt: { type: Date, default: Date.now }
}, { timestamps: true });
export default mongoose.model('Listing', ListingSchema);
```
### 5. Integrate Steam API
For inventory management and trade offers:
- Install `steam-community` and `steam-tradeoffer-manager`
- Fetch user inventories
- Send trade offers automatically
- Handle trade confirmations
### 6. Add Payment Processing
Integrate payment providers:
- Stripe for card payments
- PayPal
- Crypto payments
- Steam Wallet top-ups
### 7. Build Admin Dashboard
Create admin routes in `routes/admin.js`:
- User management
- Transaction monitoring
- Site statistics
- Ban/unban users
- Manage listings
### 8. Deploy to Production
See `README.md` for deployment instructions using:
- PM2 for process management
- Nginx as reverse proxy
- SSL certificates with Let's Encrypt
- MongoDB Atlas for hosted database
## Useful Commands
```bash
# Start with watch mode (auto-reload)
npm run dev
# Start production
npm start
# Install new package
npm install package-name
# Check for updates
npm outdated
# Update dependencies
npm update
```
## Development Tips
### 1. Use VSCode Extensions
- ESLint
- Prettier
- MongoDB for VS Code
- REST Client (for testing APIs)
### 2. Enable Logging
Set log level in Fastify config:
```javascript
logger: {
level: 'debug' // trace, debug, info, warn, error, fatal
}
```
### 3. Hot Reload
Node 18+ has built-in watch mode:
```bash
node --watch src/index.js
```
### 4. Database GUI
Use MongoDB Compass for visual database management:
- Download: https://www.mongodb.com/products/compass
### 5. API Testing
Use tools like:
- Postman
- Insomnia
- HTTPie
- curl
Example Postman collection structure:
```
TurboTrades/
├── Auth/
│ ├── Login (GET /auth/steam)
│ ├── Get Me (GET /auth/me)
│ ├── Refresh Token (POST /auth/refresh)
│ └── Logout (POST /auth/logout)
├── User/
│ ├── Get Profile
│ ├── Update Trade URL
│ └── Update Email
└── WebSocket/
└── Get Stats
```
## Resources
- [Fastify Documentation](https://www.fastify.io/docs/latest/)
- [Mongoose Documentation](https://mongoosejs.com/docs/)
- [Steam Web API Documentation](https://developer.valvesoftware.com/wiki/Steam_Web_API)
- [JWT.io](https://jwt.io/) - Debug JWT tokens
- [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
## Get Help
- Check `README.md` for detailed documentation
- Read `WEBSOCKET_GUIDE.md` for WebSocket integration
- Review example code in `src/routes/marketplace.example.js`
- Open an issue on GitHub
---
**Happy coding! 🚀**