{
  "name": "WhatSync: alert when WhatsApp disconnects",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsync-connection",
        "responseMode": "onReceived",
        "options": {
          "rawBody": true
        }
      },
      "name": "WhatsApp event",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "id": "7893d65f-7ced-4f50-acc4-1f7daed15c0e",
      "webhookId": "whatsync-whatsync-connection",
      "notes": "Answers WhatSync at once (it waits at most 10 seconds). Raw Body must stay on: the signature is checked on the exact bytes."
    },
    {
      "parameters": {
        "jsCode": "// Checks that the request really came from WhatSync before anything else runs.\n// WhatSync signs every event (Standard Webhooks): HMAC-SHA256 of \"id.timestamp.body\" with your signing secret.\n// Paste the signing secret of your webhook below. It starts with whsec_ and is shown when you add the webhook.\nconst SECRET = 'whsec_PASTE_YOUR_SIGNING_SECRET';\n\nconst item = $input.first();\nconst headers = item.json.headers || {};\nconst id = String(headers['webhook-id'] || '');\nconst timestamp = String(headers['webhook-timestamp'] || '');\nif (SECRET.includes('PASTE_YOUR')) throw new Error('Paste your WhatSync signing secret into the \"Verify signature\" node.');\nif (!id || !/^\\d+$/.test(timestamp)) throw new Error('Rejected: the WhatSync signature headers are missing.');\nif (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error('Rejected: this event is more than 5 minutes old.');\n\n// The exact bytes WhatSync sent. Needs \"Raw Body\" switched on in the Webhook node's options.\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data');\n\n// SHA-256 and HMAC in plain JavaScript: the Code node cannot load Node's crypto module unless the server allows it.\nconst K = [], H0 = [];\nfor (let n = 2; K.length < 64; n++) {\n  let prime = true;\n  for (let d = 2; d * d <= n; d++) if (n % d === 0) { prime = false; break; }\n  if (!prime) continue;\n  if (H0.length < 8) H0.push(Math.floor((Math.sqrt(n) % 1) * 4294967296) | 0);\n  K.push(Math.floor((Math.cbrt(n) % 1) * 4294967296) | 0);\n}\nfunction sha256(bytes) {\n  const length = bytes.length;\n  const padded = Buffer.alloc(((length + 72) >> 6) << 6);\n  Buffer.from(bytes).copy(padded);\n  padded[length] = 0x80;\n  padded.writeUInt32BE(Math.floor(length / 0x20000000), padded.length - 8);\n  padded.writeUInt32BE((length << 3) >>> 0, padded.length - 4);\n  const h = H0.slice(), w = new Array(64);\n  const rotr = (x, n) => (x >>> n) | (x << (32 - n));\n  for (let offset = 0; offset < padded.length; offset += 64) {\n    for (let t = 0; t < 16; t++) w[t] = padded.readInt32BE(offset + t * 4);\n    for (let t = 16; t < 64; t++) {\n      const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3);\n      const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10);\n      w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;\n    }\n    let [a, b, c, d, e, f, g, hh] = h;\n    for (let t = 0; t < 64; t++) {\n      const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;\n      const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n      hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n    }\n    [a, b, c, d, e, f, g, hh].forEach((value, i) => { h[i] = (h[i] + value) | 0; });\n  }\n  const out = Buffer.alloc(32);\n  h.forEach((value, i) => out.writeInt32BE(value, i * 4));\n  return out;\n}\nfunction hmacSha256(key, message) {\n  if (key.length > 64) key = sha256(key);\n  const inner = Buffer.alloc(64, 0x36), outer = Buffer.alloc(64, 0x5c);\n  for (let i = 0; i < key.length; i++) { inner[i] ^= key[i]; outer[i] ^= key[i]; }\n  return sha256(Buffer.concat([outer, sha256(Buffer.concat([inner, message]))]));\n}\n\nconst key = Buffer.from(SECRET.replace(/^whsec_/, ''), 'base64');\nconst expected = hmacSha256(key, Buffer.concat([Buffer.from(id + '.' + timestamp + '.'), raw]));\n// While a secret is being rotated WhatSync sends two signatures, separated by a space. Either may match.\nconst valid = String(headers['webhook-signature'] || '').split(' ').some((entry) => {\n  const [version, encoded] = entry.split(',');\n  const actual = Buffer.from(encoded || '', 'base64');\n  if (version !== 'v1' || actual.length !== expected.length) return false;\n  let difference = 0;\n  for (let i = 0; i < expected.length; i++) difference |= actual[i] ^ expected[i];\n  return difference === 0;\n});\nif (!valid) throw new Error('Rejected: the WhatSync signature does not match. Check the signing secret.');\n\n// From here on the item is the event itself: id, type, created_at, data.\nreturn [{ json: item.json.body }];\n"
      },
      "name": "Verify signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "id": "c35aab10-c20a-42fd-a469-a4875cbda0a4"
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "logic": "removeItemsWithAlreadySeenKeyValues",
        "dedupeValue": "={{ $json.id }}",
        "options": {
          "scope": "workflow",
          "historySize": 10000
        }
      },
      "name": "Skip repeats",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        440,
        0
      ],
      "id": "87796efc-a7b7-4cba-a3ec-ab18bf2588bb",
      "notes": "Remembers the last 10,000 event ids across runs and drops an event it has already seen."
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "06e34b19-3946-43cf-a332-851557025a81",
              "name": "alertUrl",
              "value": "https://hooks.slack.com/services/REPLACE/WITH/YOURS",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        660,
        0
      ],
      "id": "25054caf-db92-4679-ad9f-2273c531f443"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "39c2f1d1-dbcb-4fdd-aa9e-75d2d4bcd689",
              "leftValue": "={{ $json.type }}",
              "rightValue": "connection.disconnected",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Needs relinking?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        880,
        0
      ],
      "id": "0c1a7f7c-bb4a-4562-af6d-35929bfe1723"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings').first().json.alertUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'WhatsApp number +' + $json.data.phone + ' is disconnected (' + $json.data.reason + '). Nothing is received or sent until it is back. ' + ($json.data.action_needed === 'scan_qr' ? 'Link it again here: ' : 'Reconnect the Business number here: ') + $json.data.dashboard_url }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "name": "Alert: number disconnected",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        -100
      ],
      "id": "fefd3600-b9f7-4167-abfc-0b4670996dc2",
      "notes": "Works as is with a Slack incoming webhook. Swap this node for Email, Telegram or anything else that reaches a person."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "19e3c45c-cdc6-47e9-a707-31c19fb5f8ad",
              "leftValue": "={{ $json.type }}",
              "rightValue": "connection.connected",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Back online?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        120
      ],
      "id": "3289404e-3227-40f0-a849-8a29cc36ba83"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings').first().json.alertUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'WhatsApp number +' + $json.data.phone + ' is connected again.' }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "name": "Alert: number is back",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        120
      ],
      "id": "36611ea2-a055-4925-a732-a1a5c02e9275",
      "notes": "Works as is with a Slack incoming webhook. Swap this node for Email, Telegram or anything else that reaches a person."
    },
    {
      "parameters": {
        "content": "## Alert when a WhatsApp number disconnects\nA linked number can be logged out by the phone. Until someone links it again, nothing is received or sent, so an unattended setup needs this alert.\n\n**Set up**\n1. Paste your webhook signing secret into **Verify signature**.\n2. Put your alert URL in **Settings** (a Slack incoming webhook works as is).\n3. Publish, then add the production webhook URL in WhatSync > Developers with the events connection.disconnected and connection.connected.\n\nGuide: https://whatsync.app/docs/guides/disconnect-alert",
        "height": 250,
        "width": 560,
        "color": 4
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -330
      ],
      "id": "bad1f029-bfe8-4478-a609-75ffd3d5c5a1"
    }
  ],
  "connections": {
    "WhatsApp event": {
      "main": [
        [
          {
            "node": "Verify signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify signature": {
      "main": [
        [
          {
            "node": "Skip repeats",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip repeats": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Needs relinking?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Needs relinking?": {
      "main": [
        [
          {
            "node": "Alert: number disconnected",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Back online?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Back online?": {
      "main": [
        [
          {
            "node": "Alert: number is back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
