feat: Challenges Page and Challenge Solve Modal
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.UPLOAD_DIR = '/tmp/hipctf-challenges-events-sse-test';
|
||||
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import * as express from 'express';
|
||||
import request from 'supertest';
|
||||
import { CookieAccessInfo } from 'cookiejar';
|
||||
import { AppModule } from '../../backend/src/app.module';
|
||||
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
|
||||
import { CsrfMiddleware } from '../../backend/src/common/middleware/csrf.middleware';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { initDb } from './db-helper';
|
||||
import { SseHubService } from '../../backend/src/common/services/sse-hub.service';
|
||||
|
||||
describe('GET /api/v1/events (authenticated SSE)', () => {
|
||||
let app: INestApplication;
|
||||
let adminToken: string;
|
||||
let hub: SseHubService;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
const csrfMw = new CsrfMiddleware(app.get(ConfigService));
|
||||
app.use((req: any, res: any, next: any) => csrfMw.use(req, res, next));
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
|
||||
const httpAdapterHost = app.get(HttpAdapterHost);
|
||||
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
|
||||
await app.init();
|
||||
await initDb(app);
|
||||
hub = app.get(SseHubService);
|
||||
|
||||
const server = app.getHttpServer();
|
||||
await request(server).post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
const csrfPrime = await request(server).get('/api/v1/auth/csrf');
|
||||
const csrfCookie = (csrfPrime.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
|
||||
const csrf = csrfCookie ? decodeURIComponent(csrfCookie.split(';')[0].split('=')[1]) : '';
|
||||
const login = await request(server).post('/api/v1/auth/login')
|
||||
.set('Cookie', `csrf=${csrf}`)
|
||||
.set('X-CSRF-Token', csrf)
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
adminToken = login.body.accessToken;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('rejects unauthenticated SSE with 401', async () => {
|
||||
await request(app.getHttpServer()).get('/api/v1/events').expect(401);
|
||||
});
|
||||
|
||||
it('emits a status frame with state + timestamps and a solve frame when the hub emits one', (done) => {
|
||||
const server = app.getHttpServer();
|
||||
const req = request(server)
|
||||
.get('/api/v1/events')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.set('Accept', 'text/event-stream');
|
||||
let gotStatus = false;
|
||||
let gotSolve = false;
|
||||
req
|
||||
.buffer(true)
|
||||
.parse((res, cb) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
if (!gotStatus) {
|
||||
// Status frame: `event: status\ndata: {...}\n\n` with snake_case keys.
|
||||
const m = text.match(/(?:event: status\n)?data: (\{[^\n]*\})\n/);
|
||||
if (m) {
|
||||
try {
|
||||
const payload = JSON.parse(m[1]);
|
||||
expect(payload).toHaveProperty('state');
|
||||
expect(payload).toHaveProperty('server_time_utc');
|
||||
expect(payload).toHaveProperty('event_start_utc');
|
||||
expect(payload).toHaveProperty('event_end_utc');
|
||||
expect(payload).toHaveProperty('seconds_to_start');
|
||||
expect(payload).toHaveProperty('seconds_to_end');
|
||||
gotStatus = true;
|
||||
} catch (e) {
|
||||
(res as any).destroy();
|
||||
done(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gotStatus && !gotSolve) {
|
||||
hub.emitScoreboard({
|
||||
topic: 'solve',
|
||||
challengeId: 'c1',
|
||||
playerId: 'p1',
|
||||
playerName: 'player1',
|
||||
awardedPoints: 50,
|
||||
rankBonus: 0,
|
||||
pointsAwarded: 50,
|
||||
solvedAt: new Date().toISOString(),
|
||||
awardedAtUtc: new Date().toISOString(),
|
||||
position: 1,
|
||||
livePoints: 50,
|
||||
solveCount: 1,
|
||||
initialPoints: 100,
|
||||
minimumPoints: 50,
|
||||
decaySolves: 5,
|
||||
});
|
||||
const m2 = text.match(/(?:event: solve\n)?data: (\{[^\n]*\})\n/g);
|
||||
if (m2) {
|
||||
for (const line of m2) {
|
||||
try {
|
||||
const payload = JSON.parse(line.replace(/^data: /, '').trim());
|
||||
if (payload.challenge_id === 'c1') {
|
||||
expect(payload.player_id).toBe('p1');
|
||||
expect(payload.player_name).toBe('player1');
|
||||
expect(payload.awarded_points).toBe(50);
|
||||
expect(payload.rank_bonus).toBe(0);
|
||||
expect(payload.awarded_at_utc).toBeTruthy();
|
||||
expect(payload.position).toBe(1);
|
||||
expect(payload.live_points).toBe(50);
|
||||
expect(payload.solve_count).toBe(1);
|
||||
expect(payload.initial_points).toBe(100);
|
||||
expect(payload.minimum_points).toBe(50);
|
||||
expect(payload.decay_solves).toBe(5);
|
||||
gotSolve = true;
|
||||
(res as any).destroy();
|
||||
done();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
res.on('end', () => cb(null, Buffer.concat(chunks)));
|
||||
res.on('error', (err) => cb(err, null));
|
||||
});
|
||||
req.on('response', (res) => {
|
||||
if (res.statusCode !== 200) {
|
||||
done(new Error(`Unexpected status ${res.statusCode}`));
|
||||
}
|
||||
});
|
||||
req.on('error', (err) => done(err));
|
||||
req.end(() => {});
|
||||
}, 30_000);
|
||||
});
|
||||
Reference in New Issue
Block a user