223 lines
7.3 KiB
JavaScript
223 lines
7.3 KiB
JavaScript
import axios from 'axios';
|
||
|
||
/**
|
||
* Authentication Test Script
|
||
* Tests cookie handling and authentication flow
|
||
*/
|
||
|
||
const API_URL = 'http://localhost:3000';
|
||
const FRONTEND_URL = 'http://localhost:5173';
|
||
|
||
// Create axios instance with cookie jar simulation
|
||
const api = axios.create({
|
||
baseURL: API_URL,
|
||
withCredentials: true,
|
||
headers: {
|
||
'Origin': FRONTEND_URL,
|
||
'Referer': FRONTEND_URL,
|
||
},
|
||
});
|
||
|
||
let cookies = {};
|
||
|
||
// Interceptor to store cookies
|
||
api.interceptors.response.use((response) => {
|
||
const setCookie = response.headers['set-cookie'];
|
||
if (setCookie) {
|
||
setCookie.forEach((cookie) => {
|
||
const [nameValue] = cookie.split(';');
|
||
const [name, value] = nameValue.split('=');
|
||
cookies[name] = value;
|
||
});
|
||
}
|
||
return response;
|
||
});
|
||
|
||
// Interceptor to send cookies
|
||
api.interceptors.request.use((config) => {
|
||
if (Object.keys(cookies).length > 0) {
|
||
config.headers['Cookie'] = Object.entries(cookies)
|
||
.map(([name, value]) => `${name}=${value}`)
|
||
.join('; ');
|
||
}
|
||
return config;
|
||
});
|
||
|
||
async function testHealth() {
|
||
console.log('\n📡 Testing backend health...');
|
||
try {
|
||
const response = await api.get('/health');
|
||
console.log('✅ Backend is running:', response.data);
|
||
return true;
|
||
} catch (error) {
|
||
console.error('❌ Backend health check failed:', error.message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
async function testDebugCookies() {
|
||
console.log('\n🍪 Testing cookie debug endpoint...');
|
||
try {
|
||
const response = await api.get('/auth/debug-cookies');
|
||
console.log('✅ Debug cookies response:', JSON.stringify(response.data, null, 2));
|
||
return response.data;
|
||
} catch (error) {
|
||
console.error('❌ Debug cookies failed:', error.response?.data || error.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function testAuthMe() {
|
||
console.log('\n👤 Testing /auth/me (requires login)...');
|
||
try {
|
||
const response = await api.get('/auth/me');
|
||
console.log('✅ Authenticated user:', {
|
||
username: response.data.user.username,
|
||
steamId: response.data.user.steamId,
|
||
balance: response.data.user.balance,
|
||
staffLevel: response.data.user.staffLevel,
|
||
});
|
||
return response.data.user;
|
||
} catch (error) {
|
||
console.error('❌ Not authenticated:', error.response?.data || error.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function testSessions() {
|
||
console.log('\n📱 Testing /user/sessions (requires login)...');
|
||
try {
|
||
const response = await api.get('/user/sessions');
|
||
console.log('✅ Sessions retrieved:', {
|
||
count: response.data.sessions.length,
|
||
sessions: response.data.sessions.map(s => ({
|
||
device: s.device,
|
||
browser: s.browser,
|
||
os: s.os,
|
||
lastActivity: s.lastActivity,
|
||
})),
|
||
});
|
||
return response.data.sessions;
|
||
} catch (error) {
|
||
console.error('❌ Failed to get sessions:', error.response?.data || error.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function test2FASetup() {
|
||
console.log('\n🔐 Testing /user/2fa/setup (requires login)...');
|
||
try {
|
||
const response = await api.post('/user/2fa/setup');
|
||
console.log('✅ 2FA setup initiated:', {
|
||
hasQRCode: !!response.data.qrCode,
|
||
hasSecret: !!response.data.secret,
|
||
hasRevocationCode: !!response.data.revocationCode,
|
||
});
|
||
return response.data;
|
||
} catch (error) {
|
||
console.error('❌ Failed to setup 2FA:', error.response?.data || error.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function testRouteRegistration() {
|
||
console.log('\n🛣️ Testing route registration...');
|
||
const routes = [
|
||
'/health',
|
||
'/auth/steam/test',
|
||
'/auth/debug-cookies',
|
||
'/auth/me',
|
||
'/user/sessions',
|
||
'/user/2fa/setup',
|
||
'/market/items',
|
||
];
|
||
|
||
for (const route of routes) {
|
||
try {
|
||
const response = await api.get(route);
|
||
console.log(`✅ ${route} - Registered (Status: ${response.status})`);
|
||
} catch (error) {
|
||
if (error.response?.status === 401) {
|
||
console.log(`✅ ${route} - Registered (Requires auth)`);
|
||
} else if (error.response?.status === 404) {
|
||
console.log(`❌ ${route} - NOT FOUND`);
|
||
} else {
|
||
console.log(`⚠️ ${route} - Status: ${error.response?.status || 'Error'}`);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
async function runTests() {
|
||
console.log('╔════════════════════════════════════════╗');
|
||
console.log('║ TurboTrades Authentication Tests ║');
|
||
console.log('╚════════════════════════════════════════╝');
|
||
|
||
// Test 1: Backend health
|
||
const healthOk = await testHealth();
|
||
if (!healthOk) {
|
||
console.log('\n❌ Backend is not running. Start it with: npm run dev');
|
||
process.exit(1);
|
||
}
|
||
|
||
// Test 2: Route registration
|
||
await testRouteRegistration();
|
||
|
||
// Test 3: Debug cookies (no auth required)
|
||
const debugData = await testDebugCookies();
|
||
if (debugData) {
|
||
console.log('\n📊 Cookie Configuration:');
|
||
console.log(' Domain:', debugData.config?.cookieDomain || 'Not set');
|
||
console.log(' Secure:', debugData.config?.cookieSecure || false);
|
||
console.log(' SameSite:', debugData.config?.cookieSameSite || 'Not set');
|
||
console.log(' CORS Origin:', debugData.config?.corsOrigin || 'Not set');
|
||
}
|
||
|
||
// Test 4: Check authentication
|
||
const user = await testAuthMe();
|
||
|
||
if (!user) {
|
||
console.log('\n⚠️ You are not logged in.');
|
||
console.log(' To test authenticated endpoints:');
|
||
console.log(' 1. Start backend: npm run dev');
|
||
console.log(' 2. Start frontend: cd frontend && npm run dev');
|
||
console.log(' 3. Open http://localhost:5173');
|
||
console.log(' 4. Click "Login with Steam"');
|
||
console.log(' 5. Complete Steam OAuth');
|
||
console.log(' 6. Copy cookies from browser DevTools');
|
||
console.log(' 7. Run this script with cookies (see manual test below)');
|
||
console.log('\n💡 Or use the frontend to test - it should work if cookies are set correctly!');
|
||
} else {
|
||
// Test 5: Sessions (requires auth)
|
||
await testSessions();
|
||
|
||
// Test 6: 2FA Setup (requires auth)
|
||
await test2FASetup();
|
||
}
|
||
|
||
console.log('\n╔════════════════════════════════════════╗');
|
||
console.log('║ Tests Complete ║');
|
||
console.log('╚════════════════════════════════════════╝');
|
||
|
||
if (!user) {
|
||
console.log('\n📝 Manual Test Instructions:');
|
||
console.log(' 1. Login via frontend (http://localhost:5173)');
|
||
console.log(' 2. Open DevTools → Application → Cookies');
|
||
console.log(' 3. Copy accessToken value');
|
||
console.log(' 4. Run:');
|
||
console.log(' curl http://localhost:3000/user/sessions \\');
|
||
console.log(' -H "Cookie: accessToken=YOUR_TOKEN_HERE"');
|
||
console.log('\n If curl works but frontend doesn\'t:');
|
||
console.log(' - Check cookie Domain is "localhost" not "127.0.0.1"');
|
||
console.log(' - Check cookie Secure is false (unchecked)');
|
||
console.log(' - Check cookie SameSite is "Lax"');
|
||
console.log(' - See TROUBLESHOOTING_AUTH.md for detailed guide');
|
||
}
|
||
}
|
||
|
||
// Run the tests
|
||
runTests().catch((error) => {
|
||
console.error('\n💥 Test suite error:', error);
|
||
process.exit(1);
|
||
});
|