ZZZ Digital Lab

Back to n8n workflow hardening

after/main.json

{
  "id": "SYNTHETIC_MAIN_WORKFLOW_ID",
  "name": "SYNTHETIC - Hardened lead delivery",
  "active": false,
  "nodes": [
    {
      "id": "synthetic-webhook",
      "name": "Synthetic Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "synthetic-portfolio-leads",
        "responseMode": "lastNode",
        "authentication": "headerAuth",
        "options": {}
      },
      "webhookId": "synthetic-portfolio-webhook",
      "credentials": {
        "httpHeaderAuth": {
          "id": "SYNTHETIC_WEBHOOK_CREDENTIAL_ID",
          "name": "Configure locally - webhook"
        }
      }
    },
    {
      "id": "prepare-events",
      "name": "Prepare Events",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// SYNTHETIC. n8n Code node: Run Once for All Items. No external modules.\nconst MAX_BATCH = 50;\nconst input = $input.all();\nif (input.length !== 1) throw new Error('ONE_ENVELOPE_REQUIRED');\nconst envelope = input[0].json.body ?? input[0].json;\nconst events = envelope.events;\nif (!Array.isArray(events) || events.length === 0) throw new Error('EVENTS_REQUIRED');\nif (events.length > MAX_BATCH) throw new Error('BATCH_LIMIT');\nconst seen = new Map();\nconst output = [];\nfor (const event of events) {\n  if (!event || typeof event.event_id !== 'string' || typeof event.source !== 'string' ||\n      typeof event.customer_ref !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(event.event_id || '') ||\n      !/^[A-Za-z0-9_-]{1,32}$/.test(event.source || '') ||\n      !/^[A-Za-z0-9_-]{1,64}$/.test(event.customer_ref || '') ||\n      !Number.isSafeInteger(event.amount_minor) || event.amount_minor < 0 ||\n      event.amount_minor > 100000000 || event.currency !== 'USD') throw new Error('EVENT_SCHEMA');\n  const payload = {event_id:event.event_id, source:event.source, customer_ref:event.customer_ref,\n                   amount_minor:event.amount_minor, currency:event.currency};\n  const idempotencyKey = 'lead-event:v1:' + payload.source + ':' + payload.event_id;\n  const canonical = JSON.stringify(payload);\n  if (seen.has(idempotencyKey)) {\n    if (seen.get(idempotencyKey) !== canonical) throw new Error('IDEMPOTENCY_CONFLICT');\n    continue;\n  }\n  seen.set(idempotencyKey, canonical);\n  output.push({json:{synthetic:true,idempotencyKey,payload},pairedItem:{item:0}});\n}\nreturn output;\n"
      }
    },
    {
      "id": "deliver-event",
      "name": "Deliver Event",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        480,
        0
      ],
      "parameters": {
        "method": "PUT",
        "url": "={{ 'https://crm-receiver.example.invalid/events/' + encodeURIComponent($json.idempotencyKey) }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.idempotencyKey }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json }}",
        "options": {
          "timeout": 5000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 100
            }
          }
        }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "SYNTHETIC_DELIVER_EVENT_CREDENTIAL_ID",
          "name": "Configure locally - Deliver Event"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "onError": "continueErrorOutput"
    },
    {
      "id": "success",
      "name": "Success",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        740,
        -100
      ],
      "parameters": {}
    },
    {
      "id": "build-dead-letter",
      "name": "Build Dead Letter",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        740,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// SYNTHETIC. Run Once for All Items. Linked input identity must survive HTTP errors.\nreturn $input.all().map((item,index) => {\n  const original = $('Prepare Events').itemMatching(index).json;\n  if (!original?.idempotencyKey || !original.payload) throw new Error('DLQ_ORIGIN_MISSING');\n  return {json:{synthetic:true,dead_letter_key:'dlq:' + original.idempotencyKey,\n    idempotencyKey:original.idempotencyKey,payload:original.payload,\n    status:'awaiting_review',reason:'DELIVERY_RETRIES_EXHAUSTED',\n    execution_id:String($execution.id || 'synthetic-local')},pairedItem:{item:index}};\n});\n"
      }
    },
    {
      "id": "persist-dead-letter",
      "name": "Persist Dead Letter",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        980,
        100
      ],
      "parameters": {
        "method": "PUT",
        "url": "={{ 'https://dead-letter.example.invalid/records/' + encodeURIComponent($json.dead_letter_key) }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.dead_letter_key }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json }}",
        "options": {
          "timeout": 5000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 100
            }
          }
        }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "SYNTHETIC_PERSIST_DEAD_LETTER_CREDENTIAL_ID",
          "name": "Configure locally - Persist Dead Letter"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "onError": "stopWorkflow"
    },
    {
      "id": "delivery-failed",
      "name": "Delivery Failed",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        1220,
        100
      ],
      "parameters": {
        "errorMessage": "SYNTHETIC delivery failed; inspect dead-letter record"
      }
    }
  ],
  "connections": {
    "Synthetic Webhook": {
      "main": [
        [
          {
            "node": "Prepare Events",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Events": {
      "main": [
        [
          {
            "node": "Deliver Event",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Deliver Event": {
      "main": [
        [
          {
            "node": "Success",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Dead Letter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Dead Letter": {
      "main": [
        [
          {
            "node": "Persist Dead Letter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Persist Dead Letter": {
      "main": [
        [
          {
            "node": "Delivery Failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "executionTimeout": 300,
    "saveDataSuccessExecution": "none",
    "saveDataErrorExecution": "all",
    "errorWorkflow": "SYNTHETIC_ERROR_WORKFLOW_ID"
  },
  "pinData": {},
  "tags": []
}