Scaffold HIPCTF platform (NestJS + Angular)

- Backend: NestJS 10 + TypeORM (better-sqlite3) feature-modular layout.
  - Entities: user, setting, category, challenge, challenge_file, solve,
    refresh_token, blog_post. Auto-run migrations + idempotent 6-system-
    category seed on startup.
  - Argon2id password hashing with policy check; JWT access + rotating
    refresh tokens (HttpOnly cookie); CSRF middleware (SameSite + custom
    X-CSRF-Token header); global JWT auth guard with @Public() opt-out;
    per-IP login backoff + per-IP registration rate limit.
  - Endpoints: auth (login/refresh/logout/csrf), users (first-admin
    registration), system (bootstrap/event status/SSE), admin (guarded
    user CRUD with last-admin invariant), frontend module (uploads +
    SPA fallback).
  - Security: helmet+CSP+HSTS-gated-by-TLS, CORS allowlist, structured
    global exception filter, Zod request validation pipes, OpenAPI 3.1
    served at /api/docs and /api/docs-json, 10 canonical themes under
    backend/themes/.
- Frontend: Angular 17 standalone components, lazy-loaded feature routes,
  signals, functional HttpInterceptorFn (csrf + auth), functional
  CanActivateFn auth guard, HttpOnly-cookie-based auth service.
- Tests: Jest + supertest, 46 tests across 13 suites covering
  migrations, env schema, theme loader, event status, login backoff,
  registration rate limit, ApiError shape, bootstrap integration,
  auth refresh rotation, admin guard, last-admin invariant, SSE flat
  payloads. Single-command runner: `npm test`.
This commit is contained in:
OpenVelo Agent
2026-07-21 13:25:49 +00:00
parent e55c9cda56
commit af3c24275d
112 changed files with 21931 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"esModuleInterop": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": false,
"resolveJsonModule": true,
"moduleResolution": "node",
"baseUrl": "..",
"paths": {
"*": ["*"]
}
}
}
+102
View File
@@ -0,0 +1,102 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import request from 'supertest';
import { CookieAccessInfo } from 'cookiejar';
import cookieParser from 'cookie-parser';
import { AppModule } from '../../backend/src/app.module';
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
describe('Admin route protection', () => {
let app: INestApplication;
let adminToken: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
const server = app.getHttpServer();
await request(server).post('/api/v1/auth/register-first-admin')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
const login = await request(server).post('/api/v1/auth/login')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
adminToken = login.body.accessToken;
});
afterAll(async () => {
await app.close();
});
it('GET /api/v1/admin/users without a token returns 401', async () => {
await request(app.getHttpServer()).get('/api/v1/admin/users').expect(401);
});
it('GET /api/v1/admin/users with a player JWT returns 403', async () => {
const server = app.getHttpServer();
const agent = request.agent(server);
// Prime CSRF cookie first.
await agent.get('/api/v1/auth/csrf');
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
const csrf = cookies.find((c: any) => c.name === 'csrf');
// Create a player via admin endpoint
await agent.post('/api/v1/admin/users')
.set('Authorization', `Bearer ${adminToken}`)
.set('X-CSRF-Token', csrf.value)
.send({ username: 'player1', password: 'Sup3rSecret!Pass', role: 'player' })
.expect(201);
const playerLogin = await agent.post('/api/v1/auth/login')
.set('X-CSRF-Token', csrf.value)
.send({ username: 'player1', password: 'Sup3rSecret!Pass' })
.expect(201);
const playerToken = playerLogin.body.accessToken;
await request(app.getHttpServer())
.get('/api/v1/admin/users')
.set('Authorization', `Bearer ${playerToken}`)
.expect(403);
});
it('GET /api/v1/admin/users with admin JWT returns 200 and lists users', async () => {
const res = await request(app.getHttpServer())
.get('/api/v1/admin/users')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(Array.isArray(res.body)).toBe(true);
expect(res.body.length).toBeGreaterThanOrEqual(2);
});
it('DELETE /api/v1/admin/users/:id on the only admin returns 409 LAST_ADMIN', async () => {
const list = await request(app.getHttpServer())
.get('/api/v1/admin/users')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
const adminRow = list.body.find((u: any) => u.role === 'admin');
expect(adminRow).toBeDefined();
const server = app.getHttpServer();
const agent = request.agent(server);
await agent.get('/api/v1/auth/csrf');
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
const csrf = cookies.find((c: any) => c.name === 'csrf');
await agent.delete(`/api/v1/admin/users/${adminRow.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.set('X-CSRF-Token', csrf.value)
.expect(409);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { ApiError } from '../../backend/src/common/errors/api-error';
import { ERROR_CODES } from '../../backend/src/common/errors/error-codes';
describe('ApiError', () => {
it('formats validation errors with details', () => {
const e = ApiError.validation('Bad input', { field: 'x' });
expect(e.getStatus()).toBe(400);
const body = e.getResponse() as any;
expect(body.code).toBe(ERROR_CODES.VALIDATION_FAILED);
expect(body.message).toBe('Bad input');
expect(body.details).toEqual({ field: 'x' });
});
it('formats last-admin conflict', () => {
const e = ApiError.conflict(ERROR_CODES.LAST_ADMIN, 'Cannot delete the last admin');
expect(e.getStatus()).toBe(409);
const body = e.getResponse() as any;
expect(body.code).toBe(ERROR_CODES.LAST_ADMIN);
});
it('formats internal error as 500', () => {
const e = ApiError.internal();
expect(e.getStatus()).toBe(500);
});
});
+108
View File
@@ -0,0 +1,108 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import cookieParser from 'cookie-parser';
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';
describe('Auth refresh rotation', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
const server = app.getHttpServer();
await request(server).post('/api/v1/auth/register-first-admin')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
});
afterAll(async () => {
await app.close();
});
it('GET /api/v1/auth/csrf always sets the cookie and returns a non-empty token', async () => {
const server = app.getHttpServer();
const agent = request.agent(server);
const res = await agent.get('/api/v1/auth/csrf').expect(200);
expect(res.body.csrfToken).toBeDefined();
expect(res.body.csrfToken.length).toBeGreaterThan(0);
const cookies = res.headers['set-cookie'] as unknown as string[];
expect(cookies?.some((c) => c.startsWith('csrf='))).toBe(true);
});
it('login returns an access token and sets the rt refresh cookie', async () => {
const server = app.getHttpServer();
const agent = request.agent(server);
const res = await agent.post('/api/v1/auth/login')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
expect(res.body.accessToken).toBeDefined();
const cookies = res.headers['set-cookie'] as unknown as string[];
const rt = cookies.find((c) => c.startsWith('rt='));
expect(rt).toBeDefined();
expect(rt).toMatch(/HttpOnly/);
});
it('refresh rotates the refresh cookie and returns a new access token', async () => {
const server = app.getHttpServer();
const agent = request.agent(server);
await agent.post('/api/v1/auth/login')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
const rt = cookies.find((c: any) => c.name === 'rt');
const csrf = cookies.find((c: any) => c.name === 'csrf');
expect(rt).toBeDefined();
expect(csrf).toBeDefined();
const refresh = await agent.post('/api/v1/auth/refresh')
.set('X-CSRF-Token', csrf.value)
.set('Cookie', `rt=${rt.value}`)
.send({})
.expect(200);
expect(refresh.body.accessToken).toBeDefined();
expect(refresh.body.user.username).toBe('admin');
});
it('logout invalidates the refresh token', async () => {
const server = app.getHttpServer();
const agent = request.agent(server);
await agent.post('/api/v1/auth/login')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
const cookies: any = agent.jar.getCookies(CookieAccessInfo.All);
const rt = cookies.find((c: any) => c.name === 'rt');
const csrf = cookies.find((c: any) => c.name === 'csrf');
await agent.post('/api/v1/auth/logout')
.set('X-CSRF-Token', csrf.value)
.set('Cookie', `rt=${rt.value}`)
.send({})
.expect(204);
// Reusing the same refresh cookie must fail
await agent.post('/api/v1/auth/refresh')
.set('X-CSRF-Token', csrf.value)
.set('Cookie', `rt=${rt.value}`)
.send({})
.expect(401);
});
});
@@ -0,0 +1,71 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { AppModule } from '../../backend/src/app.module';
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
import { csrfClient, primeCsrf } from './csrf-client';
describe('Bootstrap integration', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
});
afterAll(async () => {
await app.close();
});
it('a: bootstrap before any admin', async () => {
const c = csrfClient(app);
const res = await c.get('/api/v1/bootstrap').expect(200);
expect(res.body.initialized).toBe(false);
expect(res.body.theme).toBeDefined();
expect(res.body.theme.tokens.primary).toMatch(/^#/);
});
it('b: event status is Stopped or Running', async () => {
const c = csrfClient(app);
const res = await c.get('/api/v1/event/status').expect(200);
expect(['Stopped', 'Running']).toContain(res.body.status);
expect(typeof res.body.countdownMs).toBe('number');
});
it('c: register-first-admin rejects weak password', async () => {
const c = csrfClient(app);
await c.post('/api/v1/auth/register-first-admin')
.send({ username: 'weak', password: '123' })
.expect(400);
});
it('d: register-first-admin with valid creds creates admin', async () => {
const c = csrfClient(app);
const res = await c.post('/api/v1/auth/register-first-admin')
.send({ username: 'admin', password: 'Sup3rSecret!Pass' })
.expect(201);
expect(res.body.accessToken).toBeDefined();
expect(res.body.user.role).toBe('admin');
});
it('e: bootstrap now reports initialized=true', async () => {
const c = csrfClient(app);
const res = await c.get('/api/v1/bootstrap').expect(200);
expect(res.body.initialized).toBe(true);
});
it('f: register-first-admin now refuses (system initialized)', async () => {
const c = csrfClient(app);
await c.post('/api/v1/auth/register-first-admin')
.send({ username: 'second', password: 'Sup3rSecret!Pass' })
.expect(409);
});
});
+46
View File
@@ -0,0 +1,46 @@
import request from 'supertest';
import type { INestApplication } from '@nestjs/common';
import { CookieAccessInfo } from 'cookiejar';
const csrfSkipPaths = new Set<string>(['/api/v1/auth/login', '/api/v1/auth/register-first-admin']);
function attachCsrfHeader(test: request.Test, method: string, path: string, agent: any): request.Test {
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method.toUpperCase())) return test;
if (csrfSkipPaths.has(path)) return test;
const jar = agent.jar;
if (!jar || typeof jar.getCookies !== 'function') return test;
const cookies: any[] = jar.getCookies(CookieAccessInfo.All);
if (process.env.CSRF_DEBUG) console.log('[csrf-client] all cookies in jar:', cookies.map((c: any) => ({ name: c.name, path: c.path })), 'for path', path);
const csrfCookie = cookies.find((c: any) => c.name === 'csrf');
if (!csrfCookie) return test;
const csrf = decodeURIComponent(csrfCookie.value ?? '');
if (csrf) test.set('X-CSRF-Token', csrf);
return test;
}
export function csrfClient(app: INestApplication): {
get: (path: string) => request.Test;
post: (path: string) => request.Test;
put: (path: string) => request.Test;
patch: (path: string) => request.Test;
delete: (path: string) => request.Test;
} {
const server = app.getHttpServer();
const agent = request.agent(server);
return {
get: (path: string) => agent.get(path),
post: (path: string) => attachCsrfHeader(agent.post(path), 'POST', path, agent),
put: (path: string) => attachCsrfHeader(agent.put(path), 'PUT', path, agent),
patch: (path: string) => attachCsrfHeader(agent.patch(path), 'PATCH', path, agent),
delete: (path: string) => attachCsrfHeader(agent.delete(path), 'DELETE', path, agent),
};
}
export async function primeCsrf(app: INestApplication): Promise<string> {
const server = app.getHttpServer();
const agent = request.agent(server);
const res = await agent.get('/api/v1/auth/csrf');
const cookieHeader = (res.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
const token = cookieHeader ? cookieHeader.split(';')[0].split('=')[1] : '';
return decodeURIComponent(token);
}
+23
View File
@@ -0,0 +1,23 @@
import { envSchema, SYSTEM_CATEGORY_KEYS, SETTINGS_KEYS } from '../../backend/src/config/env.schema';
describe('envSchema', () => {
it('accepts minimal valid env', () => {
const r = envSchema.safeParse({});
expect(r.success).toBe(true);
});
it('rejects invalid PORT', () => {
const r = envSchema.safeParse({ PORT: 'not-a-number' });
expect(r.success).toBe(false);
});
it('rejects short JWT secrets', () => {
const r = envSchema.safeParse({ JWT_ACCESS_SECRET: 'short' });
expect(r.success).toBe(false);
});
it('exposes the canonical system category and settings keys', () => {
expect(SYSTEM_CATEGORY_KEYS).toEqual(['crypto', 'forensics', 'pwn', 'web', 'misc', 'osint']);
expect(SETTINGS_KEYS.THEME_KEY).toBe('themeKey');
});
});
+41
View File
@@ -0,0 +1,41 @@
import { EventStatusService } from '../../backend/src/common/services/event-status.service';
describe('EventStatusService', () => {
const settings = {
get: jest.fn(),
} as any;
beforeEach(() => {
settings.get.mockReset();
});
it('returns Stopped before start with positive countdown', async () => {
const start = new Date(Date.now() + 60_000).toISOString();
const end = new Date(Date.now() + 120_000).toISOString();
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
const svc = new EventStatusService(settings);
const s = await svc.getStatus();
expect(s.status).toBe('Stopped');
expect(s.countdownMs).toBeGreaterThan(0);
});
it('returns Running between start and end', async () => {
const start = new Date(Date.now() - 30_000).toISOString();
const end = new Date(Date.now() + 60_000).toISOString();
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
const svc = new EventStatusService(settings);
const s = await svc.getStatus();
expect(s.status).toBe('Running');
expect(s.countdownMs).toBeGreaterThan(0);
});
it('returns Stopped after end with zero countdown', async () => {
const start = new Date(Date.now() - 120_000).toISOString();
const end = new Date(Date.now() - 60_000).toISOString();
settings.get.mockImplementation(async (k: string) => (k === 'eventStartUtc' ? start : end));
const svc = new EventStatusService(settings);
const s = await svc.getStatus();
expect(s.status).toBe('Stopped');
expect(s.countdownMs).toBe(0);
});
});
@@ -0,0 +1,81 @@
import { UsersService } from '../../backend/src/modules/users/users.service';
import { DataSource } from 'typeorm';
import { UserEntity } from '../../backend/src/database/entities/user.entity';
import { ApiError } from '../../backend/src/common/errors/api-error';
import { ERROR_CODES } from '../../backend/src/common/errors/error-codes';
describe('UsersService.enforceLastAdminInvariant', () => {
let ds: DataSource;
let svc: UsersService;
beforeAll(async () => {
ds = new DataSource({
type: 'better-sqlite3',
database: ':memory:',
entities: [UserEntity],
synchronize: true,
logging: false,
});
await ds.initialize();
svc = new UsersService(ds.getRepository(UserEntity));
});
afterAll(async () => {
await ds.destroy();
});
beforeEach(async () => {
await ds.getRepository(UserEntity).clear();
});
it('throws LAST_ADMIN when demoting the only admin', async () => {
const repo = ds.getRepository(UserEntity);
const admin = repo.create({
id: 'a1', username: 'admin', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString(),
});
await repo.save(admin);
await expect(
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1', 'player')),
).rejects.toMatchObject({
response: { code: ERROR_CODES.LAST_ADMIN },
});
});
it('throws LAST_ADMIN when deleting the only admin', async () => {
const repo = ds.getRepository(UserEntity);
const admin = repo.create({
id: 'a1', username: 'admin', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString(),
});
await repo.save(admin);
await expect(
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1')),
).rejects.toMatchObject({
response: { code: ERROR_CODES.LAST_ADMIN },
});
});
it('does NOT throw when more than one admin exists', async () => {
const repo = ds.getRepository(UserEntity);
await repo.save([
repo.create({ id: 'a1', username: 'a1', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
repo.create({ id: 'a2', username: 'a2', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
]);
await expect(
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'a1', 'player')),
).resolves.toBeUndefined();
});
it('does NOT throw when demoting a non-admin', async () => {
const repo = ds.getRepository(UserEntity);
await repo.save([
repo.create({ id: 'a1', username: 'a1', passwordHash: 'x', role: 'admin', status: 'enabled', createdAt: new Date().toISOString() }),
repo.create({ id: 'p1', username: 'p1', passwordHash: 'x', role: 'player', status: 'enabled', createdAt: new Date().toISOString() }),
]);
await expect(
ds.transaction(async (manager) => svc.enforceLastAdminInvariant(manager, 'p1', 'admin')),
).resolves.toBeUndefined();
});
});
+24
View File
@@ -0,0 +1,24 @@
import { LoginBackoffService } from '../../backend/src/common/services/login-backoff.service';
describe('LoginBackoffService', () => {
it('starts unblocked', () => {
const s = new LoginBackoffService();
expect(s.isBlocked('1.1.1.1', 'alice', 1000)).toBe(0);
});
it('blocks after repeated failures and resets on success', () => {
const s = new LoginBackoffService();
const now = 1000;
for (let i = 0; i < 5; i++) s.recordFailure('1.1.1.1', 'alice', now);
expect(s.isBlocked('1.1.1.1', 'alice', now + 100)).toBeGreaterThan(0);
s.reset('1.1.1.1', 'alice');
expect(s.isBlocked('1.1.1.1', 'alice', now + 100)).toBe(0);
});
it('is per (ip, username)', () => {
const s = new LoginBackoffService();
for (let i = 0; i < 6; i++) s.recordFailure('1.1.1.1', 'alice', 1000 + i);
expect(s.isBlocked('1.1.1.1', 'alice', 1100)).toBeGreaterThan(0);
expect(s.isBlocked('1.1.1.1', 'bob', 1100)).toBe(0);
});
});
+69
View File
@@ -0,0 +1,69 @@
import * as path from 'path';
import { MigrationInterface, QueryRunner } from 'typeorm';
import { InitSchema1700000000000 } from '../../backend/src/database/migrations/1700000000000-InitSchema';
import { SeedSystemData1700000000100 } from '../../backend/src/database/migrations/1700000000100-SeedSystemData';
import { DataSource } from 'typeorm';
import { UserEntity } from '../../backend/src/database/entities/user.entity';
import { SettingEntity } from '../../backend/src/database/entities/setting.entity';
import { CategoryEntity } from '../../backend/src/database/entities/category.entity';
import { ChallengeEntity } from '../../backend/src/database/entities/challenge.entity';
import { ChallengeFileEntity } from '../../backend/src/database/entities/challenge-file.entity';
import { SolveEntity } from '../../backend/src/database/entities/solve.entity';
import { RefreshTokenEntity } from '../../backend/src/database/entities/refresh-token.entity';
import { BlogPostEntity } from '../../backend/src/database/entities/blog-post.entity';
describe('Migrations', () => {
let dataSource: DataSource;
beforeAll(async () => {
dataSource = new DataSource({
type: 'better-sqlite3',
database: ':memory:',
entities: [UserEntity, SettingEntity, CategoryEntity, ChallengeEntity, ChallengeFileEntity, SolveEntity, RefreshTokenEntity, BlogPostEntity],
migrations: [InitSchema1700000000000, SeedSystemData1700000000100],
migrationsRun: true,
synchronize: false,
logging: false,
});
await dataSource.initialize();
});
afterAll(async () => {
await dataSource.destroy();
});
it('creates all required tables', async () => {
const tables = await dataSource.query("SELECT name FROM sqlite_master WHERE type='table'");
const names = tables.map((t: any) => t.name);
expect(names).toEqual(expect.arrayContaining([
'user', 'setting', 'category', 'challenge', 'challenge_file',
'solve', 'refresh_token', 'blog_post',
]));
});
it('seeds 6 system categories with unique system_keys', async () => {
const cats = await dataSource.getRepository(CategoryEntity).find();
const systemCats = cats.filter((c) => c.systemKey);
expect(systemCats.length).toBeGreaterThanOrEqual(6);
const keys = systemCats.map((c) => c.systemKey);
expect(new Set(keys).size).toBe(keys.length);
});
it('seeds default settings', async () => {
const settings = await dataSource.getRepository(SettingEntity).find();
const keys = settings.map((s) => s.key);
expect(keys).toEqual(expect.arrayContaining(['pageTitle', 'themeKey', 'eventStartUtc', 'eventEndUtc']));
});
it('enforces UNIQUE(challengeId, userId) on solve', async () => {
const indexes = await dataSource.query("SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name='solve'");
const uq = indexes.find((i: any) => /UNIQUE.*challenge_id.*user_id/i.test(i.sql || ''));
expect(uq).toBeDefined();
});
it('enforces ON DELETE RESTRICT FK on solve', async () => {
const fks = await dataSource.query("PRAGMA foreign_key_list('solve')");
const restrict = fks.filter((f: any) => f.on_delete === 'RESTRICT');
expect(restrict.length).toBeGreaterThanOrEqual(2);
});
});
@@ -0,0 +1,70 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
import { RegistrationRateLimitService } from '../../backend/src/common/services/registration-rate-limit.service';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import request from 'supertest';
import { AppModule } from '../../backend/src/app.module';
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
describe('RegistrationRateLimitService', () => {
it('allows up to 10 per minute per IP', () => {
const s = new RegistrationRateLimitService();
const now = 1_000_000;
for (let i = 0; i < 10; i++) {
expect(s.isAllowed('1.1.1.1', now + i)).toBe(true);
s.record('1.1.1.1', now + i);
}
expect(s.isAllowed('1.1.1.1', now + 10)).toBe(false);
});
it('isolates per IP', () => {
const s = new RegistrationRateLimitService();
const now = 1_000_000;
for (let i = 0; i < 10; i++) s.record('1.1.1.1', now + i);
expect(s.isAllowed('2.2.2.2', now + 10)).toBe(true);
});
});
describe('register-first-admin registration rate limit (integration)', () => {
let app: INestApplication;
let limiter: RegistrationRateLimitService;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
limiter = app.get(RegistrationRateLimitService);
});
afterAll(async () => {
await app.close();
});
it('returns 429 once the per-IP cap is reached', async () => {
// Prime the limiter for the IP that supertest will use. The default
// Express socket address is IPv6-mapped IPv4 ('::ffff:127.0.0.1') on
// most platforms; priming both forms keeps the test stable.
const now = Date.now();
for (let i = 0; i < 10; i++) {
limiter.record('127.0.0.1', now + i);
limiter.record('::ffff:127.0.0.1', now + i);
}
const server = app.getHttpServer();
const agent = request.agent(server);
await agent.post('/api/v1/auth/csrf');
const cookies: any = agent.jar.getCookies(require('cookiejar').CookieAccessInfo.All);
const csrf = cookies.find((c: any) => c.name === 'csrf');
await agent.post('/api/v1/auth/register-first-admin')
.set('X-CSRF-Token', csrf.value)
.send({ username: 'noone', password: 'Sup3rSecret!Pass' })
.expect(429);
});
});
+62
View File
@@ -0,0 +1,62 @@
process.env.DATABASE_PATH = ':memory:';
process.env.THEMES_DIR = './themes';
process.env.FRONTEND_DIST = './frontend/dist';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import request from 'supertest';
import { AppModule } from '../../backend/src/app.module';
import { GlobalExceptionFilter } from '../../backend/src/common/filters/global-exception.filter';
describe('SSE flattened payloads', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
const httpAdapterHost = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost));
await app.init();
});
afterAll(async () => {
await app.close();
});
it('event/stream emits a flattened { status, countdownMs, serverNowUtc, startUtc, endUtc } payload', (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[] = [];
res.on('data', (chunk: Buffer) => {
chunks.push(chunk);
if (received) return;
const text = Buffer.concat(chunks).toString('utf8');
const match = /data: ({.*?})\n/.exec(text);
if (match) {
try {
const payload = JSON.parse(match[1]);
expect(payload).toHaveProperty('status');
expect(payload).toHaveProperty('countdownMs');
expect(payload).toHaveProperty('serverNowUtc');
expect(payload).toHaveProperty('startUtc');
expect(payload).toHaveProperty('endUtc');
expect(['Stopped', 'Running']).toContain(payload.status);
received = true;
(res as any).destroy();
done();
} catch (e) {
done(e);
}
}
});
res.on('end', () => cb(null, Buffer.concat(chunks)));
res.on('error', (err) => cb(err, null));
})
.end(() => {});
}, 10_000);
});
+42
View File
@@ -0,0 +1,42 @@
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { ThemeLoaderService } from '../../backend/src/common/utils/theme-loader.service';
describe('ThemeLoaderService', () => {
const config = { get: jest.fn() } as any;
it('falls back to default and warns on unknown theme id', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify({ id: 'classic', name: 'Classic', tokens: { primary: '#000', secondary: '#111', accent: '#222', surface: '#fff', text: '#000', success: '#0f0', warning: '#ff0', danger: '#f00', fontFamily: 'sans', radii: { sm: '1px', md: '2px', lg: '3px' }, spacingScale: [4, 8] } }));
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
const svc = new ThemeLoaderService(config);
svc.onModuleInit();
const t = svc.getTheme('does-not-exist');
expect(t.id).toBe('classic');
expect(t.tokens.primary).toBe('#000');
});
it('loads a valid theme by id', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
const theme = { id: 'classic', name: 'Classic', tokens: { primary: '#000', secondary: '#111', accent: '#222', surface: '#fff', text: '#000', success: '#0f0', warning: '#ff0', danger: '#f00', fontFamily: 'sans', radii: { sm: '1px', md: '2px', lg: '3px' }, spacingScale: [4, 8] } };
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify(theme));
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
const svc = new ThemeLoaderService(config);
svc.onModuleInit();
const t = svc.getTheme('classic');
expect(t.id).toBe('classic');
expect(t.tokens.spacingScale).toEqual([4, 8]);
});
it('skips invalid theme files', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
fs.writeFileSync(path.join(tmp, 'classic.json'), JSON.stringify({ id: 'classic', name: 'Classic', tokens: { primary: '#000' } })); // missing required
config.get.mockImplementation((k: string, d: any) => (k === 'THEMES_DIR' ? tmp : d));
const svc = new ThemeLoaderService(config);
svc.onModuleInit();
// Falls back to builtins; classic should be findable via builtins
const t = svc.getTheme('classic');
expect(t).toBeDefined();
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"esModuleInterop": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": false,
"resolveJsonModule": true,
"moduleResolution": "node",
"lib": ["ES2022", "dom"],
"baseUrl": ".."
}
}
+13
View File
@@ -0,0 +1,13 @@
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
+27
View File
@@ -0,0 +1,27 @@
import { ThemeLoaderService, BUILTIN_THEMES } from '../../backend/src/common/utils/theme-loader.service';
describe('ThemeLoaderService builtins', () => {
it('includes all 10 canonical theme ids', () => {
const ids = BUILTIN_THEMES.map((t) => t.id).sort();
expect(ids).toEqual([
'classic', 'crimson', 'cyber', 'forest', 'midnight',
'monochrome', 'neon', 'ocean', 'paper', 'sunset',
]);
});
it('every builtin theme has full tokens', () => {
for (const t of BUILTIN_THEMES) {
expect(t.tokens.primary).toMatch(/^#/);
expect(t.tokens.radii.sm).toBeTruthy();
expect(t.tokens.spacingScale.length).toBeGreaterThan(0);
}
});
it('falls back to default for unknown id', () => {
const config = { get: jest.fn((k: string, d: any) => d) } as any;
const svc = new ThemeLoaderService(config);
svc.onModuleInit();
const t = svc.getTheme('totally-unknown');
expect(t.id).toBe('classic');
});
});
+25
View File
@@ -0,0 +1,25 @@
module.exports = {
projects: [
{
displayName: 'backend',
preset: 'ts-jest',
testEnvironment: 'node',
roots: [__dirname],
testMatch: ['<rootDir>/backend/**/*.spec.ts'],
transform: {
'^.+\\.ts$': ['ts-jest', { tsconfig: '<rootDir>/backend.tsconfig.json' }],
},
},
{
displayName: 'frontend',
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [__dirname],
testMatch: ['<rootDir>/frontend/**/*.spec.ts'],
transform: {
'^.+\\.ts$': ['ts-jest', { tsconfig: '<rootDir>/frontend.tsconfig.json' }],
},
setupFiles: ['<rootDir>/frontend/jest.setup.ts'],
},
],
};