AI Implementation feature(820): Project Scaffold and Platform Foundations (#1)

This commit was merged in pull request #1.
This commit is contained in:
2026-07-21 14:23:53 +00:00
parent e55c9cda56
commit 03bcb6b156
131 changed files with 23657 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
+49
View File
@@ -0,0 +1,49 @@
{
"name": "backend",
"version": "0.1.0",
"private": true,
"description": "HIPCTF NestJS backend",
"main": "dist/main.js",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"start": "node dist/main.js",
"start:dev": "ts-node -r tsconfig-paths/register src/main.ts"
},
"dependencies": {
"@nestjs/common": "^10.3.10",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.3.10",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.10",
"@nestjs/swagger": "^7.4.0",
"@nestjs/typeorm": "^10.0.2",
"argon2": "^0.40.1",
"better-sqlite3": "^11.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"cookie-parser": "^1.4.6",
"helmet": "^7.1.0",
"multer": "^2.0.2",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20",
"uuid": "^9.0.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@nestjs/testing": "^10.4.22",
"@types/better-sqlite3": "^7.6.10",
"@types/cookie-parser": "^1.4.7",
"@types/express": "^4.17.21",
"@types/multer": "^1.4.12",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.2",
"@types/uuid": "^9.0.8",
"supertest": "^7.0.0",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0"
}
}
+39
View File
@@ -0,0 +1,39 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_GUARD, APP_FILTER } from '@nestjs/core';
import { validateEnv } from './config/env.schema';
import { DatabaseModule } from './database/database.module';
import { CommonModule } from './common/common.module';
import { AuthModule } from './modules/auth/auth.module';
import { UsersModule } from './modules/users/users.module';
import { SystemModule } from './modules/system/system.module';
import { SettingsModule } from './modules/settings/settings.module';
import { AdminModule } from './modules/admin/admin.module';
import { UploadsModule } from './modules/uploads/uploads.module';
import { FrontendModule } from './frontend/frontend.module';
import { GlobalExceptionFilter } from './common/filters/global-exception.filter';
import { JwtAuthGuard } from './common/guards/jwt-auth.guard';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
cache: true,
validate: validateEnv,
}),
DatabaseModule,
CommonModule,
SettingsModule,
AuthModule,
UsersModule,
SystemModule,
AdminModule,
UploadsModule,
FrontendModule,
],
providers: [
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_FILTER, useClass: GlobalExceptionFilter },
],
})
export class AppModule {}
+30
View File
@@ -0,0 +1,30 @@
import { Module, Global } from '@nestjs/common';
import { ThemeLoaderService } from './utils/theme-loader.service';
import { EventStatusService } from './services/event-status.service';
import { SseHubService } from './services/sse-hub.service';
import { LoginBackoffService } from './services/login-backoff.service';
import { RegistrationRateLimitService } from './services/registration-rate-limit.service';
import { CsrfMiddleware } from './middleware/csrf.middleware';
import { SettingsModule } from '../modules/settings/settings.module';
@Global()
@Module({
imports: [SettingsModule],
providers: [
ThemeLoaderService,
EventStatusService,
SseHubService,
LoginBackoffService,
RegistrationRateLimitService,
CsrfMiddleware,
],
exports: [
ThemeLoaderService,
EventStatusService,
SseHubService,
LoginBackoffService,
RegistrationRateLimitService,
CsrfMiddleware,
],
})
export class CommonModule {}
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
@@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { UserRole } from '../../database/entities/user.entity';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';
export const SKIP_CSRF_KEY = 'skipCsrf';
export const SkipCsrf = () => SetMetadata(SKIP_CSRF_KEY, true);
+37
View File
@@ -0,0 +1,37 @@
import { HttpException, HttpStatus } from '@nestjs/common';
import { ErrorCode, ERROR_CODES } from './error-codes';
export class ApiError extends HttpException {
constructor(
public readonly code: ErrorCode,
message: string,
status: HttpStatus,
public readonly details?: unknown,
) {
super({ code, message, details }, status);
}
static validation(message = 'Validation failed', details?: unknown): ApiError {
return new ApiError(ERROR_CODES.VALIDATION_FAILED, message, HttpStatus.BAD_REQUEST, details);
}
static unauthorized(message = 'Unauthorized'): ApiError {
return new ApiError(ERROR_CODES.UNAUTHORIZED, message, HttpStatus.UNAUTHORIZED);
}
static forbidden(message = 'Forbidden'): ApiError {
return new ApiError(ERROR_CODES.FORBIDDEN, message, HttpStatus.FORBIDDEN);
}
static notFound(message = 'Not found'): ApiError {
return new ApiError(ERROR_CODES.NOT_FOUND, message, HttpStatus.NOT_FOUND);
}
static conflict(code: ErrorCode, message: string): ApiError {
return new ApiError(code, message, HttpStatus.CONFLICT);
}
static internal(message = 'Internal server error'): ApiError {
return new ApiError(ERROR_CODES.INTERNAL, message, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
+18
View File
@@ -0,0 +1,18 @@
export const ERROR_CODES = {
VALIDATION_FAILED: 'VALIDATION_FAILED',
UNAUTHORIZED: 'UNAUTHORIZED',
FORBIDDEN: 'FORBIDDEN',
NOT_FOUND: 'NOT_FOUND',
CONFLICT: 'CONFLICT',
LAST_ADMIN: 'LAST_ADMIN',
SYSTEM_INITIALIZED: 'SYSTEM_INITIALIZED',
RATE_LIMITED: 'RATE_LIMITED',
CSRF_INVALID: 'CSRF_INVALID',
WEAK_PASSWORD: 'WEAK_PASSWORD',
INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',
TOKEN_REVOKED: 'TOKEN_REVOKED',
THEME_INVALID: 'THEME_INVALID',
INTERNAL: 'INTERNAL',
} as const;
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
@@ -0,0 +1,81 @@
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { ApiError } from '../errors/api-error';
import { ERROR_CODES } from '../errors/error-codes';
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(GlobalExceptionFilter.name);
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const req = ctx.getRequest();
const path = req?.url ?? '';
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let body: { code: string; message: string; details?: unknown; path: string; timestamp: string };
if (exception instanceof ApiError) {
status = exception.getStatus();
const resp = exception.getResponse() as any;
body = {
code: resp.code,
message: resp.message,
details: resp.details,
path,
timestamp: new Date().toISOString(),
};
} else if (exception instanceof HttpException) {
status = exception.getStatus();
const resp = exception.getResponse() as any;
const message = typeof resp === 'string' ? resp : resp?.message ?? exception.message;
const code = typeof resp === 'object' && resp?.code ? resp.code : this.codeFromStatus(status);
body = {
code,
message: Array.isArray(message) ? message.join('; ') : message,
details: typeof resp === 'object' ? resp?.details : undefined,
path,
timestamp: new Date().toISOString(),
};
} else {
this.logger.error(`Unhandled error: ${(exception as Error)?.message}`, (exception as Error)?.stack);
const message = process.env.NODE_ENV === 'production' ? 'Internal server error' : (exception as Error)?.message ?? 'Internal server error';
body = {
code: ERROR_CODES.INTERNAL,
message,
path,
timestamp: new Date().toISOString(),
};
}
if (status >= 500) {
this.logger.error(`${status} ${body.code} ${path}: ${body.message}`);
} else if (status >= 400) {
this.logger.warn(`${status} ${body.code} ${path}: ${body.message}`);
}
httpAdapter.reply(ctx.getResponse(), body, status);
}
private codeFromStatus(status: number): string {
switch (status) {
case 400: return ERROR_CODES.VALIDATION_FAILED;
case 401: return ERROR_CODES.UNAUTHORIZED;
case 403: return ERROR_CODES.FORBIDDEN;
case 404: return ERROR_CODES.NOT_FOUND;
case 409: return ERROR_CODES.CONFLICT;
case 429: return ERROR_CODES.RATE_LIMITED;
default: return ERROR_CODES.INTERNAL;
}
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
const req = context.switchToHttp().getRequest();
if (!req.user) throw new ForbiddenException('Authentication required');
if (!required || required.length === 0) return true;
if (!required.includes(req.user.role)) {
throw new ForbiddenException('Admin role required');
}
return true;
}
}
@@ -0,0 +1,20 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private readonly reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
return super.canActivate(context);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
import { UserRole } from '../../database/entities/user.entity';
import { ApiError } from '../errors/api-error';
import { ERROR_CODES } from '../errors/error-codes';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!required || required.length === 0) return true;
const req = context.switchToHttp().getRequest();
if (!req.user) throw ApiError.unauthorized();
if (!required.includes(req.user.role)) {
throw new ForbiddenException('Insufficient role');
}
return true;
}
}
@@ -0,0 +1,10 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(_context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(map((data) => ({ data })));
}
}
@@ -0,0 +1,98 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';
import { ConfigService } from '@nestjs/config';
import { ApiError } from '../errors/api-error';
import { ERROR_CODES } from '../errors/error-codes';
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
const COOKIE_NAME = 'csrf';
const HEADER_NAME = 'x-csrf-token';
const SKIP_PATH_PREFIXES = ['/api/v1/auth/register-first-admin', '/api/v1/auth/login'];
function isSkipped(path: string): boolean {
return SKIP_PATH_PREFIXES.some((p) => path === p || path.startsWith(p + '/'));
}
function readCookie(req: Request): string | null {
const header = req.headers.cookie;
if (!header) return null;
const parts = header.split(';');
for (const part of parts) {
const [k, ...v] = part.trim().split('=');
if (k === COOKIE_NAME) return v.join('=');
}
return null;
}
/**
* Resolve the request's effective path. In NestJS mounted middleware,
* `req.path` may already be stripped to '/' when the controller is reached
* through a nested router; use the original URL as the authoritative source.
*/
function requestPath(req: Request): string {
const orig = req.originalUrl || req.url || req.path || '/';
const qIdx = orig.indexOf('?');
return qIdx >= 0 ? orig.slice(0, qIdx) : orig;
}
function safeEqual(a: string, b: string): boolean {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
if (bufA.length !== bufB.length) return false;
return crypto.timingSafeEqual(bufA, bufB);
}
@Injectable()
export class CsrfMiddleware implements NestMiddleware {
constructor(private readonly config: ConfigService) {}
/**
* Public helper: ensure a `csrf` cookie exists on the response and return its value.
* If a token already exists in the request cookies, that one is returned and re-set.
* Otherwise a new one is minted, set on the response, and returned.
*/
setOrGetCsrfToken(req: Request, res: Response): string {
const existing = readCookie(req);
if (existing) {
this.writeCookie(res, existing);
return existing;
}
const token = crypto.randomBytes(24).toString('base64url');
this.writeCookie(res, token);
return token;
}
use(req: Request, res: Response, next: NextFunction): void {
const path = requestPath(req);
if (isSkipped(path)) {
this.setOrGetCsrfToken(req, res);
return next();
}
if (!UNSAFE_METHODS.has(req.method)) {
this.setOrGetCsrfToken(req, res);
return next();
}
this.setOrGetCsrfToken(req, res);
const cookieToken = readCookie(req);
const headerToken = (req.headers[HEADER_NAME] as string | undefined) ?? '';
if (!cookieToken || !headerToken || !safeEqual(cookieToken, headerToken)) {
throw new ApiError(ERROR_CODES.CSRF_INVALID, 'CSRF token missing or invalid', 403);
}
next();
}
private writeCookie(res: Response, token: string): void {
const tls = this.config.get<boolean>('TLS_ENABLED', false);
res.cookie(COOKIE_NAME, token, {
httpOnly: false,
sameSite: tls ? 'strict' : 'lax',
secure: tls,
path: '/',
});
}
}
@@ -0,0 +1,17 @@
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import { ZodSchema } from 'zod';
import { ApiError } from '../errors/api-error';
@Injectable()
export class ZodValidationPipe implements PipeTransform {
constructor(private readonly schema: ZodSchema) {}
transform(value: any, _metadata: ArgumentMetadata): any {
const parsed = this.schema.safeParse(value);
if (!parsed.success) {
const details = parsed.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message }));
throw ApiError.validation('Request validation failed', details);
}
return parsed.data;
}
}
@@ -0,0 +1,48 @@
import { Injectable } from '@nestjs/common';
import { SettingsService } from '../../modules/settings/settings.module';
export type EventStatusName = 'Stopped' | 'Running';
export interface EventStatus {
status: EventStatusName;
startUtc: string;
endUtc: string;
serverNowUtc: string;
countdownMs: number;
}
@Injectable()
export class EventStatusService {
constructor(private readonly settings: SettingsService) {}
async getStatus(now: Date = new Date()): Promise<EventStatus> {
const startStr = await this.settings.get('eventStartUtc');
const endStr = await this.settings.get('eventEndUtc');
const start = new Date(startStr);
const end = new Date(endStr);
const nowMs = now.getTime();
const startMs = start.getTime();
const endMs = end.getTime();
let status: EventStatusName = 'Stopped';
let countdownMs = 0;
if (nowMs < startMs) {
status = 'Stopped';
countdownMs = startMs - nowMs;
} else if (nowMs <= endMs) {
status = 'Running';
countdownMs = endMs - nowMs;
} else {
status = 'Stopped';
countdownMs = 0;
}
return {
status,
startUtc: start.toISOString(),
endUtc: end.toISOString(),
serverNowUtc: now.toISOString(),
countdownMs,
};
}
}
@@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
const MAX_FAILS = 5;
const BACKOFF_MS = [1_000, 5_000, 30_000, 120_000, 600_000, 1_800_000];
@Injectable()
export class LoginBackoffService {
private counters = new Map<string, { count: number; blockedUntil: number }>();
private key(ip: string, username: string): string {
return `${ip}::${username}`;
}
isBlocked(ip: string, username: string, now: number = Date.now()): number {
const k = this.key(ip, username);
const entry = this.counters.get(k);
if (!entry) return 0;
if (entry.blockedUntil > now) return entry.blockedUntil - now;
return 0;
}
recordFailure(ip: string, username: string, now: number = Date.now()): void {
const k = this.key(ip, username);
const entry = this.counters.get(k) ?? { count: 0, blockedUntil: 0 };
entry.count++;
if (entry.count > MAX_FAILS) {
const idx = Math.min(entry.count - MAX_FAILS - 1, BACKOFF_MS.length - 1);
entry.blockedUntil = now + BACKOFF_MS[idx];
} else if (entry.count === MAX_FAILS) {
entry.blockedUntil = now + BACKOFF_MS[0];
}
this.counters.set(k, entry);
}
reset(ip: string, username: string): void {
this.counters.delete(this.key(ip, username));
}
}
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
const WINDOW_MS = 60_000;
const MAX_PER_WINDOW = 10;
@Injectable()
export class RegistrationRateLimitService {
private hits: Map<string, number[]> = new Map();
isAllowed(ip: string, now: number = Date.now()): boolean {
const arr = (this.hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
this.hits.set(ip, arr);
return arr.length < MAX_PER_WINDOW;
}
record(ip: string, now: number = Date.now()): void {
const arr = (this.hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
arr.push(now);
this.hits.set(ip, arr);
}
}
@@ -0,0 +1,24 @@
import { Injectable } from '@nestjs/common';
import { Subject, Observable } from 'rxjs';
@Injectable()
export class SseHubService {
private readonly eventSubject = new Subject<any>();
private readonly scoreboardSubject = new Subject<any>();
emitEvent(payload: any): void {
this.eventSubject.next(payload);
}
emitScoreboard(payload: any): void {
this.scoreboardSubject.next(payload);
}
event$(): Observable<any> {
return this.eventSubject.asObservable();
}
scoreboard$(): Observable<any> {
return this.scoreboardSubject.asObservable();
}
}
+14
View File
@@ -0,0 +1,14 @@
export const THEME_IDS = [
'classic',
'midnight',
'sunset',
'forest',
'cyber',
'paper',
'crimson',
'ocean',
'neon',
'monochrome',
] as const;
export type ThemeId = (typeof THEME_IDS)[number];
+19
View File
@@ -0,0 +1,19 @@
export type ThemeTokens = {
primary: string;
secondary: string;
accent: string;
surface: string;
text: string;
success: string;
warning: string;
danger: string;
fontFamily: string;
radii: { sm: string; md: string; lg: string };
spacingScale: number[];
};
export type Theme = {
id: string;
name: string;
tokens: ThemeTokens;
};
+116
View File
@@ -0,0 +1,116 @@
import { OpenAPIObject } from '@nestjs/swagger';
/**
* Convert a NestJS-generated OpenAPI 3.0 document to a JSON Schema 2020-12-
* compatible OpenAPI 3.1 document.
*
* The two specs differ mainly in:
* - `openapi` version string.
* - JSON Schema dialect: 3.0 used a custom subset of JSON Schema Draft 5
* (with `nullable: true`); 3.1 uses JSON Schema 2020-12 natively
* (nullable via `type: ['T', 'null']`).
* - `info` no longer requires `license` / `contact`.
*
* The `paths`/`components`/`security` structures are otherwise identical,
* and we keep all NestJS-generated content intact.
*/
export function toOpenApi31(doc: Record<string, any>): OpenAPIObject {
const next: Record<string, any> = { ...doc, openapi: '3.1.0' };
// Normalize info so it has every required 3.1 field.
if (!next.info || typeof next.info !== 'object') {
next.info = { title: 'HIPCTF API', version: '1.0.0' };
} else {
next.info = {
title: next.info.title ?? 'HIPCTF API',
version: next.info.version ?? '1.0.0',
...(next.info.description ? { description: next.info.description } : {}),
...(next.info.contact ? { contact: next.info.contact } : {}),
...(next.info.license ? { license: next.info.license } : {}),
};
}
// Rewrite component schemas: replace `nullable: true` with the JSON
// Schema 2020-12 `type: ['<orig>', 'null']` union. Leave everything else
// untouched so existing component definitions remain valid.
const components = next.components ?? {};
const schemas = components.schemas ?? {};
for (const [name, schema] of Object.entries<any>(schemas)) {
schemas[name] = rewriteNullable(schema);
}
components.schemas = schemas;
next.components = components;
// Walk paths and parameters and rewrite any remaining `nullable: true`.
if (next.paths && typeof next.paths === 'object') {
for (const [pathKey, methods] of Object.entries<any>(next.paths)) {
for (const [method, op] of Object.entries<any>(methods ?? {})) {
if (!op || typeof op !== 'object') continue;
if (Array.isArray(op.parameters)) {
op.parameters = op.parameters.map((p: any) => rewriteNullable(p));
}
if (op.requestBody) op.requestBody = rewriteNullable(op.requestBody);
const body = op.requestBody?.content;
if (body && typeof body === 'object') {
for (const media of Object.values<any>(body)) {
if (media?.schema) media.schema = rewriteNullable(media.schema);
}
}
if (op.responses && typeof op.responses === 'object') {
for (const [code, resp] of Object.entries<any>(op.responses)) {
op.responses[code] = rewriteNullable(resp);
const respBody = op.responses[code]?.content;
if (respBody && typeof respBody === 'object') {
for (const media of Object.values<any>(respBody)) {
if (media?.schema) media.schema = rewriteNullable(media.schema);
}
}
}
}
}
}
}
return next as OpenAPIObject;
}
/**
* Recursively walk a schema and convert legacy `nullable: true` markers
* into JSON Schema 2020-12 `type: ['<orig>', 'null']` unions. Preserve any
* other keyword (`$ref`, `format`, `enum`, etc.).
*/
function rewriteNullable(node: any): any {
if (!node || typeof node !== 'object' || Array.isArray(node)) return node;
// If this is a $ref, leave it alone.
if (typeof node.$ref === 'string') return node;
const out: Record<string, any> = { ...node };
if (out.nullable === true) {
delete out.nullable;
if (typeof out.type === 'string') {
out.type = [out.type, 'null'];
} else if (Array.isArray(out.type)) {
if (!out.type.includes('null')) out.type = [...out.type, 'null'];
} else if (!out.oneOf && !out.anyOf && !out.allOf) {
out.type = ['null'];
}
}
for (const k of Object.keys(out)) {
if (k === 'properties' && out.properties && typeof out.properties === 'object') {
for (const p of Object.keys(out.properties)) {
out.properties[p] = rewriteNullable(out.properties[p]);
}
} else if (k === 'items') {
out.items = rewriteNullable(out.items);
} else if (k === 'schema') {
out.schema = rewriteNullable(out.schema);
} else if ((k === 'oneOf' || k === 'anyOf' || k === 'allOf') && Array.isArray(out[k])) {
out[k] = out[k].map((v: any) => rewriteNullable(v));
}
}
return out;
}
@@ -0,0 +1,20 @@
import { ConfigService } from '@nestjs/config';
import { ApiError } from '../errors/api-error';
import { ERROR_CODES } from '../errors/error-codes';
export function validatePassword(password: string, config: ConfigService): void {
const minLen = config.get<number>('PASSWORD_MIN_LENGTH', 12);
if (typeof password !== 'string' || password.length < minLen) {
throw new ApiError(ERROR_CODES.WEAK_PASSWORD, `Password must be at least ${minLen} characters`, 400);
}
const requireMixed = config.get<boolean>('PASSWORD_REQUIRE_MIXED', true);
if (requireMixed) {
const hasUpper = /[A-Z]/.test(password);
const hasLower = /[a-z]/.test(password);
const hasDigit = /[0-9]/.test(password);
const hasSymbol = /[^A-Za-z0-9]/.test(password);
if (!(hasUpper && hasLower && hasDigit && hasSymbol)) {
throw new ApiError(ERROR_CODES.WEAK_PASSWORD, 'Password must include upper, lower, digit, and symbol', 400);
}
}
}
@@ -0,0 +1,255 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
import { THEME_IDS, ThemeId } from '../types/theme-ids';
import { Theme, ThemeTokens } from '../types/theme';
import { SettingsService } from '../../modules/settings/settings.module';
import { SETTINGS_KEYS } from '../../config/env.schema';
@Injectable()
export class ThemeLoaderService implements OnModuleInit {
private readonly logger = new Logger(ThemeLoaderService.name);
private themes: Map<string, Theme> = new Map();
private defaultThemeId: ThemeId = 'classic';
private themesDir = './themes';
constructor(
private readonly config: ConfigService,
private readonly settings: SettingsService,
) {}
async onModuleInit(): Promise<void> {
this.themesDir = this.config.get<string>('THEMES_DIR', './themes');
this.loadFromDisk();
this.backfillMissing();
await this.validateConfiguredKey();
this.logger.log(`Loaded ${this.themes.size} themes; default='${this.defaultThemeId}'`);
}
private loadFromDisk(): void {
const absDir = path.resolve(this.themesDir);
if (!fs.existsSync(absDir)) {
this.logger.warn(`Themes directory not found at ${absDir}; will backfill from built-ins`);
return;
}
const files = fs.readdirSync(absDir).filter((f) => f.endsWith('.json'));
const validIds = new Set<string>(THEME_IDS);
for (const file of files) {
try {
const raw = fs.readFileSync(path.join(absDir, file), 'utf-8');
const parsed = JSON.parse(raw) as Theme;
if (!parsed.id || !validIds.has(parsed.id)) {
this.logger.warn(`Skipping theme file ${file}: invalid or unknown id '${parsed.id}'`);
continue;
}
if (!parsed.tokens || !this.validateTokens(parsed.tokens)) {
this.logger.warn(`Skipping theme file ${file}: invalid tokens`);
continue;
}
this.themes.set(parsed.id, parsed);
} catch (err) {
this.logger.warn(`Failed to parse theme file ${file}: ${(err as Error).message}`);
}
}
}
/**
* After disk-loading, backfill any of the 10 canonical themes that are
* missing with the matching built-in. This guarantees the service
* ALWAYS exposes all 10 theme ids regardless of disk state.
*/
private backfillMissing(): void {
for (const t of BUILTIN_THEMES) {
if (!this.themes.has(t.id)) {
this.logger.warn(`Theme '${t.id}' missing from disk; using built-in default`);
this.themes.set(t.id, t);
}
}
}
/**
* Validate the configured theme key (from settings) against the 10
* canonical ids. If it's missing or invalid, fall back to 'classic' with
* a warning. Persists the canonical value back to settings so future
* reads are consistent.
*/
private async validateConfiguredKey(): Promise<void> {
let configured = 'classic';
try {
configured = await this.settings.get(SETTINGS_KEYS.THEME_KEY, 'classic');
} catch (e) {
// The setting table may not exist yet (early boot, migrations not
// run). Fall back to the safe default and try again later.
this.logger.warn(`Could not read configured themeKey (${(e as Error).message}); falling back to 'classic'`);
this.defaultThemeId = 'classic';
return;
}
const validIds = new Set<string>(THEME_IDS);
if (!configured || !validIds.has(configured)) {
this.logger.warn(`Configured themeKey '${configured}' is not in [${THEME_IDS.join(',')}]; falling back to 'classic'`);
this.defaultThemeId = 'classic';
try {
await this.settings.set(SETTINGS_KEYS.THEME_KEY, 'classic');
} catch {
// Setting table may still not exist; ignore.
}
} else {
this.defaultThemeId = configured as ThemeId;
}
}
private validateTokens(t: ThemeTokens): boolean {
const required = ['primary', 'secondary', 'accent', 'surface', 'text', 'success', 'warning', 'danger', 'fontFamily', 'radii', 'spacingScale'];
for (const k of required) {
if (!(k in t)) return false;
}
if (!t.radii.sm || !t.radii.md || !t.radii.lg) return false;
if (!Array.isArray(t.spacingScale) || t.spacingScale.length === 0) return false;
return true;
}
getTheme(id: string | null | undefined): Theme {
if (!id) return this.themes.get(this.defaultThemeId)!;
const t = this.themes.get(id);
if (t) return t;
this.logger.warn(`Unknown theme id '${id}'; falling back to '${this.defaultThemeId}'`);
return this.themes.get(this.defaultThemeId)!;
}
getDefaultTheme(): Theme {
return this.themes.get(this.defaultThemeId)!;
}
listThemes(): Theme[] {
return Array.from(this.themes.values());
}
/** Test/internal accessor for the resolved default id. */
getDefaultId(): ThemeId {
return this.defaultThemeId;
}
}
export const BUILTIN_THEMES: Theme[] = [
{
id: 'classic',
name: 'Classic',
tokens: {
primary: '#3b82f6', secondary: '#64748b', accent: '#f59e0b',
surface: '#ffffff', text: '#0f172a',
success: '#10b981', warning: '#f59e0b', danger: '#ef4444',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '4px', md: '8px', lg: '16px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'midnight',
name: 'Midnight',
tokens: {
primary: '#6366f1', secondary: '#1e293b', accent: '#22d3ee',
surface: '#0f172a', text: '#e2e8f0',
success: '#34d399', warning: '#fbbf24', danger: '#f87171',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '4px', md: '8px', lg: '16px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'sunset',
name: 'Sunset',
tokens: {
primary: '#f97316', secondary: '#fb7185', accent: '#facc15',
surface: '#fff7ed', text: '#431407',
success: '#84cc16', warning: '#f59e0b', danger: '#dc2626',
fontFamily: 'Georgia, serif',
radii: { sm: '6px', md: '12px', lg: '24px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'forest',
name: 'Forest',
tokens: {
primary: '#16a34a', secondary: '#65a30d', accent: '#ca8a04',
surface: '#f0fdf4', text: '#14532d',
success: '#15803d', warning: '#ca8a04', danger: '#b91c1c',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '4px', md: '8px', lg: '12px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'cyber',
name: 'Cyber',
tokens: {
primary: '#00ffd5', secondary: '#ff00aa', accent: '#ffee00',
surface: '#000000', text: '#00ffd5',
success: '#00ff88', warning: '#ffee00', danger: '#ff0066',
fontFamily: 'Courier New, monospace',
radii: { sm: '0', md: '0', lg: '0' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'paper',
name: 'Paper',
tokens: {
primary: '#1f2937', secondary: '#6b7280', accent: '#0ea5e9',
surface: '#fafaf9', text: '#1c1917',
success: '#059669', warning: '#d97706', danger: '#b91c1c',
fontFamily: 'Georgia, serif',
radii: { sm: '2px', md: '4px', lg: '8px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'crimson',
name: 'Crimson',
tokens: {
primary: '#dc2626', secondary: '#991b1b', accent: '#fbbf24',
surface: '#1f1f1f', text: '#fef2f2',
success: '#22c55e', warning: '#fbbf24', danger: '#ef4444',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '4px', md: '8px', lg: '12px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'ocean',
name: 'Ocean',
tokens: {
primary: '#0ea5e9', secondary: '#06b6d4', accent: '#14b8a6',
surface: '#f0f9ff', text: '#0c4a6e',
success: '#10b981', warning: '#f59e0b', danger: '#ef4444',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '8px', md: '16px', lg: '24px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'neon',
name: 'Neon',
tokens: {
primary: '#a855f7', secondary: '#ec4899', accent: '#22d3ee',
surface: '#0a0a0a', text: '#f5f3ff',
success: '#4ade80', warning: '#fbbf24', danger: '#fb7185',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '4px', md: '12px', lg: '20px' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
{
id: 'monochrome',
name: 'Monochrome',
tokens: {
primary: '#000000', secondary: '#525252', accent: '#a3a3a3',
surface: '#ffffff', text: '#0a0a0a',
success: '#404040', warning: '#737373', danger: '#171717',
fontFamily: 'system-ui, sans-serif',
radii: { sm: '0', md: '0', lg: '0' },
spacingScale: [4, 8, 12, 16, 24, 32, 48],
},
},
];
+75
View File
@@ -0,0 +1,75 @@
import { ConfigService } from '@nestjs/config';
import * as path from 'path';
import * as fs from 'fs';
import * as crypto from 'crypto';
import multer from 'multer';
export interface UploadLimits {
fileSize: number;
}
/**
* Build a multer-style `limits` object from the UPLOAD_SIZE_LIMIT env value.
* Examples: '50mb', '500kb', '2gb'. Defaults to '50mb'.
*/
export function parseUploadSizeLimit(value: string | undefined): number {
const v = (value ?? '50mb').trim().toLowerCase();
const m = /^(\d+(?:\.\d+)?)(b|kb|mb|gb)$/.exec(v);
if (!m) return 50 * 1024 * 1024;
const n = parseFloat(m[1]);
const unit = m[2];
const mult = unit === 'b' ? 1 : unit === 'kb' ? 1024 : unit === 'mb' ? 1024 * 1024 : 1024 * 1024 * 1024;
return Math.floor(n * mult);
}
export function buildUploadLimits(config: ConfigService): UploadLimits {
const v = config.get<string>('UPLOAD_SIZE_LIMIT', '50mb');
return { fileSize: parseUploadSizeLimit(v) };
}
/**
* Produce a safe, collision-resistant filename from the original upload
* filename. Strips directory traversal, lowercases, restricts to a safe
* charset, caps the stem length, and appends a short random suffix so
* identical names from different uploads never overwrite each other.
*/
export function safeFilename(original: string): string {
const base = path.basename(original || 'file').toLowerCase();
const cleaned = base
.replace(/[^a-z0-9._-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 120);
const stem = cleaned || 'file';
const dot = stem.lastIndexOf('.');
const head = dot > 0 ? stem.slice(0, dot) : stem;
const ext = dot > 0 ? stem.slice(dot) : '';
const suffix = crypto.randomBytes(4).toString('hex');
const safeHead = (head || 'file').slice(0, 100);
return `${safeHead}-${suffix}${ext}`;
}
/**
* Build a configured Multer instance with a per-route `fileSize` limit
* (taken from `UPLOAD_SIZE_LIMIT`) and safe-filename storage at the
* supplied destination directory.
*/
export interface MulterOptions {
destination?: string;
fieldName?: string;
fileSize?: number;
}
export function buildMulter(config: ConfigService, opts: MulterOptions = {}): multer.Multer {
const limits = opts.fileSize !== undefined
? { fileSize: opts.fileSize }
: buildUploadLimits(config);
const dest = opts.destination ?? path.resolve(config.get<string>('UPLOAD_DIR', '/data/hipctf/uploads'));
if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
return multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, dest),
filename: (_req, file, cb) => cb(null, safeFilename(file.originalname)),
}),
limits,
});
}
+76
View File
@@ -0,0 +1,76 @@
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_PATH: z.string().min(1).default('/data/hipctf/db.sqlite'),
UPLOAD_DIR: z.string().min(1).default('/data/hipctf/uploads'),
THEMES_DIR: z.string().min(1).default('./themes'),
FRONTEND_DIST: z.string().min(1).default('../frontend/dist'),
JWT_ACCESS_SECRET: z.string().min(32).default('dev-access-secret-change-me-please-32chars'),
JWT_REFRESH_SECRET: z.string().min(32).default('dev-refresh-secret-change-me-please-32ch'),
CSRF_SECRET: z.string().min(32).default('dev-csrf-secret-change-me-please-32chars!!'),
JWT_ACCESS_TTL: z.string().default('15m'),
JWT_REFRESH_TTL: z.string().default('7d'),
ARGON2_MEMORY_COST: z.coerce.number().int().positive().default(65536),
ARGON2_TIME_COST: z.coerce.number().int().positive().default(3),
ARGON2_PARALLELISM: z.coerce.number().int().positive().default(1),
PASSWORD_MIN_LENGTH: z.coerce.number().int().positive().default(12),
PASSWORD_REQUIRE_MIXED: z.coerce.boolean().default(true),
CORS_ORIGINS: z.string().default('http://localhost:4200,http://localhost:3000'),
BODY_SIZE_LIMIT: z.string().default('1mb'),
UPLOAD_SIZE_LIMIT: z.string().default('50mb'),
TLS_ENABLED: z.coerce.boolean().default(false),
});
export type AppEnv = z.infer<typeof envSchema>;
export function validateEnv(raw: Record<string, unknown>): AppEnv {
const parsed = envSchema.safeParse(raw);
if (!parsed.success) {
const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');
throw new Error(`Invalid environment configuration: ${issues}`);
}
return parsed.data;
}
export const SETTINGS_KEYS = {
PAGE_TITLE: 'pageTitle',
LOGO: 'logo',
WELCOME_MARKDOWN: 'welcomeMarkdown',
THEME_KEY: 'themeKey',
DEFAULT_CHALLENGE_IP: 'defaultChallengeIp',
REGISTRATIONS_ENABLED: 'registrationsEnabled',
EVENT_START_UTC: 'eventStartUtc',
EVENT_END_UTC: 'eventEndUtc',
} as const;
export const DEFAULT_SETTINGS: Record<string, string> = {
[SETTINGS_KEYS.PAGE_TITLE]: 'HIPCTF',
[SETTINGS_KEYS.LOGO]: '',
[SETTINGS_KEYS.WELCOME_MARKDOWN]: '# Welcome\n\nCreate the first admin to get started.',
[SETTINGS_KEYS.THEME_KEY]: 'classic',
[SETTINGS_KEYS.DEFAULT_CHALLENGE_IP]: '127.0.0.1',
[SETTINGS_KEYS.REGISTRATIONS_ENABLED]: 'false',
[SETTINGS_KEYS.EVENT_START_UTC]: new Date(Date.now() + 60_000).toISOString(),
[SETTINGS_KEYS.EVENT_END_UTC]: new Date(Date.now() + 7 * 24 * 60 * 60_000).toISOString(),
};
export const SYSTEM_CATEGORY_KEYS = ['crypto', 'forensics', 'pwn', 'web', 'misc', 'osint'] as const;
export type SystemCategoryKey = (typeof SYSTEM_CATEGORY_KEYS)[number];
export const SYSTEM_CATEGORY_META: Record<SystemCategoryKey, { name: string; abbreviation: string; description: string; iconPath: string }> = {
crypto: { name: 'Cryptography', abbreviation: 'CRY', description: 'Crypto challenges', iconPath: '/uploads/icons/crypto.svg' },
forensics: { name: 'Forensics', abbreviation: 'FOR', description: 'Forensics challenges', iconPath: '/uploads/icons/forensics.svg' },
pwn: { name: 'Pwn', abbreviation: 'PWN', description: 'Binary exploitation', iconPath: '/uploads/icons/pwn.svg' },
web: { name: 'Web', abbreviation: 'WEB', description: 'Web exploitation', iconPath: '/uploads/icons/web.svg' },
misc: { name: 'Misc', abbreviation: 'MSC', description: 'Miscellaneous challenges', iconPath: '/uploads/icons/misc.svg' },
osint: { name: 'OSINT', abbreviation: 'OSI', description: 'Open-source intelligence', iconPath: '/uploads/icons/osint.svg' },
};
@@ -0,0 +1,102 @@
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
@Injectable()
export class DatabaseInitService implements OnApplicationBootstrap {
private readonly logger = new Logger(DatabaseInitService.name);
private initialized = false;
constructor(
private readonly dataSource: DataSource,
private readonly config: ConfigService,
) {}
/**
* Explicit, awaitable database initialization.
*
* - Initializes the DataSource (idempotent — TypeORM returns the existing
* connection if already initialized).
* - Runs all pending migrations in order.
* - Verifies that the expected schema and seeded data are present.
*
* `main.ts` calls this BEFORE `app.listen()` so the HTTP server never
* accepts traffic until the DB is fully migrated and seeded.
*/
async init(): Promise<void> {
if (this.initialized) return;
if (!this.dataSource.isInitialized) {
await this.dataSource.initialize();
}
// Enforce WAL journal mode on every startup. The InitSchema migration
// also sets it for fresh DBs, but warm DBs (where migrations are
// skipped) need it applied here so PRAGMA journal_mode is always 'wal'.
await this.ensureWalMode();
const pending = await this.dataSource.showMigrations();
const pendingList: string[] = Array.isArray(pending) ? pending : [];
this.logger.log(`Pending migrations: ${pendingList.length}`);
if (pendingList.length > 0 || !(await this.hasCategoryTable())) {
const ran = await this.dataSource.runMigrations({ transaction: 'each' });
this.logger.log(`Ran ${ran.length} migration(s): ${ran.map((m) => m.name).join(', ')}`);
} else {
this.logger.log('Database schema is up to date');
}
try {
await this.verifySeed();
} catch (e) {
this.logger.warn(`verifySeed skipped: ${(e as Error).message}`);
}
this.initialized = true;
}
async onApplicationBootstrap(): Promise<void> {
await this.init();
}
/**
* Read PRAGMA journal_mode and switch to WAL if not already enabled.
* Persisted for file-backed databases; idempotent and safe on every
* startup.
*/
private async ensureWalMode(): Promise<void> {
try {
const rows: any[] = await this.dataSource.query('PRAGMA journal_mode');
const current = String(rows?.[0]?.journal_mode ?? '').toLowerCase();
if (current === 'wal') {
this.logger.log('PRAGMA journal_mode=wal (already set)');
return;
}
const setRows: any[] = await this.dataSource.query('PRAGMA journal_mode = WAL');
const actual = String(setRows?.[0]?.journal_mode ?? '').toLowerCase();
this.logger.log(`PRAGMA journal_mode set (was='${current}', now='${actual}')`);
} catch (e) {
this.logger.warn(`ensureWalMode skipped: ${(e as Error).message}`);
}
}
private async verifySeed(): Promise<void> {
const categoryCount = await this.dataSource.query('SELECT COUNT(*) AS c FROM "category"').then((rows: any[]) => Number(rows[0]?.c ?? 0));
const settingsCount = await this.dataSource.query('SELECT COUNT(*) AS c FROM "setting"').then((rows: any[]) => Number(rows[0]?.c ?? 0));
this.logger.log(`Seed verified: ${categoryCount} categories, ${settingsCount} settings`);
if (categoryCount < 6) {
this.logger.warn(`Expected at least 6 seeded categories, found ${categoryCount}`);
}
}
private async hasCategoryTable(): Promise<boolean> {
try {
const rows: any[] = await this.dataSource.query("SELECT name FROM sqlite_master WHERE type='table' AND name='category'");
return rows.length > 0;
} catch {
return false;
}
}
getDbPath(): string {
return this.config.get<string>('DATABASE_PATH', '/data/hipctf/db.sqlite');
}
}
+62
View File
@@ -0,0 +1,62 @@
import { Module, Global, Logger } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { UserEntity } from './entities/user.entity';
import { SettingEntity } from './entities/setting.entity';
import { CategoryEntity } from './entities/category.entity';
import { ChallengeEntity } from './entities/challenge.entity';
import { ChallengeFileEntity } from './entities/challenge-file.entity';
import { SolveEntity } from './entities/solve.entity';
import { RefreshTokenEntity } from './entities/refresh-token.entity';
import { BlogPostEntity } from './entities/blog-post.entity';
import { InitSchema1700000000000 } from './migrations/1700000000000-InitSchema';
import { SeedSystemData1700000000100 } from './migrations/1700000000100-SeedSystemData';
import { DatabaseInitService } from './database-init.service';
const ENTITIES = [
UserEntity,
SettingEntity,
CategoryEntity,
ChallengeEntity,
ChallengeFileEntity,
SolveEntity,
RefreshTokenEntity,
BlogPostEntity,
];
const MIGRATIONS = [InitSchema1700000000000, SeedSystemData1700000000100];
@Global()
@Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const dbPath = config.get<string>('DATABASE_PATH', '/data/hipctf/db.sqlite');
const isMemory = dbPath === ':memory:' || dbPath.startsWith('file:');
if (!isMemory) {
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
return {
type: 'better-sqlite3',
database: dbPath,
entities: ENTITIES,
migrations: MIGRATIONS,
migrationsRun: false,
synchronize: false,
logging: false,
};
},
}),
TypeOrmModule.forFeature(ENTITIES),
],
providers: [DatabaseInitService],
exports: [TypeOrmModule, DatabaseInitService],
})
export class DatabaseModule {
private readonly logger = new Logger(DatabaseModule.name);
}
@@ -0,0 +1,28 @@
import { Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';
export type BlogStatus = 'draft' | 'published';
@Entity('blog_post')
export class BlogPostEntity {
@PrimaryColumn('text')
id!: string;
@Column('text')
title!: string;
@Column('text', { name: 'body_md', default: '' })
bodyMd!: string;
@Index('idx_blog_status_published', ['status', 'publishedAt'])
@Column('text', { default: 'draft' })
status!: BlogStatus;
@CreateDateColumn({ type: 'text', name: 'created_at' })
createdAt!: string;
@UpdateDateColumn({ type: 'text', name: 'updated_at' })
updatedAt!: string;
@Column('text', { name: 'published_at', nullable: true })
publishedAt!: string | null;
}
@@ -0,0 +1,23 @@
import { Entity, PrimaryColumn, Column, Index } from 'typeorm';
@Entity('category')
export class CategoryEntity {
@PrimaryColumn('text')
id!: string;
@Index({ unique: true, where: 'system_key IS NOT NULL' })
@Column('text', { name: 'system_key', nullable: true })
systemKey!: string | null;
@Column('text')
name!: string;
@Column('text')
abbreviation!: string;
@Column('text', { default: '' })
description!: string;
@Column('text', { name: 'icon_path', default: '' })
iconPath!: string;
}
@@ -0,0 +1,22 @@
import { Entity, PrimaryColumn, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { ChallengeEntity } from './challenge.entity';
@Entity('challenge_file')
export class ChallengeFileEntity {
@PrimaryColumn('text')
id!: string;
@Index()
@Column('text', { name: 'challenge_id' })
challengeId!: string;
@ManyToOne(() => ChallengeEntity)
@JoinColumn({ name: 'challenge_id' })
challenge?: ChallengeEntity;
@Column('text', { name: 'original_filename' })
originalFilename!: string;
@Column('text', { name: 'stored_path' })
storedPath!: string;
}
@@ -0,0 +1,52 @@
import { Entity, PrimaryColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, Index } from 'typeorm';
import { CategoryEntity } from './category.entity';
export type Difficulty = 'low' | 'med' | 'high';
export type Protocol = 'nc' | 'web';
@Entity('challenge')
export class ChallengeEntity {
@PrimaryColumn('text')
id!: string;
@Column('text')
name!: string;
@Column('text', { name: 'description_md', default: '' })
descriptionMd!: string;
@Index()
@Column('text', { name: 'category_id' })
categoryId!: string;
@ManyToOne(() => CategoryEntity)
@JoinColumn({ name: 'category_id' })
category?: CategoryEntity;
@Column('text', { default: 'low' })
difficulty!: Difficulty;
@Column('integer', { name: 'initial_points', default: 0 })
initialPoints!: number;
@Column('integer', { name: 'minimum_points', default: 0 })
minimumPoints!: number;
@Column('integer', { name: 'decay_solves', default: 0 })
decaySolves!: number;
@Column('text', { default: '' })
flag!: string;
@Column('text', { default: 'nc' })
protocol!: Protocol;
@Column('integer', { nullable: true })
port!: number | null;
@Column('text', { name: 'ip_address', default: '' })
ipAddress!: string;
@CreateDateColumn({ type: 'text', name: 'created_at' })
createdAt!: string;
}
@@ -0,0 +1,23 @@
import { Entity, PrimaryColumn, Column, Index } from 'typeorm';
@Entity('refresh_token')
export class RefreshTokenEntity {
@PrimaryColumn('text')
id!: string;
@Index()
@Column('text', { name: 'user_id' })
userId!: string;
@Column('text', { name: 'token_hash', unique: true })
tokenHash!: string;
@Column('text', { name: 'issued_at' })
issuedAt!: string;
@Column('text', { name: 'expires_at' })
expiresAt!: string;
@Column('text', { name: 'revoked_at', nullable: true })
revokedAt!: string | null;
}
@@ -0,0 +1,10 @@
import { Entity, PrimaryColumn, Column } from 'typeorm';
@Entity('setting')
export class SettingEntity {
@PrimaryColumn('text')
key!: string;
@Column('text', { default: '' })
value!: string;
}
@@ -0,0 +1,28 @@
import { Entity, PrimaryColumn, Column, Index, Unique } from 'typeorm';
@Entity('solve')
@Unique('uq_solve_challenge_user', ['challengeId', 'userId'])
@Index('idx_solve_user', ['userId'])
@Index('idx_solve_challenge', ['challengeId'])
export class SolveEntity {
@PrimaryColumn('text')
id!: string;
@Column('text', { name: 'challenge_id' })
challengeId!: string;
@Column('text', { name: 'user_id' })
userId!: string;
@Column('text', { name: 'solved_at' })
solvedAt!: string;
@Column('integer', { name: 'points_awarded', default: 0 })
pointsAwarded!: number;
@Column('integer', { name: 'base_points', default: 0 })
basePoints!: number;
@Column('integer', { name: 'rank_bonus', default: 0 })
rankBonus!: number;
}
@@ -0,0 +1,25 @@
import { Entity, PrimaryColumn, Column, CreateDateColumn } from 'typeorm';
export type UserRole = 'admin' | 'player';
export type UserStatus = 'enabled' | 'disabled';
@Entity('user')
export class UserEntity {
@PrimaryColumn('text')
id!: string;
@Column('text', { unique: true })
username!: string;
@Column('text', { name: 'password_hash' })
passwordHash!: string;
@Column('text', { default: 'player' })
role!: UserRole;
@Column('text', { default: 'enabled' })
status!: UserStatus;
@CreateDateColumn({ type: 'text', name: 'created_at' })
createdAt!: string;
}
@@ -0,0 +1,124 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class InitSchema1700000000000 implements MigrationInterface {
name = 'InitSchema1700000000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`PRAGMA foreign_keys = ON;`);
await queryRunner.query(`PRAGMA journal_mode = WAL;`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "user" (
"id" TEXT PRIMARY KEY,
"username" TEXT NOT NULL UNIQUE,
"password_hash" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'player',
"status" TEXT NOT NULL DEFAULT 'enabled',
"created_at" TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "setting" (
"key" TEXT PRIMARY KEY,
"value" TEXT NOT NULL DEFAULT ''
);
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "category" (
"id" TEXT PRIMARY KEY,
"system_key" TEXT,
"name" TEXT NOT NULL,
"abbreviation" TEXT NOT NULL,
"description" TEXT NOT NULL DEFAULT '',
"icon_path" TEXT NOT NULL DEFAULT ''
);
`);
await queryRunner.query(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_category_system_key" ON "category"("system_key") WHERE "system_key" IS NOT NULL;`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "challenge" (
"id" TEXT PRIMARY KEY,
"name" TEXT NOT NULL,
"description_md" TEXT NOT NULL DEFAULT '',
"category_id" TEXT NOT NULL,
"difficulty" TEXT NOT NULL DEFAULT 'low',
"initial_points" INTEGER NOT NULL DEFAULT 0,
"minimum_points" INTEGER NOT NULL DEFAULT 0,
"decay_solves" INTEGER NOT NULL DEFAULT 0,
"flag" TEXT NOT NULL DEFAULT '',
"protocol" TEXT NOT NULL DEFAULT 'nc',
"port" INTEGER,
"ip_address" TEXT NOT NULL DEFAULT '',
"created_at" TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
CONSTRAINT "fk_challenge_category" FOREIGN KEY ("category_id") REFERENCES "category"("id") ON DELETE RESTRICT
);
`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_challenge_category" ON "challenge"("category_id");`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "challenge_file" (
"id" TEXT PRIMARY KEY,
"challenge_id" TEXT NOT NULL,
"original_filename" TEXT NOT NULL,
"stored_path" TEXT NOT NULL,
CONSTRAINT "fk_challenge_file_challenge" FOREIGN KEY ("challenge_id") REFERENCES "challenge"("id") ON DELETE RESTRICT
);
`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_challenge_file_challenge" ON "challenge_file"("challenge_id");`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "solve" (
"id" TEXT PRIMARY KEY,
"challenge_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"solved_at" TEXT NOT NULL,
"points_awarded" INTEGER NOT NULL DEFAULT 0,
"base_points" INTEGER NOT NULL DEFAULT 0,
"rank_bonus" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "fk_solve_challenge" FOREIGN KEY ("challenge_id") REFERENCES "challenge"("id") ON DELETE RESTRICT,
CONSTRAINT "fk_solve_user" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE RESTRICT
);
`);
await queryRunner.query(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_solve_challenge_user" ON "solve"("challenge_id","user_id");`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_solve_user" ON "solve"("user_id");`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_solve_challenge" ON "solve"("challenge_id");`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "refresh_token" (
"id" TEXT PRIMARY KEY,
"user_id" TEXT NOT NULL,
"token_hash" TEXT NOT NULL UNIQUE,
"issued_at" TEXT NOT NULL,
"expires_at" TEXT NOT NULL,
"revoked_at" TEXT
);
`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_refresh_token_user" ON "refresh_token"("user_id");`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "blog_post" (
"id" TEXT PRIMARY KEY,
"title" TEXT NOT NULL,
"body_md" TEXT NOT NULL DEFAULT '',
"status" TEXT NOT NULL DEFAULT 'draft',
"created_at" TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
"updated_at" TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
"published_at" TEXT
);
`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_blog_status_published" ON "blog_post"("status","published_at");`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE IF EXISTS "blog_post";`);
await queryRunner.query(`DROP TABLE IF EXISTS "refresh_token";`);
await queryRunner.query(`DROP TABLE IF EXISTS "solve";`);
await queryRunner.query(`DROP TABLE IF EXISTS "challenge_file";`);
await queryRunner.query(`DROP TABLE IF EXISTS "challenge";`);
await queryRunner.query(`DROP TABLE IF EXISTS "category";`);
await queryRunner.query(`DROP TABLE IF EXISTS "setting";`);
await queryRunner.query(`DROP TABLE IF EXISTS "user";`);
}
}
@@ -0,0 +1,31 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
import { SYSTEM_CATEGORY_KEYS, SYSTEM_CATEGORY_META, DEFAULT_SETTINGS, SETTINGS_KEYS } from '../../config/env.schema';
import { v4 as uuid } from 'uuid';
export class SeedSystemData1700000000100 implements MigrationInterface {
name = 'SeedSystemData1700000000100';
public async up(queryRunner: QueryRunner): Promise<void> {
for (const key of SYSTEM_CATEGORY_KEYS) {
const meta = SYSTEM_CATEGORY_META[key];
const existing = await queryRunner.query(`SELECT id FROM "category" WHERE "system_key" = ?`, [key]);
if (existing.length > 0) continue;
await queryRunner.query(
`INSERT INTO "category" ("id","system_key","name","abbreviation","description","icon_path") VALUES (?,?,?,?,?,?)`,
[uuid(), key, meta.name, meta.abbreviation, meta.description, meta.iconPath],
);
}
for (const key of Object.values(SETTINGS_KEYS)) {
const existing = await queryRunner.query(`SELECT "key" FROM "setting" WHERE "key" = ?`, [key]);
if (existing.length > 0) continue;
const value = DEFAULT_SETTINGS[key] ?? '';
await queryRunner.query(`INSERT INTO "setting" ("key","value") VALUES (?,?)`, [key, value]);
}
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DELETE FROM "category" WHERE "system_key" IS NOT NULL;`);
await queryRunner.query(`DELETE FROM "setting";`);
}
}
+7
View File
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule],
})
export class FrontendModule {}
+29
View File
@@ -0,0 +1,29 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class SpaFallbackMiddleware implements NestMiddleware {
constructor(private readonly config: ConfigService) {}
use(req: Request, res: Response, next: NextFunction): void {
const url = req.path || req.url;
if (url.startsWith('/api') || url.startsWith('/uploads')) return next();
if (path.extname(url)) return next();
if (req.method !== 'GET') return next();
const distDir = path.resolve(this.config.get<string>('FRONTEND_DIST', '../frontend/dist'));
const candidates = [distDir, path.join(distDir, 'browser')];
for (const dir of candidates) {
const p = path.join(dir, 'index.html');
if (fs.existsSync(p)) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
fs.createReadStream(p).pipe(res);
return;
}
}
res.status(200).send('<!doctype html><html><body><h1>HIPCTF</h1><p>Frontend not built.</p></body></html>');
}
}
@@ -0,0 +1,22 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class UploadsStaticMiddleware implements NestMiddleware {
private rootDir = '/tmp';
constructor(config: ConfigService) {
const dir = path.resolve(config.get<string>('UPLOAD_DIR', '/data/hipctf/uploads'));
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
this.rootDir = dir;
}
use(req: Request, res: Response, next: NextFunction): void {
if (!req.path.startsWith('/uploads')) return next();
const express = require('express');
return express.static(this.rootDir)(req, res, next);
}
}
+114
View File
@@ -0,0 +1,114 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { toOpenApi31 } from './common/utils/openapi31';
import { ConfigService } from '@nestjs/config';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import * as fs from 'fs';
import * as path from 'path';
import * as express from 'express';
import { AppModule } from './app.module';
import { SpaFallbackMiddleware } from './frontend/spa.controller';
import { DatabaseInitService } from './database/database-init.service';
import { CsrfMiddleware } from './common/middleware/csrf.middleware';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
bufferLogs: false,
});
const config = app.get(ConfigService);
const nodeEnv = config.get<string>('NODE_ENV', 'development');
const port = config.get<number>('PORT', 3000);
const corsOrigins = (config.get<string>('CORS_ORIGINS', 'http://localhost:4200,http://localhost:3000'))
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const bodyLimit = config.get<string>('BODY_SIZE_LIMIT', '1mb');
const uploadDir = path.resolve(config.get<string>('UPLOAD_DIR', '/data/hipctf/uploads'));
const tlsEnabled = config.get<boolean>('TLS_ENABLED', false);
const frontendDist = path.resolve(config.get<string>('FRONTEND_DIST', '../frontend/dist'));
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
await app.get(DatabaseInitService).init();
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'blob:'],
connectSrc: ["'self'"],
fontSrc: ["'self'", 'data:'],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
},
},
hsts: tlsEnabled ? { maxAge: 31536000, includeSubDomains: true, preload: true } : false,
frameguard: { action: 'deny' },
noSniff: true,
referrerPolicy: { policy: 'no-referrer' },
}),
);
app.enableCors({
origin: corsOrigins,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
});
// Body parsers MUST run before the CSRF middleware so that route handlers
// can read `req.body` when the CsrfMiddleware short-circuits to next().
app.use(cookieParser());
app.use(express.json({ limit: bodyLimit }));
app.use(express.urlencoded({ extended: true, limit: bodyLimit }));
// CSRF: register globally via express so we have explicit ordering after
// the body parsers. (Nest's configure()-time middleware is registered
// before app.use middlewares, which would consume the body before the
// CsrfMiddleware short-circuits to next().)
const csrf = new CsrfMiddleware(config);
app.use((req, res, next) => csrf.use(req as any, res as any, next));
app.use('/uploads', express.static(uploadDir));
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: false, transform: true }));
const swaggerConfig = new DocumentBuilder()
.setTitle('HIPCTF API')
.setDescription('HIPCTF REST API')
.setVersion('1.0.0')
.addBearerAuth()
.addCookieAuth('rt')
.build();
const rawDocument = SwaggerModule.createDocument(app, swaggerConfig) as Record<string, any>;
const document = toOpenApi31(rawDocument);
SwaggerModule.setup('api/docs', app, document, {
jsonDocumentUrl: 'api/docs-json',
});
if (fs.existsSync(frontendDist)) {
app.use(express.static(frontendDist, { index: false, fallthrough: true }));
const browserDir = path.join(frontendDist, 'browser');
if (fs.existsSync(browserDir)) {
app.use(express.static(browserDir, { index: false, fallthrough: true }));
}
}
const spa = new SpaFallbackMiddleware(config);
app.use((req, res, next) => spa.use(req as any, res as any, next));
await app.listen(port, '0.0.0.0');
Logger.log(`HIPCTF API listening on http://0.0.0.0:${port} (env=${nodeEnv})`, 'Bootstrap');
}
bootstrap().catch((err) => {
console.error('Fatal startup error:', err);
process.exit(1);
});
@@ -0,0 +1,73 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { UserRole } from '../../database/entities/user.entity';
import { AdminGuard } from '../../common/guards/admin.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import {
CreateUserDtoSchema,
ListUsersQueryDtoSchema,
UpdateUserRoleDtoSchema,
UserIdParamDtoSchema,
} from './dto/admin.dto';
import { AdminService } from './admin.service';
/**
* All admin handlers use Zod validation via `ZodValidationPipe` and an
* INLINE body/param/query type. Using inline types (rather than class
* metatypes) avoids the Nest class-transformer pass which would otherwise
* overwrite the raw body before our pipe sees it.
*/
@ApiTags('admin')
@ApiBearerAuth()
@Controller('api/v1/admin')
@UseGuards(AdminGuard)
@Roles('admin')
export class AdminController {
constructor(private readonly admin: AdminService) {}
@Get('users')
@ApiOperation({ summary: 'List all users (admin only)' })
list(
@Query(new ZodValidationPipe(ListUsersQueryDtoSchema))
query: { limit?: number; cursor?: string; role?: UserRole },
) {
return this.admin.listUsers(query);
}
@Patch('users/:id')
@ApiOperation({ summary: 'Update a user role (admin only)' })
update(
@Param(new ZodValidationPipe(UserIdParamDtoSchema)) params: { id: string },
@Body(new ZodValidationPipe(UpdateUserRoleDtoSchema)) body: { role: UserRole },
) {
return this.admin.updateUserRole(params.id, body.role);
}
@Delete('users/:id')
@ApiOperation({ summary: 'Delete a user (admin only)' })
async remove(
@Param(new ZodValidationPipe(UserIdParamDtoSchema)) params: { id: string },
): Promise<void> {
await this.admin.deleteUser(params.id);
}
@Post('users')
@ApiOperation({ summary: 'Create a user (admin only)' })
create(
@Body(new ZodValidationPipe(CreateUserDtoSchema)) body: { username: string; password: string; role: UserRole },
) {
return this.admin.createUser(body.username, body.password, body.role);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from '../../database/entities/user.entity';
import { AuthModule } from '../auth/auth.module';
import { UsersModule } from '../users/users.module';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
@Module({
imports: [TypeOrmModule.forFeature([UserEntity]), AuthModule, UsersModule],
providers: [AdminService],
controllers: [AdminController],
})
export class AdminModule {}
@@ -0,0 +1,79 @@
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { v4 as uuid } from 'uuid';
import * as argon2 from 'argon2';
import { UserEntity, UserRole } from '../../database/entities/user.entity';
import { UsersService } from '../users/users.service';
import { ApiError } from '../../common/errors/api-error';
import { ERROR_CODES } from '../../common/errors/error-codes';
import { validatePassword } from '../../common/utils/password-policy';
import { ConfigService } from '@nestjs/config';
export interface ListUsersQuery {
limit?: number;
cursor?: string;
role?: UserRole;
}
@Injectable()
export class AdminService {
constructor(
private readonly usersService: UsersService,
private readonly dataSource: DataSource,
private readonly config: ConfigService,
) {}
async listUsers(query: ListUsersQuery = {}): Promise<UserEntity[]> {
const limit = Math.min(Math.max(query.limit ?? 50, 1), 200);
const repo = this.dataSource.getRepository(UserEntity);
const qb = repo
.createQueryBuilder('u')
.orderBy('u.createdAt', 'ASC')
.addOrderBy('u.id', 'ASC')
.limit(limit + 1);
if (query.role) qb.andWhere('u.role = :role', { role: query.role });
if (query.cursor) qb.andWhere('u.id > :cursor', { cursor: query.cursor });
const rows = await qb.getMany();
return rows.slice(0, limit);
}
async updateUserRole(targetId: string, role: UserRole): Promise<UserEntity> {
if (role !== 'admin' && role !== 'player') {
throw ApiError.validation('Invalid role');
}
return this.dataSource.transaction(async (manager) => {
await this.usersService.enforceLastAdminInvariant(manager, targetId, role);
const user = await manager.findOne(UserEntity, { where: { id: targetId } });
if (!user) throw ApiError.notFound('User not found');
user.role = role;
await manager.save(user);
return user;
});
}
async deleteUser(targetId: string): Promise<void> {
return this.dataSource.transaction(async (manager) => {
await this.usersService.enforceLastAdminInvariant(manager, targetId);
const res = await manager.delete(UserEntity, { id: targetId });
if (!res.affected) throw ApiError.notFound('User not found');
});
}
async createUser(username: string, password: string, role: UserRole): Promise<UserEntity> {
validatePassword(password, this.config);
return this.dataSource.transaction(async (manager) => {
const existing = await manager.findOne(UserEntity, { where: { username } });
if (existing) throw ApiError.conflict(ERROR_CODES.CONFLICT, 'Username already taken');
const hash = await argon2.hash(password, { type: argon2.argon2id });
const user = manager.create(UserEntity, {
id: uuid(),
username,
passwordHash: hash,
role,
status: 'enabled',
});
await manager.save(user);
return user;
});
}
}
@@ -0,0 +1,25 @@
import { z } from 'zod';
export const CreateUserDtoSchema = z.object({
username: z.string().trim().min(3).max(64).regex(/^[a-zA-Z0-9._-]+$/, 'Username may contain letters, digits, dot, underscore, dash'),
password: z.string().min(1).max(256),
role: z.enum(['admin', 'player']),
});
export type CreateUserDto = z.infer<typeof CreateUserDtoSchema>;
export const UpdateUserRoleDtoSchema = z.object({
role: z.enum(['admin', 'player']),
});
export type UpdateUserRoleDto = z.infer<typeof UpdateUserRoleDtoSchema>;
export const UserIdParamDtoSchema = z.object({
id: z.string().uuid(),
});
export type UserIdParamDto = z.infer<typeof UserIdParamDtoSchema>;
export const ListUsersQueryDtoSchema = z.object({
limit: z.coerce.number().int().positive().max(200).optional().default(50),
cursor: z.string().uuid().optional(),
role: z.enum(['admin', 'player']).optional(),
});
export type ListUsersQueryDto = z.infer<typeof ListUsersQueryDtoSchema>;
@@ -0,0 +1,89 @@
import {
Body,
Controller,
Get,
Post,
Req,
Res,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { ConfigService } from '@nestjs/config';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { Public } from '../../common/decorators/public.decorator';
import { LoginDtoSchema, RefreshDtoSchema } from './dto/auth.dto';
import { AuthService } from './auth.service';
import { CsrfMiddleware } from '../../common/middleware/csrf.middleware';
import { setRefreshCookie, clearRefreshCookie } from './cookie';
@ApiTags('auth')
@Controller('api/v1/auth')
export class AuthController {
constructor(
private readonly auth: AuthService,
private readonly csrf: CsrfMiddleware,
private readonly config: ConfigService,
) {}
@Public()
@Post('login')
@ApiOperation({ summary: 'Login with username and password' })
@ApiBody({ schema: { example: { username: 'admin', password: 'SuperSecret123!' } } })
@ApiResponse({ status: 200, description: 'Login successful' })
async login(
@Body(new ZodValidationPipe(LoginDtoSchema)) body: { username: string; password: string },
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
) {
const ip = (req.ip || req.socket.remoteAddress || 'unknown') as string;
const session = await this.auth.login(body, ip);
setRefreshCookie(res, session.refreshToken, this.config);
return {
accessToken: session.accessToken,
expiresIn: session.expiresIn,
user: session.user,
};
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Rotate the refresh token' })
async refresh(
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
@Body(new ZodValidationPipe(RefreshDtoSchema)) body: { refreshToken?: string },
) {
const fromCookie = (req.cookies?.['rt'] as string | undefined) ?? '';
const token = body.refreshToken ?? fromCookie;
if (!token) return { message: 'No refresh token' };
const session = await this.auth.refresh(token);
setRefreshCookie(res, session.refreshToken, this.config);
return {
accessToken: session.accessToken,
expiresIn: session.expiresIn,
user: session.user,
};
}
@Public()
@Post('logout')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Invalidate the current refresh token' })
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<void> {
const token = (req.cookies?.['rt'] as string | undefined) ?? '';
await this.auth.logout(token || undefined);
clearRefreshCookie(res);
}
@Public()
@Get('csrf')
@ApiOperation({ summary: 'Issue a CSRF token (sets csrf cookie, returns token)' })
@ApiResponse({ status: 200, schema: { example: { csrfToken: '...' } } })
csrfEndpoint(@Req() req: Request, @Res({ passthrough: true }) res: Response): { csrfToken: string } {
const token = this.csrf.setOrGetCsrfToken(req, res);
return { csrfToken: token };
}
}
+30
View File
@@ -0,0 +1,30 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { UserEntity } from '../../database/entities/user.entity';
import { RefreshTokenEntity } from '../../database/entities/refresh-token.entity';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './strategies/jwt.strategy';
import { AdminGuard } from '../../common/guards/admin.guard';
@Module({
imports: [
TypeOrmModule.forFeature([UserEntity, RefreshTokenEntity]),
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get<string>('JWT_ACCESS_SECRET'),
signOptions: { expiresIn: config.get<string>('JWT_ACCESS_TTL', '15m') },
}),
}),
],
providers: [AuthService, JwtStrategy, AdminGuard],
controllers: [AuthController],
exports: [AuthService, JwtModule, AdminGuard],
})
export class AuthModule {}
+184
View File
@@ -0,0 +1,184 @@
import {
Injectable,
OnModuleInit,
Logger,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, EntityManager } from 'typeorm';
import * as argon2 from 'argon2';
import * as crypto from 'crypto';
import { v4 as uuid } from 'uuid';
import { UserEntity } from '../../database/entities/user.entity';
import { RefreshTokenEntity } from '../../database/entities/refresh-token.entity';
import { ApiError } from '../../common/errors/api-error';
import { ERROR_CODES } from '../../common/errors/error-codes';
import { LoginBackoffService } from '../../common/services/login-backoff.service';
import { RegistrationRateLimitService } from '../../common/services/registration-rate-limit.service';
import { LoginDto, LoginResponse } from './dto/auth.dto';
import { validatePassword } from '../../common/utils/password-policy';
const REFRESH_TTL_SECONDS_DEFAULT = 7 * 24 * 60 * 60;
@Injectable()
export class AuthService implements OnModuleInit {
private readonly logger = new Logger(AuthService.name);
private refreshTtlSeconds = REFRESH_TTL_SECONDS_DEFAULT;
constructor(
@InjectRepository(UserEntity) private readonly users: Repository<UserEntity>,
@InjectRepository(RefreshTokenEntity) private readonly refreshTokens: Repository<RefreshTokenEntity>,
private readonly jwt: JwtService,
private readonly config: ConfigService,
private readonly dataSource: DataSource,
private readonly backoff: LoginBackoffService,
private readonly registrationRateLimit: RegistrationRateLimitService,
) {}
onModuleInit(): void {
const ttl = this.config.get<string>('JWT_REFRESH_TTL', '7d');
this.refreshTtlSeconds = this.parseTtl(ttl);
}
async login(dto: LoginDto, ip: string): Promise<LoginResponse> {
const blockedMs = this.backoff.isBlocked(ip, dto.username);
if (blockedMs > 0) {
throw new ApiError(ERROR_CODES.RATE_LIMITED, `Too many failed attempts. Try again in ${Math.ceil(blockedMs / 1000)}s.`, 429);
}
return this.dataSource.transaction(async (manager) => {
const user = await manager.findOne(UserEntity, { where: { username: dto.username } });
if (!user || user.status !== 'enabled') {
this.backoff.recordFailure(ip, dto.username);
throw new ApiError(ERROR_CODES.INVALID_CREDENTIALS, 'Invalid credentials', 401);
}
const ok = await argon2.verify(user.passwordHash, dto.password);
if (!ok) {
this.backoff.recordFailure(ip, dto.username);
throw new ApiError(ERROR_CODES.INVALID_CREDENTIALS, 'Invalid credentials', 401);
}
this.backoff.reset(ip, dto.username);
return this.mintSession(manager, user);
});
}
async refresh(oldRefreshToken: string): Promise<LoginResponse> {
const tokenHash = this.hashToken(oldRefreshToken);
return this.dataSource.transaction(async (manager) => {
const row = await manager.findOne(RefreshTokenEntity, { where: { tokenHash } });
if (!row) throw new ApiError(ERROR_CODES.TOKEN_REVOKED, 'Refresh token revoked', 401);
if (row.revokedAt) throw new ApiError(ERROR_CODES.TOKEN_REVOKED, 'Refresh token revoked', 401);
if (new Date(row.expiresAt).getTime() < Date.now()) throw new ApiError(ERROR_CODES.TOKEN_REVOKED, 'Refresh token expired', 401);
const user = await manager.findOne(UserEntity, { where: { id: row.userId } });
if (!user || user.status !== 'enabled') throw new ApiError(ERROR_CODES.UNAUTHORIZED, 'User not allowed', 401);
row.revokedAt = new Date().toISOString();
await manager.save(row);
return this.mintSession(manager, user);
});
}
async logout(refreshToken: string | undefined): Promise<void> {
if (!refreshToken) return;
const tokenHash = this.hashToken(refreshToken);
await this.dataSource.transaction(async (manager) => {
const row = await manager.findOne(RefreshTokenEntity, { where: { tokenHash } });
if (!row || row.revokedAt) return;
row.revokedAt = new Date().toISOString();
await manager.save(row);
});
}
async registerFirstAdmin(username: string, password: string, ip: string): Promise<LoginResponse> {
validatePassword(password, this.config);
if (!this.registrationRateLimit.isAllowed(ip)) {
throw new ApiError(ERROR_CODES.RATE_LIMITED, 'Too many registrations from this IP; try again later.', 429);
}
return this.dataSource.transaction(async (manager) => {
const adminCount = await manager.count(UserEntity, { where: { role: 'admin' } });
if (adminCount > 0) {
throw new ApiError(ERROR_CODES.SYSTEM_INITIALIZED, 'System already initialized', 409);
}
const existing = await manager.findOne(UserEntity, { where: { username } });
if (existing) throw new ApiError(ERROR_CODES.CONFLICT, 'Username already taken', 409);
const passwordHash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: this.config.get<number>('ARGON2_MEMORY_COST'),
timeCost: this.config.get<number>('ARGON2_TIME_COST'),
parallelism: this.config.get<number>('ARGON2_PARALLELISM'),
});
const user = manager.create(UserEntity, {
id: uuid(),
username,
passwordHash,
role: 'admin',
status: 'enabled',
});
await manager.save(user);
this.registrationRateLimit.record(ip);
return this.mintSession(manager, user);
});
}
/**
* Mint a fresh access JWT and a new refresh token row inside the supplied
* transaction. The refresh token (raw) is returned alongside the access
* token so the caller can set the HttpOnly cookie.
*/
private async mintSession(manager: EntityManager, user: UserEntity): Promise<LoginResponse> {
const accessToken = await this.signAccess(user);
const refreshToken = this.generateRefreshToken();
const tokenHash = this.hashToken(refreshToken);
const now = new Date();
const expires = new Date(now.getTime() + this.refreshTtlSeconds * 1000);
await manager.insert(RefreshTokenEntity, {
id: uuid(),
userId: user.id,
tokenHash,
issuedAt: now.toISOString(),
expiresAt: expires.toISOString(),
revokedAt: null,
});
return {
accessToken,
refreshToken,
expiresIn: this.accessTtlSeconds(),
user: { id: user.id, username: user.username, role: user.role },
};
}
private async signAccess(user: UserEntity): Promise<string> {
return this.jwt.signAsync({ sub: user.id, username: user.username, role: user.role });
}
private generateRefreshToken(): string {
return crypto.randomBytes(32).toString('base64url');
}
private hashToken(token: string): string {
return crypto.createHash('sha256').update(token).digest('hex');
}
private accessTtlSeconds(): number {
return this.parseTtl(this.config.get<string>('JWT_ACCESS_TTL', '15m'));
}
private parseTtl(ttl: string): number {
const m = /^(\d+)([smhd])$/.exec(ttl.trim());
if (!m) return 900;
const n = parseInt(m[1], 10);
const unit = m[2];
const mult = unit === 's' ? 1 : unit === 'm' ? 60 : unit === 'h' ? 3600 : 86400;
return n * mult;
}
}
+19
View File
@@ -0,0 +1,19 @@
import { Response } from 'express';
import { ConfigService } from '@nestjs/config';
export const REFRESH_COOKIE_NAME = 'rt';
export function setRefreshCookie(res: Response, token: string, config: ConfigService): void {
const tls = config.get<boolean>('TLS_ENABLED', false);
res.cookie(REFRESH_COOKIE_NAME, token, {
httpOnly: true,
sameSite: tls ? 'strict' : 'lax',
secure: tls,
path: '/api/v1/auth',
maxAge: 7 * 24 * 60 * 60 * 1000,
});
}
export function clearRefreshCookie(res: Response): void {
res.clearCookie(REFRESH_COOKIE_NAME, { path: '/api/v1/auth' });
}
+24
View File
@@ -0,0 +1,24 @@
import { z } from 'zod';
export const LoginDtoSchema = z.object({
username: z.string().min(1).max(64),
password: z.string().min(1).max(256),
});
export type LoginDto = z.infer<typeof LoginDtoSchema>;
export const RefreshDtoSchema = z.object({
refreshToken: z.string().min(1).optional(),
});
export type RefreshDto = z.infer<typeof RefreshDtoSchema>;
export const CsrfResponseDtoSchema = z.object({
csrfToken: z.string(),
});
export type CsrfResponseDto = z.infer<typeof CsrfResponseDtoSchema>;
export interface LoginResponse {
accessToken: string;
refreshToken: string;
expiresIn: number;
user: { id: string; username: string; role: 'admin' | 'player' };
}
@@ -0,0 +1,26 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';
export interface JwtPayload {
sub: string;
username: string;
role: 'admin' | 'player';
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get<string>('JWT_ACCESS_SECRET'),
});
}
async validate(payload: JwtPayload): Promise<JwtPayload> {
if (!payload?.sub) throw new UnauthorizedException();
return payload;
}
}
@@ -0,0 +1,33 @@
import { Injectable, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SettingEntity } from '../../database/entities/setting.entity';
@Injectable()
export class SettingsService {
constructor(@InjectRepository(SettingEntity) private readonly repo: Repository<SettingEntity>) {}
async get(key: string, fallback: string = ''): Promise<string> {
const row = await this.repo.findOne({ where: { key } });
return row?.value ?? fallback;
}
async set(key: string, value: string): Promise<void> {
await this.repo.upsert({ key, value }, ['key']);
}
async getAll(): Promise<Record<string, string>> {
const rows = await this.repo.find();
const out: Record<string, string> = {};
for (const r of rows) out[r.key] = r.value;
return out;
}
}
@Module({
imports: [TypeOrmModule.forFeature([SettingEntity])],
providers: [SettingsService],
exports: [SettingsService],
})
export class SettingsModule {}
@@ -0,0 +1,83 @@
import { Controller, Get, Sse, MessageEvent } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { interval, map, merge, mergeMap, Observable, startWith, defer } from 'rxjs';
import { Public } from '../../common/decorators/public.decorator';
import { SystemService } from './system.service';
import { EventStatusService } from '../../common/services/event-status.service';
import { SseHubService } from '../../common/services/sse-hub.service';
@ApiTags('system')
@Controller('api/v1')
export class SystemController {
constructor(
private readonly system: SystemService,
private readonly statusSvc: EventStatusService,
private readonly hub: SseHubService,
) {}
@Public()
@Get('bootstrap')
@ApiOperation({ summary: 'Public bootstrap payload used by the SPA on startup' })
bootstrap() {
return this.system.bootstrap();
}
@Public()
@Get('event/status')
@ApiOperation({ summary: 'Event status derived from UTC timestamps' })
eventStatus() {
return this.statusSvc.getStatus();
}
/**
* Global event status + countdown stream.
* Emits a FLATTENED object every second (and whenever the hub pushes).
*/
@Public()
@Sse('event/stream')
eventStream(): Observable<MessageEvent> {
const tick$ = interval(1000).pipe(
startWith(0),
mergeMap(() =>
defer(() =>
this.statusSvc.getStatus().then((s) => ({
status: s.status,
countdownMs: s.countdownMs,
serverNowUtc: s.serverNowUtc,
startUtc: s.startUtc,
endUtc: s.endUtc,
})),
),
),
);
const hub$ = this.hub.event$().pipe(
map((payload: any) => ({
status: payload?.status,
countdownMs: payload?.countdownMs,
serverNowUtc: payload?.serverNowUtc,
startUtc: payload?.startUtc,
endUtc: payload?.endUtc,
})),
);
return merge(tick$, hub$).pipe(map((src) => ({ data: src }) as MessageEvent));
}
/**
* Live solves stream.
* Emits a FLATTENED solve payload whenever a new solve is published.
*/
@Public()
@Sse('scoreboard/stream')
scoreboardStream(): Observable<MessageEvent> {
return this.hub.scoreboard$().pipe(
map((s: any) => ({
challengeId: s?.challengeId,
userId: s?.userId,
pointsAwarded: s?.pointsAwarded,
rankBonus: s?.rankBonus,
solvedAt: s?.solvedAt,
})),
map((src) => ({ data: src }) as MessageEvent),
);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from '../../database/entities/user.entity';
import { SettingEntity } from '../../database/entities/setting.entity';
import { SystemController } from './system.controller';
import { SystemService } from './system.service';
@Module({
imports: [TypeOrmModule.forFeature([UserEntity, SettingEntity])],
controllers: [SystemController],
providers: [SystemService],
})
export class SystemModule {}
@@ -0,0 +1,45 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '../../database/entities/user.entity';
import { SettingEntity } from '../../database/entities/setting.entity';
import { ThemeLoaderService } from '../../common/utils/theme-loader.service';
import { SETTINGS_KEYS } from '../../config/env.schema';
export interface BootstrapPayload {
initialized: boolean;
pageTitle: string;
logo: string;
welcomeMarkdown: string;
theme: any;
defaultChallengeIp: string;
registrationsEnabled: boolean;
}
@Injectable()
export class SystemService {
constructor(
@InjectRepository(UserEntity) private readonly users: Repository<UserEntity>,
@InjectRepository(SettingEntity) private readonly settings: Repository<SettingEntity>,
private readonly themes: ThemeLoaderService,
) {}
async bootstrap(): Promise<BootstrapPayload> {
const adminCount = await this.users.count({ where: { role: 'admin' } });
const themeKey = await this.getSetting(SETTINGS_KEYS.THEME_KEY, 'classic');
return {
initialized: adminCount > 0,
pageTitle: await this.getSetting(SETTINGS_KEYS.PAGE_TITLE, 'HIPCTF'),
logo: await this.getSetting(SETTINGS_KEYS.LOGO, ''),
welcomeMarkdown: await this.getSetting(SETTINGS_KEYS.WELCOME_MARKDOWN, ''),
theme: this.themes.getTheme(themeKey),
defaultChallengeIp: await this.getSetting(SETTINGS_KEYS.DEFAULT_CHALLENGE_IP, '127.0.0.1'),
registrationsEnabled: (await this.getSetting(SETTINGS_KEYS.REGISTRATIONS_ENABLED, 'false')) === 'true',
};
}
private async getSetting(key: string, fallback: string): Promise<string> {
const row = await this.settings.findOne({ where: { key } });
return row?.value ?? fallback;
}
}
@@ -0,0 +1,65 @@
import { Controller, Post, UseGuards, UseInterceptors, Req, HttpCode, HttpStatus, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiConsumes } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
import { AdminGuard } from '../../common/guards/admin.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { parseUploadSizeLimit, safeFilename } from '../../common/utils/upload';
@ApiTags('uploads')
@ApiBearerAuth()
@Controller('api/v1/uploads')
@UseGuards(AdminGuard)
@Roles('admin')
export class UploadsController {
private readonly uploadDir: string;
private readonly globalLimit: number;
constructor(private readonly config: ConfigService) {
this.uploadDir = path.resolve(this.config.get<string>('UPLOAD_DIR', '/data/hipctf/uploads'));
this.globalLimit = parseUploadSizeLimit(this.config.get<string>('UPLOAD_SIZE_LIMIT', '50mb'));
}
@Post('category-icon')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Upload a category icon (admin only)' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file'))
async uploadCategoryIcon(@Req() req: any) {
return this.handleUpload(req, 'icons');
}
@Post('challenge-file')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Upload a challenge attachment (admin only)' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file'))
async uploadChallengeFile(@Req() req: any) {
return this.handleUpload(req, 'challenges');
}
private handleUpload(req: any, subdir: string) {
const file = req.file as any;
if (!file) throw new BadRequestException('No file uploaded under field "file"');
if (file.size > this.globalLimit) {
throw new BadRequestException(`File exceeds UPLOAD_SIZE_LIMIT (${file.size} > ${this.globalLimit})`);
}
const safeName = safeFilename(file.originalname || 'file');
const finalDir = path.join(this.uploadDir, subdir);
if (!fs.existsSync(finalDir)) fs.mkdirSync(finalDir, { recursive: true });
const finalPath = path.join(finalDir, safeName);
// FileInterceptor uses memoryStorage; the bytes are in file.buffer.
fs.writeFileSync(finalPath, file.buffer);
const publicUrl = `/uploads/${subdir}/${safeName}`;
return {
id: safeName,
originalFilename: file.originalname,
storedPath: finalPath,
publicUrl,
size: file.size,
mimeType: file.mimetype,
};
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { UploadsController } from './uploads.controller';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [AuthModule],
controllers: [UploadsController],
})
export class UploadsModule {}
@@ -0,0 +1,7 @@
import { z } from 'zod';
export const CreateFirstAdminDtoSchema = z.object({
username: z.string().min(3).max(64),
password: z.string().min(1).max(256),
});
export type CreateFirstAdminDto = z.infer<typeof CreateFirstAdminDtoSchema>;
@@ -0,0 +1,36 @@
import { Body, Controller, Post, Req, Res } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { ConfigService } from '@nestjs/config';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { Public } from '../../common/decorators/public.decorator';
import { AuthService } from '../auth/auth.service';
import { CreateFirstAdminDtoSchema } from './dto/create-first-admin.dto';
import { setRefreshCookie } from '../auth/cookie';
@ApiTags('users')
@Controller('api/v1/auth')
export class UsersController {
constructor(
private readonly auth: AuthService,
private readonly config: ConfigService,
) {}
@Public()
@Post('register-first-admin')
@ApiOperation({ summary: 'Create the very first admin (only allowed when no admins exist)' })
async registerFirstAdmin(
@Body(new ZodValidationPipe(CreateFirstAdminDtoSchema)) body: { username: string; password: string },
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
) {
const ip = (req.ip || req.socket.remoteAddress || 'unknown') as string;
const session = await this.auth.registerFirstAdmin(body.username, body.password, ip);
setRefreshCookie(res, session.refreshToken, this.config);
return {
accessToken: session.accessToken,
expiresIn: session.expiresIn,
user: session.user,
};
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from '../../database/entities/user.entity';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [TypeOrmModule.forFeature([UserEntity]), AuthModule],
providers: [UsersService],
controllers: [UsersController],
exports: [UsersService],
})
export class UsersModule {}
@@ -0,0 +1,49 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { UserEntity, UserRole } from '../../database/entities/user.entity';
import { ApiError } from '../../common/errors/api-error';
import { ERROR_CODES } from '../../common/errors/error-codes';
type UserRepoLike = Repository<UserEntity> | EntityManager;
@Injectable()
export class UsersService {
constructor(@InjectRepository(UserEntity) private readonly repo: Repository<UserEntity>) {}
countAdmins(manager?: EntityManager): Promise<number> {
return this.getRepo(manager).count({ where: { role: 'admin' } });
}
findById(id: string, manager?: EntityManager): Promise<UserEntity | null> {
return this.getRepo(manager).findOne({ where: { id } });
}
listAll(): Promise<UserEntity[]> {
return this.repo.find({ order: { createdAt: 'ASC' } });
}
/**
* Verify, inside an open transaction, that demoting/deleting the given user
* would not leave the system with zero admins. Throws ApiError(LAST_ADMIN)
* if so. Must be invoked from a `dataSource.transaction(...)` callback.
*/
async enforceLastAdminInvariant(manager: EntityManager, targetId: string, nextRole?: UserRole): Promise<void> {
const repo = manager.getRepository(UserEntity);
const target = await repo.findOne({ where: { id: targetId } });
if (!target) throw ApiError.notFound('User not found');
const wouldDemoteOrDelete =
target.role === 'admin' && (nextRole === undefined || nextRole !== 'admin');
if (!wouldDemoteOrDelete) return;
const adminCount = await repo.count({ where: { role: 'admin' } });
if (adminCount <= 1) {
throw ApiError.conflict(ERROR_CODES.LAST_ADMIN, 'Cannot delete or demote the last admin');
}
}
private getRepo(manager?: EntityManager): Repository<UserEntity> {
return manager ? manager.getRepository(UserEntity) : this.repo;
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "classic",
"name": "Classic",
"tokens": {
"primary": "#3b82f6",
"secondary": "#64748b",
"accent": "#f59e0b",
"surface": "#ffffff",
"text": "#0f172a",
"success": "#10b981",
"warning": "#f59e0b",
"danger": "#ef4444",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "4px", "md": "8px", "lg": "16px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "midnight",
"name": "Midnight",
"tokens": {
"primary": "#6366f1",
"secondary": "#1e293b",
"accent": "#22d3ee",
"surface": "#0f172a",
"text": "#e2e8f0",
"success": "#34d399",
"warning": "#fbbf24",
"danger": "#f87171",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "4px", "md": "8px", "lg": "16px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "sunset",
"name": "Sunset",
"tokens": {
"primary": "#f97316",
"secondary": "#fb7185",
"accent": "#facc15",
"surface": "#fff7ed",
"text": "#431407",
"success": "#84cc16",
"warning": "#f59e0b",
"danger": "#dc2626",
"fontFamily": "Georgia, serif",
"radii": { "sm": "6px", "md": "12px", "lg": "24px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "forest",
"name": "Forest",
"tokens": {
"primary": "#16a34a",
"secondary": "#65a30d",
"accent": "#ca8a04",
"surface": "#f0fdf4",
"text": "#14532d",
"success": "#15803d",
"warning": "#ca8a04",
"danger": "#b91c1c",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "4px", "md": "8px", "lg": "12px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "cyber",
"name": "Cyber",
"tokens": {
"primary": "#00ffd5",
"secondary": "#ff00aa",
"accent": "#ffee00",
"surface": "#000000",
"text": "#00ffd5",
"success": "#00ff88",
"warning": "#ffee00",
"danger": "#ff0066",
"fontFamily": "Courier New, monospace",
"radii": { "sm": "0", "md": "0", "lg": "0" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "paper",
"name": "Paper",
"tokens": {
"primary": "#1f2937",
"secondary": "#6b7280",
"accent": "#0ea5e9",
"surface": "#fafaf9",
"text": "#1c1917",
"success": "#059669",
"warning": "#d97706",
"danger": "#b91c1c",
"fontFamily": "Georgia, serif",
"radii": { "sm": "2px", "md": "4px", "lg": "8px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "crimson",
"name": "Crimson",
"tokens": {
"primary": "#dc2626",
"secondary": "#991b1b",
"accent": "#fbbf24",
"surface": "#1f1f1f",
"text": "#fef2f2",
"success": "#22c55e",
"warning": "#fbbf24",
"danger": "#ef4444",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "4px", "md": "8px", "lg": "12px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "ocean",
"name": "Ocean",
"tokens": {
"primary": "#0ea5e9",
"secondary": "#06b6d4",
"accent": "#14b8a6",
"surface": "#f0f9ff",
"text": "#0c4a6e",
"success": "#10b981",
"warning": "#f59e0b",
"danger": "#ef4444",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "8px", "md": "16px", "lg": "24px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "neon",
"name": "Neon",
"tokens": {
"primary": "#a855f7",
"secondary": "#ec4899",
"accent": "#22d3ee",
"surface": "#0a0a0a",
"text": "#f5f3ff",
"success": "#4ade80",
"warning": "#fbbf24",
"danger": "#fb7185",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "4px", "md": "12px", "lg": "20px" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"id": "monochrome",
"name": "Monochrome",
"tokens": {
"primary": "#000000",
"secondary": "#525252",
"accent": "#a3a3a3",
"surface": "#ffffff",
"text": "#0a0a0a",
"success": "#404040",
"warning": "#737373",
"danger": "#171717",
"fontFamily": "system-ui, sans-serif",
"radii": { "sm": "0", "md": "0", "lg": "0" },
"spacingScale": [4, 8, 12, 16, 24, 32, 48]
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "test", "**/*.spec.ts"]
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"baseUrl": ".",
"strict": false,
"esModuleInterop": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true,
"declaration": false,
"removeComments": true,
"sourceMap": true,
"incremental": true,
"tsBuildInfoFile": "./dist/.tsbuildinfo"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "test"]
}