{
  "name": "Huga — receber eventos (assinatura conferida, separados por evento)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "hugi-eventos",
        "responseMode": "lastNode",
        "options": {
          "rawBody": true
        }
      },
      "id": "00000000-0000-0000-0000-000000000001",
      "name": "Huga (webhook)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        200,
        300
      ],
      "webhookId": "00000000-0000-0000-0000-0000000003e9"
    },
    {
      "parameters": {
        "jsCode": "// Confere a assinatura do Huga (HMAC-SHA256 do corpo CRU) antes de qualquer outro passo.\n// Troque SEGREDO pelo segredo do endpoint: Huga -> Integrações e API -> Webhooks.\n// No n8n self-hosted, o módulo crypto precisa estar liberado: NODE_FUNCTION_ALLOW_BUILTIN=crypto\nconst crypto = require('crypto');\nconst SEGREDO = 'COLE_AQUI_O_SEGREDO_DO_ENDPOINT';\n\nfunction conferir(corpoCru, recebida) {\n  const esperada = 'sha256=' + crypto.createHmac('sha256', SEGREDO).update(corpoCru, 'utf8').digest('hex');\n  const a = Buffer.from(String(recebida || ''));\n  const b = Buffer.from(esperada);\n  // Tamanhos diferentes fazem timingSafeEqual lançar; conferir antes.\n  return a.length === b.length && crypto.timingSafeEqual(a, b);\n}\n\nconst saida = [];\nconst itens = $input.all();\nfor (let i = 0; i < itens.length; i++) {\n  const h = itens[i].json.headers || {};\n  // O corpo CRU vem do binário (opção \"Raw Body\" do Webhook). Reserializar o JSON já lido\n  // mudaria os bytes e a assinatura nunca bateria.\n  const corpoCru = (await this.helpers.getBinaryDataBuffer(i, 'data')).toString('utf8');\n  if (!conferir(corpoCru, h['x-hugi-signature-256'])) {\n    throw new Error('Assinatura do Huga inválida: esta chamada não veio do Huga (ou o segredo está errado).');\n  }\n  saida.push({\n    json: {\n      evento: h['x-hugi-evento'] || null,\n      // Mesma em toda repetição da entrega: use como chave para não processar duas vezes.\n      entrega: h['x-hugi-entrega'] || null,\n      corpo: JSON.parse(corpoCru),\n    },\n  });\n}\nreturn saida;\n"
      },
      "id": "00000000-0000-0000-0000-000000000002",
      "name": "Conferir assinatura",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        300
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.evento }}",
                    "rightValue": "mensagem.recebida",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "mensagem.recebida"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.evento }}",
                    "rightValue": "mensagem.recibo",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "mensagem.recibo"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.evento }}",
                    "rightValue": "mensagem.transcrita",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "mensagem.transcrita"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.evento }}",
                    "rightValue": "atendimento.aberto",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "atendimento.aberto"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.evento }}",
                    "rightValue": "atendimento.finalizado",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "atendimento.finalizado"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "outro evento"
        }
      },
      "id": "00000000-0000-0000-0000-000000000003",
      "name": "Separar por evento",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        660,
        300
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000a",
      "name": "Seu passo: mensagem.recebida",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        100
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000b",
      "name": "Seu passo: mensagem.recibo",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        220
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000c",
      "name": "Seu passo: mensagem.transcrita",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        340
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000d",
      "name": "Seu passo: atendimento.aberto",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        460
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000e",
      "name": "Seu passo: atendimento.finalizado",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        580
      ]
    },
    {
      "parameters": {},
      "id": "00000000-0000-0000-0000-00000000000f",
      "name": "Seu passo: outro evento",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        900,
        700
      ]
    }
  ],
  "connections": {
    "Huga (webhook)": {
      "main": [
        [
          {
            "node": "Conferir assinatura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Conferir assinatura": {
      "main": [
        [
          {
            "node": "Separar por evento",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Separar por evento": {
      "main": [
        [
          {
            "node": "Seu passo: mensagem.recebida",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Seu passo: mensagem.recibo",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Seu passo: mensagem.transcrita",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Seu passo: atendimento.aberto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Seu passo: atendimento.finalizado",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Seu passo: outro evento",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "active": false,
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
