import { ForbiddenException } from '@nestjs/common'; import type { NextFunction, Request, Response } from 'express'; const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); // A same-origin check on state-changing requests, the second lock (with the // SameSite=strict cookie) against cross-site request forgery. A cross-site // browser always sends an Origin header on these methods; we allow the request // only when that origin matches the server's own host or an allowed one. A // request with no Origin is same-origin or a non-browser client and passes. export function originGuard(allowed: string[]) { const list = new Set(allowed); return (req: Request, _res: Response, next: NextFunction): void => { if (!UNSAFE.has(req.method)) return next(); const origin = req.get('origin'); if (!origin) return next(); if (list.has(origin)) return next(); try { // Same host is ours. Behind a reverse proxy the browser's host reaches // us in X-Forwarded-Host while req host is the internal one, so trust // the forwarded value first when present. const originHost = new URL(origin).host; const forwarded = (req.get('x-forwarded-host') ?? '').split(',')[0].trim(); if (originHost === forwarded || originHost === req.get('host')) return next(); } catch { // A malformed Origin is treated as a mismatch. } throw new ForbiddenException('Cross-origin request rejected'); }; }