@code-nl/shopify-hmac
Version:
Shopify HMAC lib to verify Shopify calls
60 lines (48 loc) • 1.51 kB
JavaScript
;
const { hmacTimingSafeEqual, getHmacFromString } = require("./hmac");
/**
* Get the request object translated into a string as of Shopify would have signed it.
*
* @param {Object} request The request object
* @return {String} The body contents as it would have been signed by Shopify
*/
exports.getSignableMessage = (request) => {
// get the contents
const message = request.rawBody.toString();
return message;
};
/**
* Generate a signature based on the request body.
*
* @param {Object} request The request object
* @param {String} secret API Secret
* @return {String} Generated HMAC
*/
exports.generate = (request, secret) => {
// get a signable message
const message = module.exports.getSignableMessage(request);
// generate hmac based on the message
const generatedHmac = getHmacFromString(message, secret, "base64");
return generatedHmac;
};
/**
* Verify request is from Shopify.
* HMAC verification based on the body payload that is transmitted.
*
* @param {Object} request The request object
* @param {String} secret API Secret
* @return bool
*/
exports.verify = (request, secret) => {
// get included hmac
const hmac = request.header('X-Shopify-Hmac-Sha256');
// guard: hmac is a required property
if (typeof hmac !== "string" || !hmac) {
return false;
}
// generate HMAC
const generatedHmac = module.exports.generate(request, secret);
// verify
const valid = hmacTimingSafeEqual(hmac, generatedHmac);
return valid;
};