HMAC Verification

To verify that the request is legitimate, you may generate a HMAC of the webhook and compare it with the one included in the fuse-verification request header.

See below for an example implementation of verifying a webhook request.

  /**
   * Check whether a webhook is a legitimate Fuse webhook 
   * @param fuseApiKey 
   * @param webhook 
   * @param fuseVerificationHeader 
   * @returns A {@link boolean}
   */

requestIsFromFuse = (
    fuseApiKey: any,
    webhook: any,
    fuseVerificationHeader: string
  ) => {
    const replacer = (key: any, value: any) =>
      value instanceof Object && !(value instanceof Array)
        ? Object.keys(value)
            .sort()
            .reduce((sorted, key) => {
              sorted[key] = value[key];
              return sorted;
            }, {})
        : value;

    const requestJson = JSON.stringify(webhook, replacer);
    const dataHmac = this.hmacSignature(apiKey, requestJson, "base64");

    return crypto.timingSafeEqual(
      Buffer.from(requestHmac),
      Buffer.from(dataHmac)
    );
  };

hmacSignature = (key: any, msg: any, algorithm: string) => {
  return crypto.createHmac("sha256", key).update(msg).digest(algorithm);
};