Last active
July 29, 2022 02:41
-
-
Save n9iels/311734835e2ea4719cdbf6ca0d0ab78c to your computer and use it in GitHub Desktop.
Verify simple implementation to verify a GitHub webhook payload in TypeScript using NodeJs and Restify
This file contains 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 * as Restify from "restify" | |
import * as Crypto from "crypto" | |
type GithubWebRepository = { | |
id: number | |
name: string | |
full_name: string | |
private: boolean | |
git_url: string | |
ssh_url: string | |
} | |
type GitHubWebhookPayload = { | |
ref: string | |
repository: GithubWebRepository | |
} | |
// Webhook secret | |
const WEBHOOK_SECRET = "1234secret" | |
// Configure the server | |
const server = Restify.createServer(); | |
server.use(Restify.plugins.bodyParser()) | |
server.post('/', (req, res, next) => { | |
let body: GitHubWebhookPayload = req.body | |
let signature = req.header('X-Hub-Signature') | |
let event = req.header('X-GitHub-Event') | |
// Verify the signature | |
let hmac = Crypto.createHmac("sha1", WEBHOOK_SECRET) | |
let calculatedSignature = "sha1=" + hmac.update(JSON.stringify(req.body)).digest("hex"); | |
if (calculatedSignature !== signature) { | |
return res.send(401) | |
} | |
res.send(req.body) | |
}); | |
server.listen(80, function () { | |
console.log('%s listening at %s', server.name, server.url); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment