{
  "name": "Vexday | T00 - Análise de CVE (v0.3)",
  "nodes": [
    {
      "name": "Formulário",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [
        0,
        0
      ],
      "webhookId": "c6b0c12b-9252-40a2-8a35-4270993eff54",
      "parameters": {
        "authentication": "basicAuth",
        "formTitle": "Vexday | Análise de CVE",
        "formDescription": "Informe um CVE-ID. Sai um relatório com prioridade, exploração, atores, alertas gov.br, impacto na sua stack, uso por ransomware, mitigação e detecção.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "CVE",
              "placeholder": "CVE-2024-3400",
              "requiredField": true
            },
            {
              "fieldLabel": "Idioma",
              "fieldType": "dropdown",
              "fieldOptions": {
                "values": [
                  {
                    "option": "pt"
                  },
                  {
                    "option": "en"
                  },
                  {
                    "option": "es"
                  }
                ]
              }
            }
          ]
        },
        "responseMode": "lastNode",
        "options": {
          "buttonLabel": "Analisar"
        }
      },
      "id": "d313583e-86ce-4f75-52b5-6f6670dedc91"
    },
    {
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        220
      ],
      "webhookId": "bd2f9441-81d5-f91a-06e2-1650cab35399",
      "parameters": {
        "httpMethod": "POST",
        "path": "vexday-t00-cve",
        "authentication": "headerAuth",
        "responseMode": "lastNode",
        "options": {
          "responseData": "firstEntryJson"
        }
      },
      "id": "05c96915-9dae-4ec1-d9f6-c560bb032dfe"
    },
    {
      "name": "Config",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        100
      ],
      "parameters": {
        "mode": "manual",
        "includeOtherFields": false,
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "eb827e89-ab3b-6d59-ceff-783ac1ca2f5e",
              "name": "vexday_mcp_url",
              "value": "https://api.vexday.io/mcp",
              "type": "string"
            },
            {
              "id": "ed2b0c7a-f9e8-7edf-61e8-5b1dcb79717b",
              "name": "lang_padrao",
              "value": "pt",
              "type": "string"
            },
            {
              "id": "66e6c627-5ffd-d558-a8ea-57ed101f990c",
              "name": "canais",
              "value": "[]",
              "type": "string"
            }
          ]
        }
      },
      "id": "b4dc6464-6c23-e750-fa6f-fc663296eceb"
    },
    {
      "name": "Valida entrada",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        100
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\n// Normaliza a entrada do Formulário ou do Webhook e valida o CVE-ID.\nconst cfg = $('Config').first().json;\nconst ran = (n) => { try { return $(n).isExecuted; } catch (e) { return false; } };\nconst fromWebhook = ran('Webhook');\nconst j = fromWebhook ? $('Webhook').first().json : $('Formulário').first().json;\n\nconst raw = fromWebhook ? (j.body?.cve_id ?? j.body?.cve ?? '') : (j['CVE'] ?? '');\nconst langIn = fromWebhook ? j.body?.lang : j['Idioma'];\nconst cve_id = String(raw).trim().toUpperCase();\nconst lang = ['pt', 'en', 'es'].includes(langIn) ? langIn : (cfg.lang_padrao || 'pt');\nconst valid = /^CVE-\\d{4}-\\d{4,}$/.test(cve_id);\n\nreturn [{ json: {\n  source: fromWebhook ? 'webhook' : 'form',\n  cve_id, lang, valid,\n  erro: valid ? null : `\"${String(raw).slice(0, 60)}\" não é um CVE-ID válido (formato CVE-AAAA-NNNN).`,\n} }];\n"
      },
      "id": "6cd33f17-2a37-9f6d-0551-c62152e6af51"
    },
    {
      "name": "CVE válido?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        680,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "10379c04-4c03-f309-8f0d-69260ebb8aa9",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "209b651b-3008-8ddf-12d9-aa3d19be3678"
    },
    {
      "name": "Vexday MCP get_cve",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        900,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.vexday_mcp_url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.rpc }}",
        "options": {
          "timeout": 45000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 2200
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "c04f46fc-c7ab-f9e3-16a5-2193f0f0bfea"
    },
    {
      "name": "Vexday MCP check_stack",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1120,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.vexday_mcp_url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.rpc }}",
        "options": {
          "timeout": 45000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 2200
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "a7272789-9554-0b37-a326-6a61d1b08913"
    },
    {
      "name": "Pede get_cve",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        790,
        -120
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\nconst v = $input.first().json;\nreturn [mcpReq('get_cve', { cve_id: v.cve_id, lang: v.lang })];\n"
      },
      "id": "bbac99e8-e7a3-f56e-4eb6-7515a7f1e9d6"
    },
    {
      "name": "Pede check_stack",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1010,
        -120
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\nreturn [mcpReq('check_cve_against_my_stack', { cve_id: $('Valida entrada').first().json.cve_id })];\n"
      },
      "id": "c2a4e782-488e-335e-465d-b1724ad2960e"
    },
    {
      "name": "Pede ransomware",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1230,
        -120
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\nconst v = $('Valida entrada').first().json;\nreturn [mcpReq('find_ransomware_by_cve', { cve_id: v.cve_id, lang: v.lang })];\n"
      },
      "id": "b609e175-7160-b8a9-c71a-eeb1a5698bd4"
    },
    {
      "name": "Vexday MCP ransomware",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.vexday_mcp_url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.rpc }}",
        "options": {
          "timeout": 45000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 2200
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "84b3c841-fd80-fc6b-68ba-ebe85bfd6266"
    },
    {
      "name": "Monta relatório",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        100
      ],
      "parameters": {
        "jsCode": "// Vexday | T00 - Monta o relatório a partir das respostas do MCP.\n// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\n\nconst inp = $('Valida entrada').first().json;\nconst cfg = $('Config').first().json;\nconst canais = cfgJson(cfg, 'canais', []);\nfunction parseMcp(nodeName, tool) {\n  let resp;\n  try { resp = $(nodeName).first().json; } catch (e) { return { err: `${tool} não executou.`, fatal: true }; }\n  return parseMcpResp(resp, tool);\n}\n\nfunction out(o) { return [{ json: o }]; }\n\nfunction erro(msg) {\n  return out({\n    ok: false,\n    source: inp.source,\n    report: { ok: false, cve_id: inp.cve_id || null, erro: msg },\n    html: page('Erro', `<h1>Não foi possível analisar</h1><div class=\"err\">${esc(msg)}</div>`),\n    markdown: null,\n    notifyItems: [],\n  });\n}\n\n// ---------- validação e consultas ----------\nif (!inp.valid) return erro(inp.erro);\n\nconst cveR = parseMcp('Vexday MCP get_cve', 'get_cve');\nif (cveR.err) return erro(cveR.err);\nconst c = cveR.data.data || {};\nconst stR = parseMcp('Vexday MCP check_stack', 'check_cve_against_my_stack');\nconst rwR = parseMcp('Vexday MCP ransomware', 'find_ransomware_by_cve');\n\nconst lang = inp.lang;\nconst i18n = c.i18n?.[lang] || c.i18n?.pt || c.i18n?.en || {};\nconst deep = c.deep || null;\nconst risk = c.risk || {};\n\n// inventário por versão (só existe se a conta tiver inventário cadastrado)\nlet invResumo = null;\nconst inv = stR.data?.inventory;\nif (Array.isArray(inv) && inv.length) {\n  invResumo = inv.reduce((acc, a) => { const s = a.state || 'desconhecido'; acc[s] = (acc[s] || 0) + 1; return acc; }, {});\n}\n\nconst rep = {\n  ok: true,\n  cve_id: c.cve_id,\n  titulo: c.title,\n  url: `https://vexday.io/${lang}/cve/${c.cve_id}`,\n  resumo: i18n.summary_short || c.description_en || null,\n  veredito: { score: risk.score ?? null, faixa: risk.band ?? null, ssvc: risk.ssvc ?? null, maturidade: risk.maturity ?? null },\n  cvss: { score: num(c.cvss_score), severidade: c.cvss_severity || null, vetor: c.cvss_vector || null, versao: c.cvss_version || null },\n  epss: { score: num(c.epss_score), percentil: num(c.epss_percentile), atualizado: c.epss_updated || null },\n  exploracao: {\n    kev_cisa: !!c.in_kev, kev_desde: day(c.kev_date_added), kev_prazo: day(c.kev_due_date),\n    kev_ransomware: !!c.kev_ransomware, kev_acao: c.kev_required_action || null,\n    vulncheck_kev: !!c.vulncheck_kev, ssvc_exploitation: c.ssvc_exploitation || null,\n    poc_publica: !!c.has_public_poc, pocs_total: c.pocs_total ?? (c.pocs || []).length,\n    primeira_poc: day(c.first_poc_date), metasploit: !!c.has_metasploit, nuclei: !!c.has_nuclei,\n    exploits: (c.exploits || []).map((e) => ({ fonte: e.source, nome: e.name, url: e.url })),\n    pocs_top: (c.pocs || []).slice(0, 5).map((p) => ({ fonte: p.source, titulo: p.title, url: p.url, verificada: p.verified })),\n  },\n  atores: (c.actors || []).map((a) => ({ nome: a.name, tipo: a.actor_type, origem: a.origin, confianca: a.confidence, fonte: a.source })),\n  alertas_gov: (c.gov_alerts || []).map((g) => ({ fonte: g.source, codigo: g.code, titulo: g.title, url: g.url })),\n  incidentes: (c.incidents || []).map((i) => ({ id: i.id, titulo: i.headline || i.title || i.id })),\n  stack: stR.err\n    ? { checado: false, erro: stR.err }\n    : {\n        checado: true,\n        afeta: !!stR.data.affects_my_stack,\n        tecnologias: (stR.data.items || []).map((i) => ({ nome: i.name, fabricante: i.vendor, tags: i.tags || [] })),\n        clientes: stR.data.tags || [],\n        inventario: invResumo,\n      },\n  ransomware: rwR.err\n    ? { checado: false, erro: rwR.err }\n    : {\n        checado: true,\n        usado: !!rwR.data.data?.used_by_ransomware,\n        kev_ransomware: !!rwR.data.data?.kev_ransomware,\n        familias: (rwR.data.data?.families || []).slice(0, 10).map((f) => ({\n          id: f.family_id, nome: f.name || f.family_id, grupos: (f.groups || []).map((g) => g.actor || g.actor_id).filter(Boolean).slice(0, 5),\n          estado_recuperacao: f.recovery_state || null, cves_no_inventario: f.inventory_cves || [] })),\n      },\n  analise: deep ? {\n    idioma: c.deep_lang || null, gerada_em: day(deep.generated_at),\n    resumo: deep.summary, tecnico: deep.technical, exploracao: deep.exploitation, mitigacao: deep.mitigation,\n    versoes_afetadas: deep.versions_affected, versoes_corrigidas: deep.versions_fixed, deteccao: deep.detection,\n    fontes: (deep.sources || []).map((s) => ({ label: s.label, url: s.url })),\n  } : null,\n  cwes: (c.cwes || []).map((w) => w.name || w.cwe_id),\n  referencias: (c.references || []).slice(0, 8).map((r) => r.url),\n  publicada_em: day(c.date_published),\n  atualizada_em: day(c.date_updated),\n  attribution: (cveR.data.attribution?.sources || []).map((s) => s.name),\n  attribution_url: cveR.data.attribution?.all_sources || null,\n};\n\n// análise aprofundada mais antiga que a última atualização da CVE\nrep.aviso_analise = (deep && c.date_updated && deep.generated_at && new Date(deep.generated_at) < new Date(c.date_updated))\n  ? 'A análise aprofundada foi gerada antes da última atualização da CVE. Confira versões e mitigação na fonte.'\n  : null;\n\n// ---------- prioridade (regra determinística, sem IA) ----------\n// SSVC primeiro (Act > Attend > Track* > Track); sem SSVC, cai pra faixa e depois pro CVSS.\nconst ssvc = String(rep.veredito.ssvc || '');\nconst band = String(rep.veredito.faixa || '').toLowerCase();\nconst sev = String(rep.cvss.severidade || '').toLowerCase();\nlet lvl;\nif (rep.exploracao.kev_cisa || ssvc === 'Act') lvl = 3;\nelse if (ssvc === 'Attend') lvl = 2;\nelse if (ssvc === 'Track*') lvl = 1;\nelse if (ssvc === 'Track') lvl = 0;\nelse if (band === 'critical' || sev === 'critical') lvl = 3;\nelse if (band === 'high' || sev === 'high') lvl = 2;\nelse if (band === 'medium' || sev === 'medium') lvl = 1;\nelse lvl = 0;\nconst [prio, cls] = [['Prioridade baixa', 'low'], ['Prioridade média', 'med'], ['Prioridade alta', 'high'], ['Agir agora', 'crit']][lvl];\nrep.prioridade = prio;\n\n// frases curtas reaproveitadas em todos os formatos\nconst fExpl = rep.exploracao.kev_cisa\n  ? `Exploração ativa confirmada (KEV CISA desde ${rep.exploracao.kev_desde}${rep.exploracao.kev_ransomware ? ', usada por ransomware' : ''}).`\n  : (rep.exploracao.ssvc_exploitation === 'active' ? 'Exploração ativa reportada (SSVC).' : 'Sem exploração ativa confirmada no KEV.');\nconst extras = [rep.exploracao.metasploit && 'Metasploit', rep.exploracao.nuclei && 'Nuclei'].filter(Boolean).join(', ');\nconst fPoc = rep.exploracao.poc_publica\n  ? `${rep.exploracao.pocs_total} PoC(s) pública(s)${extras ? ` + ${extras}` : ''}.`\n  : 'Sem PoC pública conhecida.';\nlet fStack;\nif (!rep.stack.checado) fStack = `Stack não checada: ${rep.stack.erro}`;\nelse if (!rep.stack.afeta) fStack = 'Não afeta nenhuma tecnologia monitorada na conta.';\nelse {\n  const techs = rep.stack.tecnologias.map((t) => t.nome + (t.tags.length ? ` (${t.tags.join(', ')})` : '')).join('; ');\n  fStack = `AFETA a stack monitorada: ${techs}.`;\n  if (invResumo) fStack += ` Inventário: ${Object.entries(invResumo).map(([k, v]) => `${v} ${k}`).join(', ')}.`;\n}\nconst ESTADO_RW = { confirmed: 'decryptor público confirmado', conditional: 'recuperação condicional (depende da variante)', no_known_tool: 'sem decryptor público', inconclusive: 'inconclusivo' };\nconst rw = rep.ransomware;\nlet fRw;\nif (!rw.checado) fRw = `Uso por ransomware não checado: ${rw.erro}`;\nelse if (rw.familias.length) fRw = `Usada por ransomware: ${rw.familias.slice(0, 3).map((f) => f.nome + (f.grupos.length ? ` (${f.grupos.slice(0, 2).join(', ')})` : '')).join('; ')}${rw.familias.length > 3 ? ` e mais ${rw.familias.length - 3}` : ''}.`;\nelse if (rw.usado) fRw = 'O KEV da CISA marca uso em campanha de ransomware, sem família vinculada no Vexday.';\nelse fRw = 'Sem uso por ransomware conhecido.';\nconst fRisco = `Risco ${rep.veredito.score ?? 'n/d'}/100 (${rep.veredito.faixa || 'n/d'}${rep.veredito.ssvc ? `, SSVC ${rep.veredito.ssvc}` : ''})`;\n\n// ---------- Markdown (Discord) e mrkdwn (Slack) ----------\nconst lines = [\n  `**${prio} | ${rep.cve_id}**`,\n  rep.titulo ? rep.titulo.slice(0, 200) : '',\n  `• ${fRisco} · CVSS ${rep.cvss.score ?? 'n/d'} · EPSS ${pct(rep.epss.score)}`,\n  `• ${fExpl}`,\n  `• ${fPoc}`,\n  `• ${fStack}`,\n  rw.usado ? `• ${fRw}` : '',\n  rep.alertas_gov.length ? `• Alerta gov.br: ${rep.alertas_gov.map((g) => g.codigo || g.titulo).join(', ')}` : '',\n  rep.url,\n].filter(Boolean);\nconst markdown = lines.join('\\n').slice(0, 1900);\nconst slack = [\n  `*${prio} | ${rep.cve_id}*`,\n  rep.titulo ? slackEsc(rep.titulo.slice(0, 200)) : '',\n  `• ${slackEsc(fRisco)} · CVSS ${rep.cvss.score ?? 'n/d'} · EPSS ${pct(rep.epss.score)}`,\n  `• ${slackEsc(fExpl)}`,\n  `• ${slackEsc(fPoc)}`,\n  `• ${slackEsc(fStack)}`,\n  rw.usado ? `• ${slackEsc(fRw)}` : '',\n  `<${rep.url}|Ver no Vexday>`,\n].filter(Boolean).join('\\n');\n\nconst notifyItems = buildNotify(canais, {\n  titulo: `${prio.replace(/^\\S+\\s/, '')} | ${rep.cve_id}`,\n  linhas: [rep.titulo ? rep.titulo.slice(0, 200) : '', `${fRisco} · CVSS ${rep.cvss.score ?? 'n/d'} · EPSS ${pct(rep.epss.score)}`, fExpl, fPoc, fStack, rw.usado ? fRw : ''].filter(Boolean),\n  url: rep.url, nivel: lvl, rodape: 'Vexday | T00',\n}, rep.stack.clientes);\n\n// ---------- HTML (resposta do formulário) ----------\nconst li = (arr, f) => (arr.length ? `<ul>${arr.map(f).join('')}</ul>` : '<p class=\"muted\">Nenhum.</p>');\nconst A = rep.analise;\nconst html = page(`${rep.cve_id} | Vexday`, `\n<p class=\"muted\">Vexday · Análise de CVE</p>\n<h1>${esc(rep.cve_id)}</h1>\n<p>${esc(rep.titulo)}</p>\n<p><span class=\"tag ${cls}\">${esc(prio)}</span><span class=\"muted\">${esc(fRisco)}</span></p>\n<p>${esc(rep.resumo)}</p>\n<div class=\"grid\">\n  <div class=\"card\"><span class=\"muted\">CVSS ${esc(rep.cvss.versao || '')}</span><b>${esc(rep.cvss.score ?? 'n/d')}</b><span class=\"muted\">${esc(rep.cvss.severidade || '')}</span></div>\n  <div class=\"card\"><span class=\"muted\">EPSS</span><b>${esc(pct(rep.epss.score))}</b><span class=\"muted\">percentil ${esc(pct(rep.epss.percentil))}</span></div>\n  <div class=\"card\"><span class=\"muted\">KEV CISA</span><b>${rep.exploracao.kev_cisa ? 'Sim' : 'Não'}</b><span class=\"muted\">${rep.exploracao.kev_ransomware ? 'usada por ransomware' : (rep.exploracao.kev_prazo ? 'prazo ' + esc(rep.exploracao.kev_prazo) : '')}</span></div>\n  <div class=\"card\"><span class=\"muted\">PoCs públicas</span><b>${esc(rep.exploracao.pocs_total)}</b><span class=\"muted\">${esc(extras || '')}</span></div>\n</div>\n\n<h2>Sua stack</h2>\n<p>${esc(fStack)}</p>\n\n<h2>Exploração</h2>\n<p>${esc(fExpl)} ${esc(fPoc)}${rep.exploracao.primeira_poc ? ' Primeira PoC em ' + esc(rep.exploracao.primeira_poc) + '.' : ''}</p>\n${rep.exploracao.kev_acao ? `<p class=\"muted\">Ação exigida pela CISA: ${esc(rep.exploracao.kev_acao)}</p>` : ''}\n${li(rep.exploracao.exploits, (e) => `<li>${esc(e.fonte)}: <a href=\"${esc(safeUrl(e.url))}\" rel=\"noopener noreferrer\">${esc(e.nome)}</a></li>`)}\n\n<h2>Ransomware</h2>\n<p>${esc(fRw)}</p>\n${rw.checado && rw.familias.length ? `<table><tr><th>Família</th><th>Grupos que exploram a CVE</th><th>Recuperação</th></tr>${rw.familias.map((f) => `<tr><td>${esc(f.nome)}</td><td>${esc(f.grupos.join(', ') || 'n/d')}</td><td>${esc(ESTADO_RW[f.estado_recuperacao] || f.estado_recuperacao || 'n/d')}</td></tr>`).join('')}</table>\n<p class=\"muted\">Quem explora a CVE é o grupo, não a família. Para identificar um ataque em curso, use o T06.</p>` : ''}\n\n<h2>Atores associados</h2>\n${li(rep.atores, (a) => `<li>${esc(a.nome)} <span class=\"muted\">(${esc(a.tipo || '')}${a.origem ? ', ' + esc(a.origem) : ''}, confiança ${esc(a.confianca || 'n/d')})</span></li>`)}\n\n<h2>Alertas do governo brasileiro</h2>\n${li(rep.alertas_gov, (g) => `<li><a href=\"${esc(safeUrl(g.url))}\" rel=\"noopener noreferrer\">${esc(g.codigo || '')} ${esc(g.titulo)}</a> <span class=\"muted\">${esc(g.fonte)}</span></li>`)}\n\n${A ? `\n<h2>Análise</h2>\n${rep.aviso_analise ? `<p class=\"warn\">${esc(rep.aviso_analise)}</p>` : ''}\n<p>${para(A.resumo)}</p>\n<h2>Detalhe técnico</h2><p>${para(A.tecnico)}</p>\n<h2>Como é explorada</h2><p>${para(A.exploracao)}</p>\n<h2>Mitigação</h2><p>${para(A.mitigacao)}</p>\n<p><b>Versões afetadas:</b> ${para(A.versoes_afetadas)}</p>\n<p><b>Versões corrigidas:</b> ${para(A.versoes_corrigidas)}</p>\n<h2>Detecção</h2><p>${para(A.deteccao)}</p>\n<h2>Fontes da análise</h2>\n${li(A.fontes, (s) => `<li><a href=\"${esc(safeUrl(s.url))}\" rel=\"noopener noreferrer\">${esc(s.label || s.url)}</a></li>`)}\n<p class=\"muted\">Análise gerada em ${esc(A.gerada_em)} (${esc(A.idioma)}).</p>\n` : '<h2>Análise</h2><p class=\"muted\">O Vexday ainda não tem análise aprofundada desta CVE. Veja as referências abaixo.</p>'}\n\n<h2>Referências</h2>\n${li(rep.referencias, (u) => `<li><a href=\"${esc(safeUrl(u))}\" rel=\"noopener noreferrer\">${esc(u)}</a></li>`)}\n\n<footer>\n<p><a href=\"${esc(rep.url)}\" rel=\"noopener noreferrer\">Abrir no Vexday</a> · publicada ${esc(rep.publicada_em)} · atualizada ${esc(rep.atualizada_em)}</p>\n<p>Fontes: ${esc(rep.attribution.join(' · '))}${rep.attribution_url ? ` · <a href=\"${esc(rep.attribution_url)}\">todas as fontes e licenças</a>` : ''}</p>\n<p>Gerado por Vexday | T00. Confira a fonte antes de agir.</p>\n</footer>`);\n\nreturn out({\n  ok: true,\n  source: inp.source,\n  report: rep,\n  markdown,\n  html,\n  notifyItems,\n});\n"
      },
      "id": "49ea994e-95ac-d331-05d7-e3a9ec8ed7eb"
    },
    {
      "name": "Veio do formulário?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1780,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "bb17a849-aaf6-18d1-7eb1-519f74bb9a5b",
              "leftValue": "={{ $json.source === 'form' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "30740863-bb1f-2680-d949-3a4a7a778d01"
    },
    {
      "name": "Mostra relatório",
      "type": "n8n-nodes-base.form",
      "typeVersion": 2.3,
      "position": [
        2000,
        -80
      ],
      "parameters": {
        "operation": "completion",
        "respondWith": "showText",
        "responseText": "={{ $json.html }}"
      },
      "id": "b8623e91-10e5-58b8-5306-0d0e0c66e6bb"
    },
    {
      "name": "Resposta JSON",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2000,
        80
      ],
      "parameters": {
        "mode": "raw",
        "jsonOutput": "={{ JSON.stringify({ ...$json.report, markdown: $json.markdown }) }}",
        "options": {}
      },
      "id": "feef9021-2b37-4f34-2fc4-769bef6accf2"
    },
    {
      "name": "Itens de notificação",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1780,
        -300
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\n// Transforma os destinos calculados no relatório em itens para o HTTP de notificação.\nconst r = $input.first().json;\nreturn (r.notifyItems || []).map((n) => ({ json: n }));\n"
      },
      "id": "f9c2030b-1a53-f664-b934-3f67d404121e"
    },
    {
      "name": "Envia notificações",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2000,
        -300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.url }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "timeout": 15000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 400
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "2a501e31-00be-ac43-c747-c4c2213addf0"
    },
    {
      "name": "Leia-me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -460,
        -300
      ],
      "parameters": {
        "content": "## Vexday | T00 - Análise de CVE\n\nRecebe um CVE-ID (formulário ou webhook) e devolve o relatório completo. Sem IA: a análise vem pronta do Vexday e a prioridade é regra fixa (SSVC).\n\n### Setup\n1. Credencial `Vexday API` (Header Auth): Name `Authorization`, Value `Bearer vx_live_SUA_CHAVE` (painel do Vexday → Integrações). Selecione em todo nó `Vexday MCP`.\n2. Credencial Basic Auth no Formulário e Header Auth no Webhook. Cada análise gasta 3 consultas.\n3. Ajuste o Config e ative.\n\nPlano: SOC ou MSSP\nCusto: 3 consultas por análise",
        "width": 420,
        "height": 480
      },
      "id": "cad6a68b-3b0b-f89b-427c-ce232f9855e2"
    },
    {
      "name": "Ajuda do Config",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        180,
        -420
      ],
      "parameters": {
        "content": "### Config\n- `vexday_mcp_url`: não mude (só para proxy)\n- `lang_padrao`: pt, en ou es\n- `canais`: lista JSON de destinos. Ex.:\n```json\n[{\"tipo\":\"discord\",\"url\":\"https://discord.com/api/webhooks/...\"},\n {\"tipo\":\"teams\",\"url\":\"https://...logic.azure.com/...\",\"tags\":[\"cliente-acme\"]}]\n```\nTipos: `discord`, `slack`, `teams` (webhook de Workflows), `json`. Com `tags`, o canal só recebe aquele cliente.",
        "width": 440,
        "height": 300,
        "color": 5
      },
      "id": "a3009dd9-51e4-1f51-fc23-0bfe78d851d6"
    },
    {
      "name": "Webhook doc",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -460,
        220
      ],
      "parameters": {
        "content": "### Webhook\n`POST /webhook/vexday-t00-cve` com o header de autenticação:\n```json\n{\"cve_id\": \"CVE-2024-3400\", \"lang\": \"pt\"}\n```\nResposta JSON: `ok`, `erro`, relatório e `markdown`.",
        "width": 420,
        "height": 230,
        "color": 7
      },
      "id": "5474706a-ab48-b578-4df6-5929ab21f2b7"
    }
  ],
  "connections": {
    "Formulário": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Valida entrada",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Valida entrada": {
      "main": [
        [
          {
            "node": "CVE válido?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CVE válido?": {
      "main": [
        [
          {
            "node": "Pede get_cve",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Monta relatório",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pede get_cve": {
      "main": [
        [
          {
            "node": "Vexday MCP get_cve",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP get_cve": {
      "main": [
        [
          {
            "node": "Pede check_stack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pede check_stack": {
      "main": [
        [
          {
            "node": "Vexday MCP check_stack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP check_stack": {
      "main": [
        [
          {
            "node": "Pede ransomware",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pede ransomware": {
      "main": [
        [
          {
            "node": "Vexday MCP ransomware",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP ransomware": {
      "main": [
        [
          {
            "node": "Monta relatório",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Monta relatório": {
      "main": [
        [
          {
            "node": "Itens de notificação",
            "type": "main",
            "index": 0
          },
          {
            "node": "Veio do formulário?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Veio do formulário?": {
      "main": [
        [
          {
            "node": "Mostra relatório",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Resposta JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Itens de notificação": {
      "main": [
        [
          {
            "node": "Envia notificações",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
