import request from 'supertest'; import type { INestApplication } from '@nestjs/common'; import { CookieAccessInfo } from 'cookiejar'; const csrfSkipPaths = new Set(['/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 { 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); }