import { INestApplication } from '@nestjs/common'; import { ValidationPipe } from '@nestjs/common'; import cookieParser from 'cookie-parser'; import { raw } from 'express'; import type { NextFunction, Request, Response } from 'express'; import { HttpErrorFilter } from './interface/http-exception.filter'; import { originGuard } from './interface/origin-guard'; // Shared setup for prod and tests: signed cookies, validation and a uniform // error filter. `sessionSecret` signs the auth session cookie, required so the // guard can read req.signedCookies. export function configureApp(app: INestApplication, sessionSecret: string): void { app.use(cookieParser(sessionSecret)); // Reject cross-site state-changing requests (CSRF), allowing only the // configured cross-origin clients (the shells, a dev frontend). const allowedOrigins = (process.env.CORS_ORIGINS ?? '') .split(',') .map((o) => o.trim()) .filter(Boolean); app.use(originGuard(allowedOrigins)); // Blob uploads are raw bytes; everything else under /api/blobs (diff) stays // JSON, so the raw parser only wraps PUTs. const rawParser = raw({ type: () => true, limit: `${process.env.MAX_UPLOAD_MB || 200}mb` }); app.use('/api/blobs', (req: Request, res: Response, next: NextFunction) => { if (req.method === 'PUT') return rawParser(req, res, next); next(); }); app.useGlobalPipes( new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true, transformOptions: { enableImplicitConversion: false }, }), ); app.useGlobalFilters(new HttpErrorFilter()); }