merit-webhook-verification
v1.0.1
Published
Helps to verify that the message came from Merit's webhook
Maintainers
Readme
Merit Webhook Signature Verification
A lightweight and easy-to-use Node.js library for verifying Merit webhook signatures.
Installation
Install the package with npm:
npm install merit-webhook-verificationOr with yarn:
yarn add merit-webhook-verificationUsage
The package exports a single function verifyMeritWebhookSignature that you can use to verify the signature of a Merit webhook request.
Here's an example of how to use it in an Express.js application:
import express from 'express';
import verifyMeritWebhookSignature from 'merit-webhook-verification';
const app = express();
// It's important to use the raw request body, so we disable the default JSON parser for this route
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const xMeritSignature = req.headers['x-merit-signature'];
const rawRequestBody = req.body.toString();
const secretKey = process.env.MERIT_WEBHOOK_SECRET_KEY; // It's recommended to store the secret key in an environment variable
try {
const isVerified = verifyMeritWebhookSignature(rawRequestBody, xMeritSignature, secretKey);
if (isVerified) {
// Signature is valid, process the webhook
console.log('Webhook verified successfully');
res.status(200).send('Webhook received');
} else {
// Signature is invalid
console.log('Webhook verification failed');
res.status(400).send('Invalid signature');
}
} catch (error) {
console.error('Error verifying webhook:', error);
res.status(500).send('Internal server error');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});verifyMeritWebhookSignature(rawRequestBody, xMeritSignature, secretKey)
rawRequestBody(string): The raw request body from the webhook. It's crucial to use the raw body, not a parsed one.xMeritSignature(string): The value of theX-Merit-Signatureheader from the request.secretKey(string): Your Merit webhook secret key.
The function returns true if the signature is valid and false otherwise.
Signature Verification
The library verifies the signature by:
- Parsing the
t(timestamp) andvX(signature) values from theX-Merit-Signatureheader. - Creating a signature payload by concatenating the timestamp and the raw request body with a comma:
${timestamp},${rawRequestBody}. - Calculating an HMAC-SHA256 signature of the payload using your secret key.
- Comparing the calculated signature with the signature(s) from the header.
License
This project is licensed under the ISC License.
