feat: Admin Area General Settings and Categories 1.10
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
import { AdminGeneralService } from '../../backend/src/modules/admin/general.service';
|
||||
|
||||
function makeFakeThemeLoader() {
|
||||
return [
|
||||
{ id: 'classic', name: 'Classic', tokens: {} as any },
|
||||
{ id: 'midnight', name: 'Midnight', tokens: {} as any },
|
||||
];
|
||||
}
|
||||
|
||||
function makeService() {
|
||||
const stored: Record<string, string> = {};
|
||||
const fakeSettings = {
|
||||
get: jest.fn().mockImplementation(async (k: string, d: string) => (k in stored ? stored[k] : d)),
|
||||
set: jest.fn().mockImplementation(async (k: string, v: string) => { stored[k] = v; }),
|
||||
} as any;
|
||||
const fakeHub = { emitEvent: jest.fn() } as any;
|
||||
const fakeThemes: any = { listThemes: () => makeFakeThemeLoader() };
|
||||
const fakeConfig: any = { get: jest.fn().mockReturnValue('./themes') };
|
||||
const svc = new AdminGeneralService(fakeSettings, fakeThemes, fakeHub, fakeConfig);
|
||||
return { svc, fakeHub, fakeSettings };
|
||||
}
|
||||
|
||||
describe('AdminGeneralService.updateSettings - general SSE payload (Job 892)', () => {
|
||||
it('emits a general hub event carrying both themeKey and registrationsEnabled when registrations are enabled', async () => {
|
||||
const { svc, fakeHub } = makeService();
|
||||
await svc.updateSettings({
|
||||
pageTitle: 'Hello',
|
||||
logo: '',
|
||||
welcomeMarkdown: '',
|
||||
themeKey: 'midnight',
|
||||
eventStartUtc: '2026-01-01T00:00:00Z',
|
||||
eventEndUtc: '2026-02-01T00:00:00Z',
|
||||
defaultChallengeIp: '127.0.0.1',
|
||||
registrationsEnabled: true,
|
||||
});
|
||||
expect(fakeHub.emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
topic: 'general',
|
||||
themeKey: 'midnight',
|
||||
registrationsEnabled: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('emits a general hub event with registrationsEnabled=false when the admin disables registrations', async () => {
|
||||
const { svc, fakeHub } = makeService();
|
||||
await svc.updateSettings({
|
||||
pageTitle: 'Hello',
|
||||
logo: '',
|
||||
welcomeMarkdown: '',
|
||||
themeKey: 'classic',
|
||||
eventStartUtc: '2026-01-01T00:00:00Z',
|
||||
eventEndUtc: '2026-02-01T00:00:00Z',
|
||||
defaultChallengeIp: '127.0.0.1',
|
||||
registrationsEnabled: false,
|
||||
});
|
||||
expect(fakeHub.emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
topic: 'general',
|
||||
themeKey: 'classic',
|
||||
registrationsEnabled: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
process.env.DATABASE_PATH = ':memory:';
|
||||
process.env.THEMES_DIR = './themes';
|
||||
process.env.FRONTEND_DIST = './frontend/dist';
|
||||
process.env.NODE_ENV = '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 { 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 { SseHubService } from '../../backend/src/common/services/sse-hub.service';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { initDb } from './db-helper';
|
||||
|
||||
describe('GET /api/v1/event/stream forwards general topic (Job 892)', () => {
|
||||
let app: INestApplication;
|
||||
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);
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/auth/register-first-admin')
|
||||
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
|
||||
.expect(201);
|
||||
hub = app.get(SseHubService);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('emits a { topic: "general", themeKey, registrationsEnabled } frame through the public stream', (done) => {
|
||||
const server = app.getHttpServer();
|
||||
const req = request(server).get('/api/v1/event/stream');
|
||||
let received = false;
|
||||
req
|
||||
.buffer(true)
|
||||
.parse((res, cb) => {
|
||||
const chunks: Buffer[] = [];
|
||||
const finalize = () => cb(null, Buffer.concat(chunks));
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
if (received) return;
|
||||
const text = Buffer.concat(chunks).toString('utf8');
|
||||
const match = /data: (\{[^{]*?"topic":\s*"general"[^{]*\})\n/.exec(text);
|
||||
if (!match) return;
|
||||
try {
|
||||
const payload = JSON.parse(match[1]);
|
||||
expect(payload.topic).toBe('general');
|
||||
expect(payload).toHaveProperty('themeKey');
|
||||
expect(payload).toHaveProperty('registrationsEnabled');
|
||||
received = true;
|
||||
(res as any).destroy();
|
||||
done();
|
||||
} catch (e) {
|
||||
(res as any).destroy();
|
||||
done(e);
|
||||
}
|
||||
});
|
||||
res.on('end', finalize);
|
||||
res.on('error', (err) => cb(err, null));
|
||||
})
|
||||
.end(() => {});
|
||||
|
||||
// Push the hub event shortly after the consumer attaches.
|
||||
setTimeout(() => {
|
||||
hub.emitEvent({ topic: 'general', themeKey: 'midnight', registrationsEnabled: true });
|
||||
}, 150);
|
||||
|
||||
setTimeout(() => {
|
||||
if (!received) {
|
||||
done(new Error('Did not receive a general frame within 5s'));
|
||||
}
|
||||
}, 5000);
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
const webStreams = require('node:stream/web');
|
||||
const util = require('node:util');
|
||||
|
||||
if (typeof (globalThis as any).ReadableStream === 'undefined') {
|
||||
(globalThis as any).ReadableStream = webStreams.ReadableStream;
|
||||
}
|
||||
if (typeof (globalThis as any).TextEncoder === 'undefined') {
|
||||
(globalThis as any).TextEncoder = util.TextEncoder;
|
||||
}
|
||||
if (typeof (globalThis as any).TextDecoder === 'undefined') {
|
||||
(globalThis as any).TextDecoder = util.TextDecoder;
|
||||
}
|
||||
|
||||
import {
|
||||
isBootstrapGeneralFrame,
|
||||
makeBootstrapEventSource as defaultCreateSource,
|
||||
} from '../../frontend/src/app/core/services/bootstrap-event.pure';
|
||||
|
||||
function makeCaptureableFetch(frames: string[]): { fetchMock: jest.Mock; readCaptured(): { url: string } | null } {
|
||||
const encoder = new TextEncoder();
|
||||
const state: { captured: { url: string } | null } = { captured: null };
|
||||
const fetchMock = jest.fn(async (url: string) => {
|
||||
state.captured = { url };
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
for (const f of frames) controller.enqueue(encoder.encode(f));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
return { ok: true, status: 200, body } as unknown as Response;
|
||||
});
|
||||
return { fetchMock, readCaptured: () => state.captured };
|
||||
}
|
||||
|
||||
describe('isBootstrapGeneralFrame', () => {
|
||||
it('accepts a frame with topic === "general"', () => {
|
||||
expect(isBootstrapGeneralFrame({ topic: 'general', registrationsEnabled: true })).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects frames that do not carry topic === "general"', () => {
|
||||
expect(isBootstrapGeneralFrame({ topic: 'scoreboard' })).toBe(false);
|
||||
expect(isBootstrapGeneralFrame({ registrationsEnabled: true })).toBe(false);
|
||||
expect(isBootstrapGeneralFrame({ status: 'running' })).toBe(false);
|
||||
expect(isBootstrapGeneralFrame(null)).toBe(false);
|
||||
expect(isBootstrapGeneralFrame(undefined)).toBe(false);
|
||||
expect(isBootstrapGeneralFrame('general')).toBe(false);
|
||||
expect(isBootstrapGeneralFrame(42)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultCreateSource (public SSE opener)', () => {
|
||||
let originalFetch: typeof globalThis.fetch | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
originalFetch = (globalThis as any).fetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(globalThis as any).fetch = originalFetch;
|
||||
});
|
||||
|
||||
it('opens /api/v1/event/stream with credentials and Accept text/event-stream', async () => {
|
||||
const f = makeCaptureableFetch([]);
|
||||
(globalThis as any).fetch = f.fetchMock as any;
|
||||
const src = defaultCreateSource('/api/v1/event/stream');
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const captured = f.readCaptured();
|
||||
expect(captured).not.toBeNull();
|
||||
expect(captured!.url).toBe('/api/v1/event/stream');
|
||||
src.close();
|
||||
});
|
||||
|
||||
it('dispatches SSE message frames to message listeners', async () => {
|
||||
const frame =
|
||||
'data: {"status":"Running","countdownMs":1,"serverNowUtc":"2026-07-22T00:00:00.000Z","startUtc":null,"endUtc":null}\n\n';
|
||||
const f = makeCaptureableFetch([frame]);
|
||||
(globalThis as any).fetch = f.fetchMock as any;
|
||||
const src = defaultCreateSource('/api/v1/event/stream');
|
||||
const received: any[] = [];
|
||||
src.addEventListener('message', (ev) => {
|
||||
const me = ev as MessageEvent;
|
||||
received.push(typeof me.data === 'string' ? JSON.parse(me.data) : me.data);
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(received.length).toBeGreaterThanOrEqual(1);
|
||||
expect(received[0].status).toBe('Running');
|
||||
src.close();
|
||||
});
|
||||
|
||||
it('buffers early frames and flushes them when a message listener attaches', async () => {
|
||||
const frame =
|
||||
'data: {"topic":"general","themeKey":"classic","registrationsEnabled":true}\n\n';
|
||||
const f = makeCaptureableFetch([frame]);
|
||||
(globalThis as any).fetch = f.fetchMock as any;
|
||||
const src = defaultCreateSource('/api/v1/event/stream');
|
||||
// Wait for the underlying reader to drain before adding the listener
|
||||
// so we exercise the buffering path.
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
const received: any[] = [];
|
||||
src.addEventListener('message', (ev) => {
|
||||
const me = ev as MessageEvent;
|
||||
received.push(typeof me.data === 'string' ? JSON.parse(me.data) : me.data);
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(received.length).toBeGreaterThanOrEqual(1);
|
||||
expect(received.some((r) => r && r.topic === 'general')).toBe(true);
|
||||
src.close();
|
||||
});
|
||||
|
||||
it('forwards error events when the underlying fetch reports failure', async () => {
|
||||
const fetchMock = jest.fn(async () => ({ ok: false, status: 500, body: null } as unknown as Response));
|
||||
(globalThis as any).fetch = fetchMock as any;
|
||||
const src = defaultCreateSource('/api/v1/event/stream');
|
||||
const errors: string[] = [];
|
||||
src.addEventListener('error', (ev) => errors.push((ev as Event).type));
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
expect(errors).toContain('error');
|
||||
src.close();
|
||||
});
|
||||
|
||||
it('close() is idempotent and safe to call twice', async () => {
|
||||
const f = makeCaptureableFetch([]);
|
||||
(globalThis as any).fetch = f.fetchMock as any;
|
||||
const src = defaultCreateSource('/api/v1/event/stream');
|
||||
src.close();
|
||||
expect(() => src.close()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,7 @@
|
||||
import { buildLoginFailureMessage } from '../../frontend/src/app/features/landing/login-modal.service';
|
||||
import {
|
||||
buildLoginFailureMessage,
|
||||
landingModalShowsRegister,
|
||||
} from '../../frontend/src/app/features/landing/login-modal.service';
|
||||
|
||||
describe('buildLoginFailureMessage', () => {
|
||||
it.each([
|
||||
@@ -50,4 +53,16 @@ describe('buildLoginFailureMessage', () => {
|
||||
expect(buildLoginFailureMessage({ code: 'EXOTIC', message: 'Quux' }).text).toBe('Quux');
|
||||
expect(buildLoginFailureMessage({ code: 'EXOTIC', message: '' }).text).toBe('Something went wrong. Please try again.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('landingModalShowsRegister', () => {
|
||||
it('returns true only when registrationsEnabled is exactly true', () => {
|
||||
expect(landingModalShowsRegister(true)).toBe(true);
|
||||
expect(landingModalShowsRegister(false)).toBe(false);
|
||||
expect(landingModalShowsRegister(null)).toBe(false);
|
||||
expect(landingModalShowsRegister(undefined)).toBe(false);
|
||||
expect(landingModalShowsRegister('true')).toBe(false);
|
||||
expect(landingModalShowsRegister(1)).toBe(false);
|
||||
expect(landingModalShowsRegister({})).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user