quentin-messagebird

Bird - Webhook signature verification nodeJS

Jul 5th, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import crypto from "crypto";
  2.  
  3. class SignedRequest {
  4.   constructor(requestSignature, requestTimestamp, requestBody, requestUrl) {
  5.     this._requestSignature = requestSignature;
  6.     this._requestTimestamp = requestTimestamp.toString();
  7.     this._requestBody = requestBody;
  8.     this._requestUrl = requestUrl;
  9.   }
  10.  
  11.   verify(signingKey) {
  12.     const payload = this._buildPayload();
  13.     const expectedSignature = Buffer.from(this._requestSignature, "base64");
  14.     const calculatedSignature = crypto
  15.       .createHmac("sha256", Buffer.from(signingKey, "latin1"))
  16.       .update(Buffer.from(payload, "latin1"))
  17.       .digest();
  18.     return expectedSignature.equals(calculatedSignature);
  19.   }
  20.  
  21.   _buildPayload() {
  22.     const checksumBody = crypto
  23.       .createHash("sha256")
  24.       .update(Buffer.from(this._requestBody, "latin1"))
  25.       .digest();
  26.     const strChecksumBody = checksumBody.toString("latin1");
  27.     const parts = [this._requestTimestamp, this._requestUrl, strChecksumBody];
  28.     return parts.join("\n");
  29.   }
  30. }
  31.  
  32. const sig = "lrv/39nhNz0qRfvAc/2cP8tqPpW1ZoRg8yqvM2WFDiA=";
  33. const timestamp = "1719823259";
  34. const body = {
  35.   service: "channels",
  36.   event: "whatsapp.outbound",
  37.   payload: {
  38.     id: "351fe763-99eb-4cc3-bd4c-1ce661fdc075",
  39.     channelId: "aeb8f6af-d330-467b-9778-835144431687",
  40.     sender: {
  41.       connector: {
  42.         id: "216852e9-5eaa-4c8c-b33c-572210004b9f",
  43.         identifierValue: "104587572718860",
  44.       },
  45.     },
  46.     receiver: {
  47.       contacts: [
  48.         {
  49.           id: "bfda0e99-9454-47d7-afc3-447e15642bf3",
  50.           identifierKey: "phonenumber",
  51.           identifierValue: "+33757909733",
  52.           annotations: { name: "Quentin Hausser" },
  53.           countryCode: "FR",
  54.         },
  55.       ],
  56.     },
  57.     reference: "",
  58.     status: "accepted",
  59.     reason: "",
  60.     lastStatusAt: "2024-07-01T08:40:58.363Z",
  61.     createdAt: "2024-07-01T08:40:58.363Z",
  62.     updatedAt: "2024-07-01T08:40:58.363Z",
  63.   },
  64. };
  65.  
  66. const url = "https://webhook.site/bb7e434b-2aeb-463c-82f5-6b05af10461e";
  67. const test = new SignedRequest(sig, timestamp, JSON.stringify(body), url);
  68. console.log(test.verify("thisiscryptos"));
  69.  
Add Comment
Please, Sign In to add comment