feat(security): add security hardening — Helmet, CORS, rate limiting, input sanitization

- Add Helmet with CSP, HSTS, referrer policy
- Configure CORS with environment-based origins
- Add global validation pipe with whitelist mode
- Add SanitizeInputMiddleware for XSS prevention
- Add ThrottlerBehindProxyGuard for rate limiting
- Add FileValidationPipe for upload security
- Set request body size limit to 1MB

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 02:04:13 +07:00
parent 5e44456d11
commit f3081d92fc
6 changed files with 197 additions and 1 deletions

View File

@@ -0,0 +1,17 @@
import { Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import type { Request } from 'express';
/**
* Extends ThrottlerGuard to extract real client IP behind reverse proxies
* (e.g., nginx, CloudFlare, AWS ALB) using X-Forwarded-For header.
*/
@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
protected override getTracker(req: Request): Promise<string> {
const forwarded = req.headers['x-forwarded-for'];
const ip =
typeof forwarded === 'string' ? (forwarded.split(',')[0]?.trim() ?? '127.0.0.1') : req.ip;
return Promise.resolve(ip ?? '127.0.0.1');
}
}