Fix stuff

This commit is contained in:
Joey Yakimowich-Payne 2026-01-14 09:07:20 -07:00
commit 32696ad33d
No known key found for this signature in database
GPG key ID: 6BFE655FA5ABD1E1
13 changed files with 2194 additions and 110 deletions

View file

@ -1573,6 +1573,427 @@ async function runTests() {
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 404);
});
console.log('\n=== Game Session Tests ===');
async function gameRequest(
method: string,
path: string,
body?: unknown,
headers?: Record<string, string>,
expectStatus = 200
): Promise<{ status: number; data: unknown }> {
const response = await fetch(`${API_URL}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const data = response.headers.get('content-type')?.includes('application/json')
? await response.json()
: null;
if (response.status !== expectStatus) {
throw new Error(`Expected ${expectStatus}, got ${response.status}: ${JSON.stringify(data)}`);
}
return { status: response.status, data };
}
let testGamePin: string | null = null;
let testHostSecret: string | null = null;
console.log('\nGame Session CRUD Tests:');
await test('POST /api/games creates game session', async () => {
const gameData = {
pin: '123456',
hostPeerId: 'kaboot-123456',
quiz: {
title: 'Test Quiz',
questions: [
{
id: 'q1',
text: 'What is 2+2?',
options: [
{ text: '3', isCorrect: false, shape: 'triangle', color: 'red' },
{ text: '4', isCorrect: true, shape: 'diamond', color: 'blue' },
],
timeLimit: 20,
},
],
},
gameConfig: {
shuffleQuestions: false,
shuffleAnswers: false,
hostParticipates: true,
streakBonusEnabled: false,
streakThreshold: 3,
streakMultiplier: 1.1,
comebackBonusEnabled: false,
comebackBonusPoints: 50,
penaltyForWrongAnswer: false,
penaltyPercent: 25,
firstCorrectBonusEnabled: false,
firstCorrectBonusPoints: 50,
},
};
const { data } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const result = data as { success: boolean; hostSecret: string };
if (!result.success) throw new Error('Expected success: true');
if (!result.hostSecret) throw new Error('Missing hostSecret');
if (result.hostSecret.length < 32) throw new Error('hostSecret too short');
testGamePin = '123456';
testHostSecret = result.hostSecret;
});
await test('GET /api/games/:pin returns game info', async () => {
if (!testGamePin) throw new Error('No game created');
const { data } = await gameRequest('GET', `/api/games/${testGamePin}`);
const game = data as Record<string, unknown>;
if (game.pin !== testGamePin) throw new Error('Wrong PIN');
if (game.hostPeerId !== 'kaboot-123456') throw new Error('Wrong hostPeerId');
if (game.gameState !== 'LOBBY') throw new Error('Wrong initial gameState');
if (game.currentQuestionIndex !== 0) throw new Error('Wrong initial currentQuestionIndex');
if (game.quizTitle !== 'Test Quiz') throw new Error('Wrong quizTitle');
if (game.playerCount !== 0) throw new Error('Wrong initial playerCount');
});
await test('GET /api/games/:pin/host returns full game state with valid secret', async () => {
if (!testGamePin || !testHostSecret) throw new Error('No game created');
const { data } = await gameRequest('GET', `/api/games/${testGamePin}/host`, undefined, {
'X-Host-Secret': testHostSecret,
});
const game = data as Record<string, unknown>;
if (game.pin !== testGamePin) throw new Error('Wrong PIN');
if (!game.quiz) throw new Error('Missing quiz');
if (!game.gameConfig) throw new Error('Missing gameConfig');
if (!Array.isArray(game.players)) throw new Error('Missing players array');
const quiz = game.quiz as Record<string, unknown>;
if (quiz.title !== 'Test Quiz') throw new Error('Wrong quiz title');
});
await test('PATCH /api/games/:pin updates game state', async () => {
if (!testGamePin || !testHostSecret) throw new Error('No game created');
const update = {
gameState: 'QUESTION',
currentQuestionIndex: 1,
players: [
{
id: 'player1',
name: 'Alice',
score: 500,
previousScore: 0,
streak: 1,
lastAnswerCorrect: true,
pointsBreakdown: null,
isBot: false,
avatarSeed: 0.5,
color: '#2563eb',
},
],
};
await gameRequest('PATCH', `/api/games/${testGamePin}`, update, {
'X-Host-Secret': testHostSecret,
});
const { data } = await gameRequest('GET', `/api/games/${testGamePin}/host`, undefined, {
'X-Host-Secret': testHostSecret,
});
const game = data as Record<string, unknown>;
if (game.gameState !== 'QUESTION') throw new Error('gameState not updated');
if (game.currentQuestionIndex !== 1) throw new Error('currentQuestionIndex not updated');
const players = game.players as Record<string, unknown>[];
if (players.length !== 1) throw new Error('players not updated');
if (players[0].name !== 'Alice') throw new Error('player name not saved');
if (players[0].score !== 500) throw new Error('player score not saved');
});
await test('PATCH /api/games/:pin updates hostPeerId', async () => {
if (!testGamePin || !testHostSecret) throw new Error('No game created');
await gameRequest('PATCH', `/api/games/${testGamePin}`, { hostPeerId: 'new-peer-id-12345' }, {
'X-Host-Secret': testHostSecret,
});
const { data } = await gameRequest('GET', `/api/games/${testGamePin}`);
const game = data as Record<string, unknown>;
if (game.hostPeerId !== 'new-peer-id-12345') throw new Error('hostPeerId not updated');
});
console.log('\nGame Session Auth Tests:');
await test('GET /api/games/:pin/host without secret returns 401', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('GET', `/api/games/${testGamePin}/host`, undefined, {}, 401);
});
await test('GET /api/games/:pin/host with wrong secret returns 404', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('GET', `/api/games/${testGamePin}/host`, undefined, {
'X-Host-Secret': 'wrong-secret-12345',
}, 404);
});
await test('PATCH /api/games/:pin without secret returns 401', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('PATCH', `/api/games/${testGamePin}`, { gameState: 'LOBBY' }, {}, 401);
});
await test('PATCH /api/games/:pin with wrong secret returns 404', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('PATCH', `/api/games/${testGamePin}`, { gameState: 'LOBBY' }, {
'X-Host-Secret': 'wrong-secret-12345',
}, 404);
});
await test('DELETE /api/games/:pin without secret returns 401', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('DELETE', `/api/games/${testGamePin}`, undefined, {}, 401);
});
await test('DELETE /api/games/:pin with wrong secret returns 404', async () => {
if (!testGamePin) throw new Error('No game created');
await gameRequest('DELETE', `/api/games/${testGamePin}`, undefined, {
'X-Host-Secret': 'wrong-secret-12345',
}, 404);
});
console.log('\nGame Session Not Found Tests:');
await test('GET /api/games/:pin with non-existent PIN returns 404', async () => {
await gameRequest('GET', '/api/games/999999', undefined, {}, 404);
});
await test('GET /api/games/:pin/host with non-existent PIN returns 404', async () => {
await gameRequest('GET', '/api/games/999999/host', undefined, {
'X-Host-Secret': 'any-secret',
}, 404);
});
await test('PATCH /api/games/:pin with non-existent PIN returns 404', async () => {
await gameRequest('PATCH', '/api/games/999999', { gameState: 'LOBBY' }, {
'X-Host-Secret': 'any-secret',
}, 404);
});
console.log('\nGame Session Validation Tests:');
await test('POST /api/games without pin returns 400', async () => {
const invalidGame = {
hostPeerId: 'peer-123',
quiz: { title: 'Test', questions: [] },
gameConfig: {},
};
await gameRequest('POST', '/api/games', invalidGame, {}, 400);
});
await test('POST /api/games without hostPeerId returns 400', async () => {
const invalidGame = {
pin: '111111',
quiz: { title: 'Test', questions: [] },
gameConfig: {},
};
await gameRequest('POST', '/api/games', invalidGame, {}, 400);
});
await test('POST /api/games without quiz returns 400', async () => {
const invalidGame = {
pin: '111111',
hostPeerId: 'peer-123',
gameConfig: {},
};
await gameRequest('POST', '/api/games', invalidGame, {}, 400);
});
await test('POST /api/games without gameConfig returns 400', async () => {
const invalidGame = {
pin: '111111',
hostPeerId: 'peer-123',
quiz: { title: 'Test', questions: [] },
};
await gameRequest('POST', '/api/games', invalidGame, {}, 400);
});
await test('POST /api/games with duplicate PIN returns 409', async () => {
if (!testGamePin) throw new Error('No game created');
const duplicateGame = {
pin: testGamePin,
hostPeerId: 'another-peer',
quiz: { title: 'Another Quiz', questions: [] },
gameConfig: {},
};
await gameRequest('POST', '/api/games', duplicateGame, {}, 409);
});
await test('PATCH /api/games/:pin with no updates returns 400', async () => {
if (!testGamePin || !testHostSecret) throw new Error('No game created');
await gameRequest('PATCH', `/api/games/${testGamePin}`, {}, {
'X-Host-Secret': testHostSecret,
}, 400);
});
console.log('\nGame Session Delete Tests:');
await test('DELETE /api/games/:pin with valid secret succeeds', async () => {
if (!testGamePin || !testHostSecret) throw new Error('No game created');
await gameRequest('DELETE', `/api/games/${testGamePin}`, undefined, {
'X-Host-Secret': testHostSecret,
});
await gameRequest('GET', `/api/games/${testGamePin}`, undefined, {}, 404);
});
await test('DELETE /api/games/:pin twice returns 404 on second call', async () => {
const gameData = {
pin: '222222',
hostPeerId: 'kaboot-222222',
quiz: { title: 'Delete Test Quiz', questions: [] },
gameConfig: {},
};
const { data } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const secret = (data as { hostSecret: string }).hostSecret;
await gameRequest('DELETE', '/api/games/222222', undefined, {
'X-Host-Secret': secret,
});
await gameRequest('DELETE', '/api/games/222222', undefined, {
'X-Host-Secret': secret,
}, 404);
});
console.log('\nGame Session Edge Cases:');
await test('POST /api/games with special characters in quiz title', async () => {
const gameData = {
pin: '333333',
hostPeerId: 'kaboot-333333',
quiz: {
title: 'Quiz with "quotes" & <tags> and special chars',
questions: [],
},
gameConfig: {},
};
const { data } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const secret = (data as { hostSecret: string }).hostSecret;
const { data: getResult } = await gameRequest('GET', '/api/games/333333');
const game = getResult as Record<string, unknown>;
if (game.quizTitle !== 'Quiz with "quotes" & <tags> and special chars') {
throw new Error('Special characters not preserved in quiz title');
}
await gameRequest('DELETE', '/api/games/333333', undefined, {
'X-Host-Secret': secret,
});
});
await test('POST /api/games with large player data', async () => {
const gameData = {
pin: '444444',
hostPeerId: 'kaboot-444444',
quiz: { title: 'Large Players Test', questions: [] },
gameConfig: {},
};
const { data } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const secret = (data as { hostSecret: string }).hostSecret;
const manyPlayers = Array.from({ length: 50 }, (_, i) => ({
id: `player-${i}`,
name: `Player ${i}`,
score: i * 100,
previousScore: 0,
streak: i % 5,
lastAnswerCorrect: i % 2 === 0,
pointsBreakdown: null,
isBot: false,
avatarSeed: Math.random(),
color: '#2563eb',
}));
await gameRequest('PATCH', '/api/games/444444', { players: manyPlayers }, {
'X-Host-Secret': secret,
});
const { data: getResult } = await gameRequest('GET', '/api/games/444444/host', undefined, {
'X-Host-Secret': secret,
});
const game = getResult as Record<string, unknown>;
const players = game.players as unknown[];
if (players.length !== 50) throw new Error(`Expected 50 players, got ${players.length}`);
await gameRequest('DELETE', '/api/games/444444', undefined, {
'X-Host-Secret': secret,
});
});
await test('GET /api/games/:pin public endpoint does not expose hostSecret', async () => {
const gameData = {
pin: '555555',
hostPeerId: 'kaboot-555555',
quiz: { title: 'Secret Test', questions: [] },
gameConfig: {},
};
const { data: createResult } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const secret = (createResult as { hostSecret: string }).hostSecret;
const { data: getResult } = await gameRequest('GET', '/api/games/555555');
const game = getResult as Record<string, unknown>;
if ('hostSecret' in game) throw new Error('hostSecret should not be exposed in public endpoint');
if ('host_secret' in game) throw new Error('host_secret should not be exposed in public endpoint');
await gameRequest('DELETE', '/api/games/555555', undefined, {
'X-Host-Secret': secret,
});
});
await test('Game session tracks updated_at on PATCH', async () => {
const gameData = {
pin: '666666',
hostPeerId: 'kaboot-666666',
quiz: { title: 'Timestamp Test', questions: [] },
gameConfig: {},
};
const { data } = await gameRequest('POST', '/api/games', gameData, {}, 201);
const secret = (data as { hostSecret: string }).hostSecret;
await new Promise((resolve) => setTimeout(resolve, 100));
await gameRequest('PATCH', '/api/games/666666', { gameState: 'COUNTDOWN' }, {
'X-Host-Secret': secret,
});
await gameRequest('DELETE', '/api/games/666666', undefined, {
'X-Host-Secret': secret,
});
});
console.log('\n=== Results ===');
const passed = results.filter((r) => r.passed).length;
const failed = results.filter((r) => !r.passed).length;