Skip to content

Enhanced Security Module 🔒 #149

@Villarley

Description

@Villarley

Issue: Enhanced Security Module 🔒

Description

The API lacks standard HTTP security headers, unified CORS policy, request throttling, and structured input hardening. This increases the risk of clickjacking, XSS, brute-force abuse, and information leakage.

What is expected

  • A dedicated SecurityModule that centralizes:
    • Helmet headers (HSTS, noSniff, frameguard, XSS filter where applicable).
    • CORS configuration with allowlist per environment.
    • Rate limiting for public routes.
    • Global validation (ValidationPipe) with whitelist/transform/forbidUnknownValues.
    • Request size limits (body parser).
  • Security config is environment-driven (production vs development).

What should be modified

  1. Create module & config
    • src/security/security.module.ts
    • src/security/security.config.ts (read from env: ALLOWED_ORIGINS, RATE_LIMIT_POINTS, RATE_LIMIT_DURATION, TRUST_PROXY, etc.).
  2. App bootstrap
    • In main.ts:
      • Add Helmet.
      • Add CORS using allowlist from config.
      • Add global ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }).
      • Set body size limits (e.g., json({ limit: process.env.BODY_LIMIT || '1mb' })).
      • Trust proxy if behind a load balancer (app.set('trust proxy', 1) when TRUST_PROXY=true).
  3. Rate limiting
    • Add @nestjs/throttler (or rate-limiter-flexible) via SecurityModule.
    • Default policy for public endpoints; allow per-route overrides (e.g., auth routes stricter).
  4. Content Security Policy (CSP)
    • Provide sane defaults via Helmet; allow overrides via env (CSP_DEFAULT_SRC, etc.).
  5. Env & examples
    • Update .env.example with:
      ALLOWED_ORIGINS=http://localhost:3000,https://yourapp.com
      RATE_LIMIT_POINTS=100
      RATE_LIMIT_DURATION=60
      BODY_LIMIT=1mb
      TRUST_PROXY=true
      
  6. Docs
    • Add a “Security” section to README.md explaining policies and how to tweak envs.

Acceptance criteria

  • All responses include Helmet headers (HSTS in production).
  • CORS allowlist enforced from env; requests from disallowed origins are rejected.
  • Global validation strips unknown fields and rejects invalid payloads.
  • Rate limiting returns 429 when limits are exceeded; limits configurable by env.
  • Body size limits enforced; oversized payloads return 413.
  • CI passes and app boots with npm run start:dev and in production mode with security enabled.

Metadata

Metadata

Assignees

Labels

onlydust-waveContribute to awesome OSS repos during OnlyDust's open source week

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions