Created
October 28, 2024 13:56
-
-
Save leonardo2204/30d82417a3d229667bc7efb88865887b to your computer and use it in GitHub Desktop.
Access raw body on Nestjs to verify payload x-hub-signature-256
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { NestFactory } from '@nestjs/core'; | |
| import { AppModule } from './app.module'; | |
| import { NestExpressApplication } from '@nestjs/platform-express'; | |
| async function bootstrap() { | |
| // you can use fastify https://docs.nestjs.com/faq/raw-body | |
| const app = await NestFactory.create<NestExpressApplication>(AppModule, { | |
| rawBody: true, | |
| }); | |
| await app.listen(process.env.PORT ?? 3000); | |
| } | |
| bootstrap(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common"; | |
| import * as crypto from 'crypto'; | |
| @Injectable() | |
| export class WhatsappGuard implements CanActivate { | |
| async canActivate(context: ExecutionContext): Promise<boolean> { | |
| const request = context.switchToHttp().getRequest(); | |
| const signature = request.headers['x-hub-signature-256']; | |
| const payload = request.rawBody; | |
| const hash = `sha256=${crypto.createHmac('sha256', process.env.FACEBOOK_APP_SECRET).update(payload).digest('hex')}`; | |
| if (signature && signature.length === hash.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(hash))) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment