Fix stuff
This commit is contained in:
parent
fc270d437f
commit
32696ad33d
13 changed files with 2194 additions and 110 deletions
|
|
@ -32,6 +32,26 @@ const runMigrations = () => {
|
|||
db.exec("ALTER TABLE users ADD COLUMN default_game_config TEXT");
|
||||
console.log("Migration: Added default_game_config to users");
|
||||
}
|
||||
|
||||
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='game_sessions'").get();
|
||||
if (!tables) {
|
||||
db.exec(`
|
||||
CREATE TABLE game_sessions (
|
||||
pin TEXT PRIMARY KEY,
|
||||
host_peer_id TEXT NOT NULL,
|
||||
host_secret TEXT NOT NULL,
|
||||
quiz_data TEXT NOT NULL,
|
||||
game_config TEXT NOT NULL,
|
||||
game_state TEXT NOT NULL DEFAULT 'LOBBY',
|
||||
current_question_index INTEGER NOT NULL DEFAULT 0,
|
||||
players_data TEXT NOT NULL DEFAULT '[]',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX idx_game_sessions_updated ON game_sessions(updated_at);
|
||||
`);
|
||||
console.log("Migration: Created game_sessions table");
|
||||
}
|
||||
};
|
||||
|
||||
runMigrations();
|
||||
|
|
|
|||
|
|
@ -41,6 +41,20 @@ CREATE TABLE IF NOT EXISTS answer_options (
|
|||
FOREIGN KEY (question_id) REFERENCES questions(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS game_sessions (
|
||||
pin TEXT PRIMARY KEY,
|
||||
host_peer_id TEXT NOT NULL,
|
||||
host_secret TEXT NOT NULL,
|
||||
quiz_data TEXT NOT NULL,
|
||||
game_config TEXT NOT NULL,
|
||||
game_state TEXT NOT NULL DEFAULT 'LOBBY',
|
||||
current_question_index INTEGER NOT NULL DEFAULT 0,
|
||||
players_data TEXT NOT NULL DEFAULT '[]',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_quizzes_user ON quizzes(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_questions_quiz ON questions(quiz_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_options_question ON answer_options(question_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_game_sessions_updated ON game_sessions(updated_at);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { db } from './db/connection.js';
|
|||
import quizzesRouter from './routes/quizzes.js';
|
||||
import usersRouter from './routes/users.js';
|
||||
import uploadRouter from './routes/upload.js';
|
||||
import gamesRouter from './routes/games.js';
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
|
@ -60,6 +61,7 @@ app.get('/health', (_req: Request, res: Response) => {
|
|||
app.use('/api/quizzes', quizzesRouter);
|
||||
app.use('/api/users', usersRouter);
|
||||
app.use('/api/upload', uploadRouter);
|
||||
app.use('/api/games', gamesRouter);
|
||||
|
||||
app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
|
||||
console.error('Unhandled error:', err);
|
||||
|
|
|
|||
205
server/src/routes/games.ts
Normal file
205
server/src/routes/games.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
import { Router, Request, Response } from 'express';
|
||||
import { db } from '../db/connection.js';
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
const router = Router();
|
||||
|
||||
const SESSION_TTL_MINUTES = parseInt(process.env.GAME_SESSION_TTL_MINUTES || '5', 10);
|
||||
|
||||
interface GameSession {
|
||||
pin: string;
|
||||
host_peer_id: string;
|
||||
host_secret: string;
|
||||
quiz_data: string;
|
||||
game_config: string;
|
||||
game_state: string;
|
||||
current_question_index: number;
|
||||
players_data: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const cleanupExpiredSessions = () => {
|
||||
// Use SQLite's datetime function with the same format as CURRENT_TIMESTAMP
|
||||
// to avoid string comparison issues between JS ISO format and SQLite format
|
||||
const result = db.prepare(`
|
||||
DELETE FROM game_sessions
|
||||
WHERE updated_at < datetime('now', '-' || ? || ' minutes')
|
||||
`).run(SESSION_TTL_MINUTES);
|
||||
if (result.changes > 0) {
|
||||
console.log(`Cleaned up ${result.changes} expired game session(s)`);
|
||||
}
|
||||
};
|
||||
|
||||
setInterval(cleanupExpiredSessions, 60 * 1000);
|
||||
|
||||
router.post('/', (req: Request, res: Response) => {
|
||||
try {
|
||||
const { pin, hostPeerId, quiz, gameConfig } = req.body;
|
||||
|
||||
if (!pin || !hostPeerId || !quiz || !gameConfig) {
|
||||
res.status(400).json({ error: 'Missing required fields' });
|
||||
return;
|
||||
}
|
||||
|
||||
const hostSecret = randomBytes(32).toString('hex');
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO game_sessions (pin, host_peer_id, host_secret, quiz_data, game_config, game_state, players_data)
|
||||
VALUES (?, ?, ?, ?, ?, 'LOBBY', '[]')
|
||||
`).run(pin, hostPeerId, hostSecret, JSON.stringify(quiz), JSON.stringify(gameConfig));
|
||||
|
||||
res.status(201).json({ success: true, hostSecret });
|
||||
} catch (err: any) {
|
||||
if (err.code === 'SQLITE_CONSTRAINT_PRIMARYKEY') {
|
||||
res.status(409).json({ error: 'Game PIN already exists' });
|
||||
return;
|
||||
}
|
||||
console.error('Error creating game session:', err);
|
||||
res.status(500).json({ error: 'Failed to create game session' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:pin', (req: Request, res: Response) => {
|
||||
try {
|
||||
const { pin } = req.params;
|
||||
|
||||
cleanupExpiredSessions();
|
||||
|
||||
const session = db.prepare('SELECT * FROM game_sessions WHERE pin = ?').get(pin) as GameSession | undefined;
|
||||
|
||||
if (!session) {
|
||||
res.status(404).json({ error: 'Game not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
pin: session.pin,
|
||||
hostPeerId: session.host_peer_id,
|
||||
gameState: session.game_state,
|
||||
currentQuestionIndex: session.current_question_index,
|
||||
quizTitle: JSON.parse(session.quiz_data).title,
|
||||
playerCount: JSON.parse(session.players_data).length,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error getting game session:', err);
|
||||
res.status(500).json({ error: 'Failed to get game session' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:pin/host', (req: Request, res: Response) => {
|
||||
try {
|
||||
const { pin } = req.params;
|
||||
const hostSecret = req.headers['x-host-secret'] as string;
|
||||
|
||||
if (!hostSecret) {
|
||||
res.status(401).json({ error: 'Host secret required' });
|
||||
return;
|
||||
}
|
||||
|
||||
const session = db.prepare('SELECT * FROM game_sessions WHERE pin = ? AND host_secret = ?').get(pin, hostSecret) as GameSession | undefined;
|
||||
|
||||
if (!session) {
|
||||
res.status(404).json({ error: 'Game not found or invalid secret' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
pin: session.pin,
|
||||
hostPeerId: session.host_peer_id,
|
||||
quiz: JSON.parse(session.quiz_data),
|
||||
gameConfig: JSON.parse(session.game_config),
|
||||
gameState: session.game_state,
|
||||
currentQuestionIndex: session.current_question_index,
|
||||
players: JSON.parse(session.players_data),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error getting host session:', err);
|
||||
res.status(500).json({ error: 'Failed to get game session' });
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:pin', (req: Request, res: Response) => {
|
||||
try {
|
||||
const { pin } = req.params;
|
||||
const hostSecret = req.headers['x-host-secret'] as string;
|
||||
const { hostPeerId, gameState, currentQuestionIndex, players } = req.body;
|
||||
|
||||
if (!hostSecret) {
|
||||
res.status(401).json({ error: 'Host secret required' });
|
||||
return;
|
||||
}
|
||||
|
||||
const session = db.prepare('SELECT pin FROM game_sessions WHERE pin = ? AND host_secret = ?').get(pin, hostSecret);
|
||||
|
||||
if (!session) {
|
||||
res.status(404).json({ error: 'Game not found or invalid secret' });
|
||||
return;
|
||||
}
|
||||
|
||||
const updates: string[] = [];
|
||||
const values: any[] = [];
|
||||
|
||||
if (hostPeerId !== undefined) {
|
||||
updates.push('host_peer_id = ?');
|
||||
values.push(hostPeerId);
|
||||
}
|
||||
if (gameState !== undefined) {
|
||||
updates.push('game_state = ?');
|
||||
values.push(gameState);
|
||||
}
|
||||
if (currentQuestionIndex !== undefined) {
|
||||
updates.push('current_question_index = ?');
|
||||
values.push(currentQuestionIndex);
|
||||
}
|
||||
if (players !== undefined) {
|
||||
updates.push('players_data = ?');
|
||||
values.push(JSON.stringify(players));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
res.status(400).json({ error: 'No updates provided' });
|
||||
return;
|
||||
}
|
||||
|
||||
updates.push('updated_at = CURRENT_TIMESTAMP');
|
||||
values.push(pin, hostSecret);
|
||||
|
||||
db.prepare(`
|
||||
UPDATE game_sessions
|
||||
SET ${updates.join(', ')}
|
||||
WHERE pin = ? AND host_secret = ?
|
||||
`).run(...values);
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Error updating game session:', err);
|
||||
res.status(500).json({ error: 'Failed to update game session' });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:pin', (req: Request, res: Response) => {
|
||||
try {
|
||||
const { pin } = req.params;
|
||||
const hostSecret = req.headers['x-host-secret'] as string;
|
||||
|
||||
if (!hostSecret) {
|
||||
res.status(401).json({ error: 'Host secret required' });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = db.prepare('DELETE FROM game_sessions WHERE pin = ? AND host_secret = ?').run(pin, hostSecret);
|
||||
|
||||
if (result.changes === 0) {
|
||||
res.status(404).json({ error: 'Game not found or invalid secret' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Error deleting game session:', err);
|
||||
res.status(500).json({ error: 'Failed to delete game session' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue