{
  "id": "7sONHDdoh4XD1uHI",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Email Monitoring",
  "tags": [],
  "nodes": [
    {
      "id": "4e331916-ffab-4d8d-be64-0daa117a7294",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -704,
        528
      ],
      "parameters": {
        "color": 7,
        "width": 544,
        "height": 336,
        "content": "## DATA INGESTION\n\nMonitors the target inbox in real-time. \nWhen an email arrives, this section strips out all complex formatting, signatures and hidden trackers.\n\nGoal: Deliver pure, clean text to the AI to save tokens and improve analysis accuracy."
      },
      "typeVersion": 1
    },
    {
      "id": "2d670a91-d49d-4959-ac98-dd11ac8b9829",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -16,
        512
      ],
      "parameters": {
        "color": 7,
        "width": 720,
        "height": 560,
        "content": "##  AI INTELLIGENCE & PARSING\n\nThe core brain of the workflow. \nAI analyzes the email text in its native language (bypassing translation) and detects compliance risks.\n\nThe custom Code and Edit Fields nodes act as a safety net\u2014they use Regex and try/catch blocks to strictly parse the AI's output into valid JSON, preventing system crashes if the AI hallucinates."
      },
      "typeVersion": 1
    },
    {
      "id": "9694d200-c614-4129-93df-541e87cfa7dd",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        848,
        480
      ],
      "parameters": {
        "color": 7,
        "width": 464,
        "height": 400,
        "content": "##  Flagging Risky Mails\n\nRoutes the workflow execution based on the detected Risk Level (High, Medium, Low).\n\nIncludes a strict Filter safeguard: \"High Risk\" alerts are immediately dropped if the AI's confidence score is below 80%. \n\nGoal: Prevent false positives and filtering only risky emails"
      },
      "typeVersion": 1
    },
    {
      "id": "4b5d93e6-1f8f-45ec-903f-4b6dcf0a65ae",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1424,
        480
      ],
      "parameters": {
        "color": 7,
        "width": 720,
        "height": 400,
        "content": "## SECURE AUDIT & ALERTING\n\nCreates an immutable compliance trail. \n1. Generates a secure cryptographic Hash to mask PII in subject lines.\n2. Silently logs all incidents to a Google Sheet for quarterly audits.\n3. Converts AI reasoning to HTML and dispatches a high-priority alert to the compliance team."
      },
      "typeVersion": 1
    },
    {
      "id": "9f11dd71-5385-4667-a23d-73a2db65f28d",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1568,
        64
      ],
      "parameters": {
        "width": 768,
        "height": 912,
        "content": "# Email Monitoring and Risk Compliance \n\n### OVERVIEW\nThis workflow acts as an automated, multilingual security analyst. It continuously monitors a designated inbox for compliance risks such as fraud, data leaks or phishing attempts. When an email arrives, the workflow extracts the raw text and securely passes it to Google Gemini for native analysis. Gemini returns a structured JSON evaluation containing the risk type, severity level and a confidence score.\n\n### HOW IT WORKS\nIngestion: A Gmail trigger catches incoming mail and strips out messy HTML, leaving clean text.\n\nIntelligence: Gemini analyzes the content and assigns a Risk Level (High/Medium/Low). A dedicated Code node safely parses this output, ensuring the workflow never crashes even if the AI formatting varies.\n\nTraffic Control: A Switch node routes the data based on severity. A Filter node acts as a safeguard, dropping any \"High Risk\" alerts where the AI's confidence is below 80%, preventing false alarms and alert fatigue.\n\nAudit & Action: The system generates a cryptographically secure Incident ID to mask plain-text emails. It then permanently logs the incident details into a Google Sheet for compliance auditing before wrapping the AI's reasoning into an HTML email and alerting the security team.\n\n### SETUP INSTRUCTIONS\nCredentials: Authenticate your Google Workspace (Gmail/Sheets) and Google Gemini API.\n\nTrigger: Set the Gmail Trigger to listen to your specific compliance or support inbox.\n\nDatabase: Create a Google Sheet with columns for Incident_Hash, Incident_Time, Risk_Type and Risk_Confidence. Link it to the Google Sheets node.\n\nAlerts: Update the final Gmail node with your admin/security team's email address.\n\n### CORE BENEFITS\nMultilingual Native Analysis: Processes emails in any language without needing third-party translation tools.\n\nImmutable Audit Trail: Automatically builds a secure compliance log in Google Sheets.\n\nZero Alert Fatigue: Strict logic filtering ensures your team is only pinged for high-confidence threats.\n\nCost & Time Efficient: Replaces manual inbox monitoring with an intelligent, sub-second automated response system."
      },
      "typeVersion": 1
    },
    {
      "id": "87828b71-2826-45f3-8d7a-b68a63d35126",
      "name": "Google Gemini Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        48,
        928
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "799a14d8-a681-4a49-b997-3bf6b6f03eb3",
      "name": "Catch Incoming Emails",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -592,
        720
      ],
      "parameters": {
        "limit": 1,
        "simple": false,
        "filters": {},
        "options": {},
        "operation": "getAll"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "2a324218-d202-44dd-afff-53429f354ad4",
      "name": "Strip Email Formatting",
      "type": "n8n-nodes-base.html",
      "position": [
        -368,
        720
      ],
      "parameters": {
        "options": {},
        "operation": "extractHtmlContent",
        "dataPropertyName": "html",
        "extractionValues": {
          "values": [
            {
              "key": "clean_body",
              "cssSelector": "body"
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "038437ba-a758-4e4e-a17b-982f799b12f2",
      "name": "Analyze Compliance Risk",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        48,
        720
      ],
      "parameters": {
        "text": "=You are a multilingual compliance risk detection AI. \nAnalyze the following email text:\nSubject: {{ $('Catch Incoming Emails').item.json.subject }}\nBody: {{ $json.clean_body }}\n\nSTRICTLY return valid JSON only, translated into English for standard reporting:\n{\n  \"risk_type\": \"Fraud/Data Leak/Phishing/None\",\n  \"risk_level\": \"High/Medium/Low\",\n  \"confidence\": 0-100,\n  \"reason\": \"Brief explanation in Markdown format\"\n}",
        "options": {},
        "promptType": "define"
      },
      "typeVersion": 3.1
    },
    {
      "id": "6e5b5549-352d-4d9a-b250-0dd302ad5e2c",
      "name": "Clean & Parse AI Output",
      "type": "n8n-nodes-base.code",
      "position": [
        352,
        720
      ],
      "parameters": {
        "jsCode": "for (const item of $input.all()) {\n  let rawText = item.json.output || \"\";\n  let cleanString = \"\";\n  \n  // Step 1: Hunt down the JSON inside the text (Ignore Markdown)\n  const match = rawText.match(/\\{[\\s\\S]*\\}/);\n  \n  if (match) {\n    cleanString = match[0];\n  } else {\n    // Fallback if there are no brackets found\n    cleanString = rawText.replace(/```json/g, '').replace(/```/g, '').trim();\n  }\n  \n  // Step 2: Safely attempt to parse the clean string into an object\n  try {\n    item.json.parsed_data = JSON.parse(cleanString);\n  } catch (error) {\n    // Safe fallback if the AI hallucinates completely invalid JSON\n    item.json.parsed_data = {\n      \"risk_type\": \"Parse Error\",\n      \"risk_level\": \"Medium\",\n      \"confidence\": 0,\n      \"reason\": \"System Error: AI generated invalid JSON formatting. Manual review required.\"\n    };\n  }\n}\n\nreturn $input.all();"
      },
      "typeVersion": 2
    },
    {
      "id": "5d1cf672-85f0-407a-81a8-23c1f234f40b",
      "name": "Prep Variables for Routing",
      "type": "n8n-nodes-base.set",
      "position": [
        544,
        720
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "41ad59af-320d-413e-b6b8-291a10921a86",
              "name": "risk_type",
              "type": "string",
              "value": "={{ $json.parsed_data.risk_type }}"
            },
            {
              "id": "e6185c80-0e41-4d64-882e-621f1dce48f9",
              "name": "risk_level",
              "type": "string",
              "value": "={{ $json.parsed_data.risk_level }}"
            },
            {
              "id": "64a8001f-cfc4-450b-abf3-1d3328a2f932",
              "name": "confidence",
              "type": "number",
              "value": "={{ $json.parsed_data.confidence }}"
            },
            {
              "id": "6bd158cc-0986-4913-bc7f-8693a5cc1068",
              "name": "reason",
              "type": "string",
              "value": "={{ $json.parsed_data.reason }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "6ccc7849-44eb-461e-82e7-9b99ec88f1c6",
      "name": "Route by Risk Level",
      "type": "n8n-nodes-base.switch",
      "position": [
        896,
        704
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "48242fa0-0f4f-479d-9b76-8455615a3cdc",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.risk_level }}",
                    "rightValue": "High"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "f46b5ad4-c309-4328-8ad6-a43273954079",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.risk_level }}",
                    "rightValue": "Medium"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "5081e8b4-9797-4deb-8c4d-d4884f301c42",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.risk_level }}",
                    "rightValue": "Low"
                  }
                ]
              }
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.4
    },
    {
      "id": "41ee46a2-b6bc-48fb-a830-367b94cf7c34",
      "name": "Block Low-Confidence Alerts",
      "type": "n8n-nodes-base.filter",
      "position": [
        1152,
        688
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "12364f6c-6c06-4572-adc9-44c698fd7b22",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "leftValue": "={{ $('Clean & Parse AI Output').item.json.parsed_data.confidence }}",
              "rightValue": 80
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "58e5cf05-d294-4155-8bf5-da80dd7dcb18",
      "name": "Generate Secure Incident ID",
      "type": "n8n-nodes-base.crypto",
      "position": [
        1488,
        688
      ],
      "parameters": {
        "type": "SHA256",
        "value": "={{ $('Catch Incoming Emails').item.json.replyTo.value[0].address }} + {{ $('Catch Incoming Emails').item.json.headers.date }}",
        "dataPropertyName": "incident_hash"
      },
      "typeVersion": 1
    },
    {
      "id": "3cc70a5e-ef2a-4c13-93e2-41903059b5d6",
      "name": "Save to Audit Log",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1664,
        688
      ],
      "parameters": {
        "columns": {
          "value": {
            "Risk_Type": "={{ $('Clean & Parse AI Output').item.json.parsed_data.risk_type }}",
            "Incident_Hash": "={{ $json.incident_hash }}",
            "Incident_Time": "={{ $('Catch Incoming Emails').item.json.headers.date }}",
            "Risk_Confidence": "={{ $('Clean & Parse AI Output').item.json.parsed_data.confidence }}"
          },
          "schema": [
            {
              "id": "Incident_Time",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Incident_Time",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Incident_Hash",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Incident_Hash",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Risk_Type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Risk_Type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Risk_Confidence",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Risk_Confidence",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VqX5i22NJ5NaKzxl9zyg6vBSvNt8dPa6qKAoqO-DbJc/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1VqX5i22NJ5NaKzxl9zyg6vBSvNt8dPa6qKAoqO-DbJc",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1VqX5i22NJ5NaKzxl9zyg6vBSvNt8dPa6qKAoqO-DbJc/edit?usp=drivesdk",
          "cachedResultName": "compliance_logs"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "d819b4fb-3089-4081-80f3-edf0584595ec",
      "name": "Format AI Report",
      "type": "n8n-nodes-base.markdown",
      "position": [
        1840,
        688
      ],
      "parameters": {
        "html": "={{ $('Clean & Parse AI Output').item.json.parsed_data.reason }}",
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "35805598-6a09-4839-a23a-2fb8e615b838",
      "name": "Send Security Alert",
      "type": "n8n-nodes-base.gmail",
      "position": [
        2016,
        688
      ],
      "parameters": {
        "sendTo": "REPLACE_WITH_YOUR_EMAIL",
        "message": "=<div style=\"font-family: Arial, sans-serif; max-width: 600px; border: 2px solid #d9534f; border-radius: 8px; padding: 20px; background-color: #fdf7f7;\">   <h2 style=\"color: #d9534f; margin-top: 0;\"> Compliance Risk Detected</h2>      <table style=\"width: 100%; border-collapse: collapse; margin-bottom: 20px;\">     <tr>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"><strong>Incident ID:</strong></td>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\">{{ $json.Incident_Hash }}</td>     </tr>     <tr>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"><strong>Timestamp:</strong></td>   {{ $('Catch Incoming Emails').item.json.headers.date }}    <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"> </td>     </tr>     <tr>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"><strong>Risk Type:</strong></td>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"><span style=\"color: #d9534f; font-weight: bold;\">{{ $json.Risk_Type }}</span></td>     </tr>     <tr>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\"><strong>AI Confidence:</strong></td>       <td style=\"padding: 8px 0; border-bottom: 1px solid #ddd;\">{{ $json.Risk_Confidence }}%</td>     </tr>   </table>    <h3 style=\"color: #333;\"> AI Analysis & Reasoning:</h3>   <div style=\"background-color: #fff; padding: 15px; border: 1px solid #ccc; border-radius: 4px;\">   {{ $json.data }}   </div> </div>",
        "options": {},
        "subject": "=Alert!!! Incident Report: Risky Mail Found.."
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "2e2440b7-a32f-40be-b549-90f3584766a5",
      "name": "Start",
      "type": "n8n-nodes-base.manualTrigger",
      "position": [
        -832,
        720
      ],
      "parameters": {},
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "a99b72e2-2531-40d3-8431-abda01f35e43",
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Catch Incoming Emails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format AI Report": {
      "main": [
        [
          {
            "node": "Send Security Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save to Audit Log": {
      "main": [
        [
          {
            "node": "Format AI Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route by Risk Level": {
      "main": [
        [
          {
            "node": "Block Low-Confidence Alerts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Catch Incoming Emails": {
      "main": [
        [
          {
            "node": "Strip Email Formatting",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Strip Email Formatting": {
      "main": [
        [
          {
            "node": "Analyze Compliance Risk",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Compliance Risk": {
      "main": [
        [
          {
            "node": "Clean & Parse AI Output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean & Parse AI Output": {
      "main": [
        [
          {
            "node": "Prep Variables for Routing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Analyze Compliance Risk",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Prep Variables for Routing": {
      "main": [
        [
          {
            "node": "Route by Risk Level",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Block Low-Confidence Alerts": {
      "main": [
        [
          {
            "node": "Generate Secure Incident ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Secure Incident ID": {
      "main": [
        [
          {
            "node": "Save to Audit Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}