Verify Webhook

All requests are signed. A x-webhook-signature HTTP header contains a signature. You can verify this signature to be sure it’s INConnect which sent the request.

You can use the following code to verify signatures:

// time after the signature is reject
// ex: 24 hour is the max retry webhook retry strategy
const SIGN_TIMEOUT = 24 * 60 * 60 * 1000;

const verifySignature = function (endpoint, webhook, clientSecret, signature) {
    if (!webhook || !clientSecret || !clientSecret || !signature) {
        return false;
    }

    const match = /v=(\d+),d=([\da-f]+)/.exec(signature);
    if (!match) {
        return false;
    }

    const poststamp = Number(match[1]);
    const postDigest = match[2];

    const timestamp = Date.now();
    const difference = Math.abs(timestamp - poststamp);
    if (difference > SIGN_TIMEOUT) {
        return false;
    }

    const hmac = crypto.createHmac('SHA256', clientSecret);

    let webhookType = '';
    let webhookData = '';
    if (webhook.event) {
        if (webhook.event.eventId) {
            webhookType = webhook.event.eventId.toLowerCase();
        }
        if (webhook.event.data) {
            webhookData = JSON.stringify(webhook.event.data);
        }
    }
		
		hmac.update(`${endpoint}${webhook._id.toString()}${webhookType}${webhookData}`);

    const expectedSignature = hmac.digest('hex');
    return expectedSignature === postDigest;
};