Skip to content

Instantly share code, notes, and snippets.

@revant
Created October 20, 2019 10:47
Show Gist options
  • Save revant/c919ff93639c4927dc5b202aa6092dcd to your computer and use it in GitHub Desktop.
Save revant/c919ff93639c4927dc5b202aa6092dcd to your computer and use it in GitHub Desktop.
NestJS GithubWebHookGuard
// 2019 Revant Nandgaonkar
// License: MIT
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
import * as rawBody from 'raw-body';
@Injectable()
export class GithubWebHookGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
if (req.readable) {
const X_HUB_SIGNATURE = 'x-hub-signature';
const chunk = (await rawBody(req)).toString().trim();
const headerSignature = req.headers[X_HUB_SIGNATURE];
const signature = `sha1=${crypto
.createHmac('sha1', process.env.GITHUB_SECRET)
.update(chunk)
.digest('hex')}`;
return headerSignature === signature;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment