Files
TurboTrades/FILE_PROTOCOL_TESTING.md
2026-01-10 04:57:43 +00:00

367 lines
9.6 KiB
Markdown

# 🌐 File Protocol Testing Guide
## Overview
This guide explains how to use the test client (`test-client.html`) when opened directly from your filesystem (`file://` protocol) instead of through a web server.
---
## 🔑 The Authentication Challenge
When you open `test-client.html` directly from your filesystem:
- The file runs with `file://` protocol (e.g., `file:///C:/Users/you/TurboTrades/test-client.html`)
- Cookies set by `http://localhost:3000` are **not accessible** from `file://`
- You must use **Bearer token authentication** instead of cookies
---
## ✅ How to Authenticate
### Step 1: Login via Steam
1. **Open your browser and navigate to:**
```
http://localhost:3000/auth/steam
```
2. **Complete Steam OAuth login**
- You'll be redirected to Steam
- Authorize the application
- You'll be redirected back
3. **Get your access token**
- After successful login, navigate to:
```
http://localhost:3000/auth/decode-token
```
- Copy the entire `accessToken` value from the JSON response
**Alternative: Extract from Browser Console**
```javascript
// Open browser console (F12) on http://localhost:3000
document.cookie.split('; ').find(row => row.startsWith('accessToken=')).split('=')[1]
```
---
### Step 2: Use Token in Test Client
1. **Open the test client:**
```
Double-click: test-client.html
```
2. **Paste your token:**
- Find the "Access Token (optional)" field in the Connection section
- Paste your full JWT token (starts with `eyJhbGciOiJIUzI1NiIs...`)
3. **Verify authentication:**
- Click **"🔄 Check Auth Status"** button in the Authentication Status section
- You should see: ✅ Authenticated with your username and Steam ID
---
## 🧪 What Works Now
With your token pasted, you can use all authenticated features:
### ✅ WebSocket Connection
```
- Connect with token in URL parameter
- Receive authenticated welcome message
- Server identifies you by Steam ID
```
### ✅ Marketplace APIs
```
- Create Listing (POST /marketplace/listings)
- Update Price (PATCH /marketplace/listings/:id/price)
- Get Listings (GET /marketplace/listings) - with user-specific data
```
### ✅ User APIs
```
- Set Trade URL (PUT /user/trade-url)
- Update Email (PATCH /user/email)
- Get Profile (GET /user/profile)
- Get Balance (GET /user/balance)
- Get Stats (GET /user/stats)
```
---
## 🔍 How It Works
### API Request Flow
1. **Test client reads token from input field:**
```javascript
const token = document.getElementById("token").value;
```
2. **Adds Authorization header to requests:**
```javascript
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
}
```
3. **Server validates token:**
```javascript
// Server checks Authorization header first
const authHeader = request.headers.authorization;
if (authHeader && authHeader.startsWith("Bearer ")) {
token = authHeader.substring(7);
}
// Falls back to cookies if no header
if (!token && request.cookies.accessToken) {
token = request.cookies.accessToken;
}
```
4. **Request succeeds with user context**
---
## 🎯 Quick Start Example
### Example: Create a Listing
1. **Login and get token** (see Step 1 above)
```
Your token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOi...
```
2. **Open test-client.html**
3. **Paste token in "Access Token" field**
4. **Click "Check Auth Status"**
- Should show: ✅ Authenticated as [Your Name]
5. **Set your Trade URL** (if not set):
- Get from: Steam → Inventory → Trade Offers → "Who can send me trade offers?"
- Format: `https://steamcommunity.com/tradeoffer/new/?partner=XXXXX&token=XXXXX`
- Click "Set Trade URL"
6. **Create a listing:**
- Item Name: "AK-47 | Redline"
- Game: CS2
- Price: 45.99
- Click "Create Listing (Requires Auth)"
7. **Success!** ✅
- You'll get a success message
- WebSocket will broadcast the new listing to all connected clients
---
## 🐛 Troubleshooting
### "No access token provided" Error
**Problem:** Token not being sent with request
**Solutions:**
1. Check token is pasted in "Access Token" field
2. Click "Check Auth Status" to verify
3. Token must be the full JWT (starts with `eyJhbGci...`)
4. Token expires after 15 minutes - get a new one
---
### "Invalid access token" Error
**Problem:** Token is expired or malformed
**Solutions:**
1. Login again to get a fresh token
2. Copy the entire token (no spaces or line breaks)
3. Check token hasn't expired (15 minute lifespan)
---
### "Trade URL must be set" Error
**Problem:** Trying to create listing without trade URL
**Solutions:**
1. Set your trade URL first using the "Set Trade URL" section
2. Get your trade URL from Steam:
- Steam → Inventory → Trade Offers
- "Who can send me trade offers?"
- Copy the URL
---
### Authentication Status Shows "Not Authenticated"
**Problem:** Token not recognized or not present
**Solutions:**
1. Make sure you pasted the token in the "Access Token" field
2. Click "Check Auth Status" button
3. If still failing, get a new token (it may have expired)
4. Check browser console for specific error messages
---
## 📊 Token Information
### Your Current Token
```
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2OTYxMzRlOTIwNzYxOTc3ZGNjMWQ2ZDIiLCJzdGVhbUlkIjoiNzY1NjExOTgwMjc2MDgwNzEiLCJ1c2VybmFtZSI6IuKchSBBc2hsZXkg44Ki44K344Ol44Oq44O8IiwiYXZhdGFyIjoiaHR0cHM6Ly9hdmF0YXJzLnN0ZWFtc3RhdGljLmNvbS9kNmI2MTY0NjQ2MjlkYjIxNjcwYTQ0NTY3OWFlZmVlYjE4ZmI0MDFmX2Z1bGwuanBnIiwic3RhZmZMZXZlbCI6MCwiaWF0IjoxNzY3OTk0MzkwLCJleHAiOjE3Njc5OTUyOTAsImF1ZCI6InR1cmJvdHJhZGVzLWFwaSIsImlzcyI6InR1cmJvdHJhZGVzIn0.9Xh-kDvWZbQERuXgRb-NEMw6il2h8SQyVQySdILcLo8
User ID: 696134e92076197...[truncated]
Steam ID: 76561198027608071
Username: ✅ Ashley アシュリー
Staff Level: 0
Issued At: 1767994390 (Unix timestamp)
Expires At: 1767995290 (Unix timestamp - 15 minutes from issue)
```
### Token Lifespan
- **Access Token:** 15 minutes
- **Refresh Token:** 7 days (stored in cookies, not available in file:// protocol)
### When Token Expires
1. Navigate to `http://localhost:3000/auth/steam` again
2. You'll be automatically logged in (Steam session still active)
3. Get new token from `/auth/decode-token`
4. Paste new token in test client
---
## 🎓 Advanced Tips
### Save Token Temporarily
```javascript
// In browser console on test client page
localStorage.setItem('authToken', 'YOUR_TOKEN_HERE');
// Load it later
const token = localStorage.getItem('authToken');
document.getElementById('token').value = token;
```
### Check Token Expiry
```javascript
// Decode JWT (client-side, no verification)
function parseJwt(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
const decoded = parseJwt(YOUR_TOKEN);
const expiresAt = new Date(decoded.exp * 1000);
console.log('Token expires at:', expiresAt);
```
### Auto-Refresh Before Expiry
```javascript
// Set up auto-refresh 1 minute before expiry
const decoded = parseJwt(token);
const expiresIn = (decoded.exp * 1000) - Date.now();
const refreshTime = expiresIn - 60000; // 1 minute before
if (refreshTime > 0) {
setTimeout(() => {
alert('Token expiring soon! Please get a new token.');
}, refreshTime);
}
```
---
## 🌐 Alternative: Use a Web Server
If you prefer cookie-based authentication:
### Option 1: Simple HTTP Server (Python)
```bash
cd TurboTrades
python -m http.server 8000
```
Then open: `http://localhost:8000/test-client.html`
### Option 2: Node.js HTTP Server
```bash
cd TurboTrades
npx http-server -p 8000
```
Then open: `http://localhost:8000/test-client.html`
### Option 3: VS Code Live Server
1. Install "Live Server" extension
2. Right-click `test-client.html`
3. Select "Open with Live Server"
**Note:** With a web server, cookies will work and you don't need to paste tokens!
---
## 📋 Testing Checklist
### With Token Authentication (file:// protocol)
- [ ] Login via Steam
- [ ] Get access token
- [ ] Paste token in test client
- [ ] Check auth status (should show ✅)
- [ ] Connect WebSocket with token
- [ ] Set trade URL
- [ ] Create listing
- [ ] Update listing price
- [ ] Get listings
- [ ] Verify WebSocket broadcasts received
---
## 🔐 Security Notes
### Token Security
- ✅ Token is sent via HTTPS in production
- ✅ Token expires after 15 minutes
- ✅ Token is JWT signed and verified server-side
- ⚠️ Don't share your token with others
- ⚠️ Don't commit tokens to version control
### File Protocol Limitations
- ❌ Cookies don't work across protocols
- ❌ Can't access localStorage from different origin
- ✅ Authorization header works perfectly
- ✅ CORS configured to allow file:// protocol
---
## 📚 Related Documentation
- **WEBSOCKET_AUTH.md** - WebSocket authentication details
- **TESTING_GUIDE.md** - Comprehensive testing guide
- **TEST_CLIENT_REFERENCE.md** - Quick reference for test client
- **NEW_FEATURES.md** - Latest features and enhancements
---
## 💡 Summary
**File Protocol Testing Flow:**
1. Login via `http://localhost:3000/auth/steam`
2. Get token from `/auth/decode-token`
3. Paste token in test client "Access Token" field
4. Click "Check Auth Status"
5. Use all authenticated features! 🎉
**Key Points:**
- Token authentication works from `file://` protocol
- Token lasts 15 minutes
- Server accepts `Authorization: Bearer <token>` header
- All API requests automatically include your token
- WebSocket can use token via query parameter
**You're all set! Happy testing! 🚀**