Skip to content

Instantly share code, notes, and snippets.

@leonardo2204
Created October 28, 2024 13:56
Show Gist options
  • Select an option

  • Save leonardo2204/30d82417a3d229667bc7efb88865887b to your computer and use it in GitHub Desktop.

Select an option

Save leonardo2204/30d82417a3d229667bc7efb88865887b to your computer and use it in GitHub Desktop.
Access raw body on Nestjs to verify payload x-hub-signature-256
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();
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