Files
HIPCTF2/tests/backend/csrf-client.ts
T
OpenVelo Agent af3c24275d Scaffold HIPCTF platform (NestJS + Angular)
- Backend: NestJS 10 + TypeORM (better-sqlite3) feature-modular layout.
  - Entities: user, setting, category, challenge, challenge_file, solve,
    refresh_token, blog_post. Auto-run migrations + idempotent 6-system-
    category seed on startup.
  - Argon2id password hashing with policy check; JWT access + rotating
    refresh tokens (HttpOnly cookie); CSRF middleware (SameSite + custom
    X-CSRF-Token header); global JWT auth guard with @Public() opt-out;
    per-IP login backoff + per-IP registration rate limit.
  - Endpoints: auth (login/refresh/logout/csrf), users (first-admin
    registration), system (bootstrap/event status/SSE), admin (guarded
    user CRUD with last-admin invariant), frontend module (uploads +
    SPA fallback).
  - Security: helmet+CSP+HSTS-gated-by-TLS, CORS allowlist, structured
    global exception filter, Zod request validation pipes, OpenAPI 3.1
    served at /api/docs and /api/docs-json, 10 canonical themes under
    backend/themes/.
- Frontend: Angular 17 standalone components, lazy-loaded feature routes,
  signals, functional HttpInterceptorFn (csrf + auth), functional
  CanActivateFn auth guard, HttpOnly-cookie-based auth service.
- Tests: Jest + supertest, 46 tests across 13 suites covering
  migrations, env schema, theme loader, event status, login backoff,
  registration rate limit, ApiError shape, bootstrap integration,
  auth refresh rotation, admin guard, last-admin invariant, SSE flat
  payloads. Single-command runner: `npm test`.
2026-07-21 13:25:49 +00:00

46 lines
2.1 KiB
TypeScript

import request from 'supertest';
import type { INestApplication } from '@nestjs/common';
import { CookieAccessInfo } from 'cookiejar';
const csrfSkipPaths = new Set<string>(['/api/v1/auth/login', '/api/v1/auth/register-first-admin']);
function attachCsrfHeader(test: request.Test, method: string, path: string, agent: any): request.Test {
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method.toUpperCase())) return test;
if (csrfSkipPaths.has(path)) return test;
const jar = agent.jar;
if (!jar || typeof jar.getCookies !== 'function') return test;
const cookies: any[] = jar.getCookies(CookieAccessInfo.All);
if (process.env.CSRF_DEBUG) console.log('[csrf-client] all cookies in jar:', cookies.map((c: any) => ({ name: c.name, path: c.path })), 'for path', path);
const csrfCookie = cookies.find((c: any) => c.name === 'csrf');
if (!csrfCookie) return test;
const csrf = decodeURIComponent(csrfCookie.value ?? '');
if (csrf) test.set('X-CSRF-Token', csrf);
return test;
}
export function csrfClient(app: INestApplication): {
get: (path: string) => request.Test;
post: (path: string) => request.Test;
put: (path: string) => request.Test;
patch: (path: string) => request.Test;
delete: (path: string) => request.Test;
} {
const server = app.getHttpServer();
const agent = request.agent(server);
return {
get: (path: string) => agent.get(path),
post: (path: string) => attachCsrfHeader(agent.post(path), 'POST', path, agent),
put: (path: string) => attachCsrfHeader(agent.put(path), 'PUT', path, agent),
patch: (path: string) => attachCsrfHeader(agent.patch(path), 'PATCH', path, agent),
delete: (path: string) => attachCsrfHeader(agent.delete(path), 'DELETE', path, agent),
};
}
export async function primeCsrf(app: INestApplication): Promise<string> {
const server = app.getHttpServer();
const agent = request.agent(server);
const res = await agent.get('/api/v1/auth/csrf');
const cookieHeader = (res.headers['set-cookie'] as unknown as string[] | undefined)?.find((c) => c.startsWith('csrf='));
const token = cookieHeader ? cookieHeader.split(';')[0].split('=')[1] : '';
return decodeURIComponent(token);
}