'use strict';

const ecdsa = require('@starkbank/ecdsa');
const Ecdsa = ecdsa.Ecdsa;
const Signature = ecdsa.Signature;
const PublicKey = ecdsa.PublicKey;

class EventWebhook {
  /**
   *
   * @param {string} publicKey verification key under Mail Settings
   * @return {PublicKey} A public key using the ECDSA algorithm
   */
  convertPublicKeyToECDSA(publicKey) {
    return PublicKey.fromPem(publicKey);
  }

  /**
   *
   * @param {PublicKey} publicKey elliptic curve public key
   * @param {Object|string} payload event payload in the request body
   * @param {string} signature value obtained from the 'X-Twilio-Email-Event-Webhook-Signature' header
   * @param {string} timestamp value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
   * @return {Boolean} true or false if signature is valid
   */
  verifySignature(publicKey, payload, signature, timestamp) {
    let timestampPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
    timestampPayload = timestamp + timestampPayload;
    const decodedSignature = Signature.fromBase64(signature);

    return Ecdsa.verify(timestampPayload, decodedSignature, publicKey);
  }
}

module.exports = EventWebhook;

@@ -153,34 +153,251 @@
 y;%0A%0A
-class EventWebhook %7B%0A  /**
+/*%0A * This class allows you to use the Event Webhook feature. Read the docs for%0A * more details: https://sendgrid.com/docs/for-developers/tracking-events/event%0A */%0Aclass EventWebhook %7B%0A  /**%0A   * Convert the public key string to a ECPublicKey.
 %0A   
@@ -623,24 +623,67 @@
 %0A  %7D%0A%0A  /**%0A
+   * Verify signed event webhook requests.%0A
    *%0A   * @p

add missing summaries