@kontent-ai/webhook-helper
Version:
This utility helps with webhook notifications from Kontent.ai
35 lines • 1.45 kB
JavaScript
import { createHmac, timingSafeEqual } from "node:crypto";
import { parseWebhookResponse } from "../models/parse-webhook.js";
export const parseSignedWebhookResponse = ({ payload, secret, signature, }) => {
if (!isSignatureValid({ payload, secret, signature })) {
return { success: false, error: new Error("Webhook signature validation failed") };
}
try {
const parsedPayload = JSON.parse(payload);
return parseWebhookResponse(parsedPayload);
}
catch (error) {
return {
success: false,
error: new Error(`Failed to parse webhook payload: ${error instanceof Error ? error.message : "Invalid JSON"}`),
};
}
};
export const isSignatureValid = ({ payload, secret, signature }) => {
const expectedSignature = getHashFromString(replaceLinebreaks(payload), secret);
if (expectedSignature.length !== signature.length) {
return false;
}
try {
return timingSafeEqual(Buffer.from(expectedSignature, "utf8"), Buffer.from(signature, "utf8"));
}
catch (_a) {
return false;
}
};
const getHashFromString = (jsonPayload, secret) => createHmac("sha256", secret).update(jsonPayload, "utf8").digest("base64");
/**
* Normalizes line breaks in a string by replacing all line break variations with CRLF (`\r\n`).
*/
const replaceLinebreaks = (data) => data.replace(/[\r\n]+/gm, "\r\n");
//# sourceMappingURL=signature-helper.js.map