Last active
February 23, 2023 16:36
-
-
Save narenmanoharan/5083d1998c80586c8f470b21d15206eb to your computer and use it in GitHub Desktop.
Node example for a POST endpoint to consume wolfia webhooks
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
var express = require('express'); | |
var crypto = require('crypto'); | |
var router = express.Router(); | |
router.post('/', function (req, res, next) { | |
const isExpired = isWebhookExpired(req); | |
const isVerified = isWebhookVerified(req); | |
if (isVerified && !isExpired) { | |
processWebhook(req.body); | |
res.status(200).send('OK'); | |
} else if (isVerified && isExpired) { | |
res.status(400).send("Webhook expired"); | |
} else if (!isVerified) { | |
res.status(400).send("Invalid signature"); | |
} else { | |
res.status(400).send("Unknown error"); | |
} | |
}); | |
// Prevents man-in-the-middle attacks by verifying the signature | |
function isWebhookVerified(req) { | |
const body = req.body; | |
const validUntil = req.header("X-Wolfia-Until"); | |
const signature = req.header("X-Wolfia-Signature"); | |
return verifySignature(body, validUntil, signature); | |
} | |
// Prevents replay attacks by verifying the expiration date | |
function isWebhookExpired(req) { | |
const validUntil = req.header("X-Wolfia-Until"); | |
const validDateTime = new Date(validUntil * 1000); | |
const currentTime = new Date(); | |
return validDateTime < currentTime; | |
} | |
function verifySignature(body, validUntil, signature) { | |
const secret = "secret you entered when creating the webhook goes here" | |
const data = JSON.stringify(body) + "." + validUntil; | |
const hash = crypto.createHmac('sha256', secret).update(data).digest('hex'); | |
return hash === signature | |
} | |
function processWebhook(body) { | |
console.log("Received webhook: " + JSON.stringify(body, null, 2)); | |
switch (body.event) { | |
case "ios.appstore.review.started": | |
console.log(`Started review for version: ${body.cfBundleShortVersionString}.${body.cfBundleVersion}`) | |
// handle review start | |
break; | |
case "ios.appstore.review.completed": | |
console.log(`Completed review for version: ${body.cfBundleShortVersionString}.${body.cfBundleVersion}`) | |
// handle review complete | |
break; | |
default: | |
console.log("Unknown event: " + body.event) | |
} | |
} | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the schema of the webhook events:
And an example in json:
Also the associated headers for the post request: