middleware for setting security headers

This commit is contained in:
smart_ex 2022-04-12 19:26:03 +10:00
parent ac2e142cf0
commit ee9ae05983
3 changed files with 23 additions and 8 deletions

View File

@ -1,8 +1,9 @@
import { Module } from '@nestjs/common'; import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { baseConfig } from '@/config'; import { baseConfig } from '@/config';
import { QueueModule, ApiModule } from '@/modules'; import { QueueModule, ApiModule } from '@/modules';
import { setHeadersMiddleware } from '@/modules/api/set-headers.middleware';
@Module({ @Module({
imports: [ imports: [
@ -14,4 +15,8 @@ import { QueueModule, ApiModule } from '@/modules';
QueueModule, QueueModule,
], ],
}) })
export class AppModule {} export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(setHeadersMiddleware).forRoutes('/');
}
}

View File

@ -1,4 +1,4 @@
import { Controller, Body, Param, Res, Get, Post, HttpStatus } from '@nestjs/common'; import { Body, Controller, Get, HttpStatus, Param, Post, Res } from '@nestjs/common';
import { Response } from 'express'; import { Response } from 'express';
import { ApiService } from './api.service'; import { ApiService } from './api.service';
@ -9,13 +9,13 @@ export class ApiController {
constructor(private readonly service: ApiService) {} constructor(private readonly service: ApiService) {}
@Get('/status') @Get('/status')
async status(): Promise<Status> { async status(@Res() res: Response): Promise<Response<Status>> {
return await this.service.status(); return res.json(await this.service.status());
} }
@Get('/') @Get('/')
async root(): Promise<string> { root(@Res() res: Response): Response<string> {
return this.service.root(); return res.send(this.service.root());
} }
@Get('/job/:jobId') @Get('/job/:jobId')
@ -25,7 +25,6 @@ export class ApiController {
if (!job) { if (!job) {
return res.status(HttpStatus.BAD_REQUEST).json({ error: "The job doesn't exist" }); return res.status(HttpStatus.BAD_REQUEST).json({ error: "The job doesn't exist" });
} }
return res.json(job); return res.json(job);
} }

View File

@ -0,0 +1,11 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class setHeadersMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
}
}