{
  "name": "Vexday | T06 - Identificação de ransomware (v0.1)",
  "nodes": [
    {
      "name": "Formulário",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [
        0,
        0
      ],
      "webhookId": "77f2fde5-a6d2-9f1d-b4c4-aaef2b4d4a9f",
      "parameters": {
        "authentication": "basicAuth",
        "formTitle": "Vexday | Identificação de ransomware",
        "formDescription": "Preencha pelo menos um campo com o que foi achado na máquina. Quanto mais indicadores, mais precisa a identificação. Sai a família provável, o estado de recuperação, os decryptors oficiais, o guia de recuperação e o pacote de detecção.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Extensão",
              "placeholder": ".akira"
            },
            {
              "fieldLabel": "Nota de resgate",
              "placeholder": "akira_readme.txt"
            },
            {
              "fieldLabel": "Hash",
              "placeholder": "MD5, SHA-1 ou SHA-256 da amostra"
            },
            {
              "fieldLabel": "Família",
              "placeholder": "Akira"
            },
            {
              "fieldLabel": "Grupo",
              "placeholder": "Akira"
            }
          ]
        },
        "responseMode": "lastNode",
        "options": {
          "buttonLabel": "Identificar"
        }
      },
      "id": "1a34d543-8372-47b5-281b-f4c07c7258e9"
    },
    {
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        220
      ],
      "webhookId": "087095f7-b89c-b9c1-be47-8e685f357b85",
      "parameters": {
        "httpMethod": "POST",
        "path": "vexday-t06-ransomware",
        "authentication": "headerAuth",
        "responseMode": "lastNode",
        "options": {
          "responseData": "firstEntryJson"
        }
      },
      "id": "eb300f07-6f3e-ac12-7bf6-6341a80148f9"
    },
    {
      "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": "be4af4f8-ee3a-6a6f-33aa-d7529dc473bc"
    },
    {
      "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 os indicadores (Formulário ou Webhook) e valida antes de gastar consulta.\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.body || {}) : $('Formulário').first().json;\nconst pick = (...ks) => { for (const k of ks) { const v = j[k]; if (v !== undefined && v !== null && String(v).trim() !== '') return String(v).trim(); } return ''; };\n\nlet extensao = pick('extensao', 'extension', 'Extensão');\nlet nota = pick('nota', 'note', 'Nota de resgate');\nlet hash = pick('hash', 'Hash');\nconst familia = pick('familia', 'family', 'name', 'Família').slice(0, 80);\nconst grupo = pick('grupo', 'group', 'actor', 'Grupo').slice(0, 80);\nconst langIn = fromWebhook ? j.lang : null;\nconst lang = ['pt', 'en', 'es'].includes(langIn) ? langIn : (['pt', 'en', 'es'].includes(cfg.lang_padrao) ? cfg.lang_padrao : 'pt');\n\n// extensão: minúscula, sem \"*\" e com ponto na frente (\"AKIRA\" e \"*.akira\" viram \".akira\")\nif (extensao) {\n  extensao = extensao.toLowerCase().replace(/^\\*+/, '').replace(/\\s+/g, '');\n  if (!extensao.startsWith('.')) extensao = '.' + extensao;\n  extensao = extensao.slice(0, 80);\n}\n// nota: só o nome do arquivo, sem caminho\nif (nota) nota = nota.split(/[\\\\/]/).pop().trim().slice(0, 120);\n\nconst erros = [];\nlet tipoHash = null;\nif (hash) {\n  hash = hash.replace(/\\s+/g, '').toLowerCase();\n  tipoHash = { 32: 'MD5', 40: 'SHA-1', 64: 'SHA-256' }[hash.length] || null;\n  if (!/^[0-9a-f]+$/.test(hash) || !tipoHash)\n    erros.push(`Hash inválido (${hash.length} caractere(s)${/^[0-9a-f]*$/.test(hash) ? '' : ', com caractere fora de 0-9 e a-f'}). Use MD5 (32), SHA-1 (40) ou SHA-256 (64) em hexadecimal.`);\n}\n\nconst campos = [\n  ['extensao', extensao, 'extensão dos arquivos cifrados'],\n  ['nota', nota, 'nome do arquivo da nota de resgate'],\n  ['hash', hash, 'hash da amostra (de preferência SHA-256 do executável)'],\n  ['familia', familia, 'nome da família citado na nota'],\n  ['grupo', grupo, 'grupo (pelo site de vazamento ou contato da nota)'],\n];\nconst fornecidos = campos.filter((c) => c[1]).map((c) => c[0]);\nif (!fornecidos.length) erros.unshift('Informe pelo menos um indicador: extensão, nome do arquivo da nota, hash, família ou grupo.');\n\nconst args = { lang };\nif (extensao) args.extension = extensao;\nif (nota) args.note = nota;\nif (hash && !erros.length) args.hash = hash;\nif (familia) args.name = familia;\nif (grupo) args.actor = grupo;\n\nreturn [{ json: {\n  source: fromWebhook ? 'webhook' : 'form',\n  valid: erros.length === 0,\n  erro: erros.length ? erros.join(' ') : null,\n  lang, args, tipo_hash: tipoHash,\n  entrada: { extensao: extensao || null, nota: nota || null, hash: hash || null, familia: familia || null, grupo: grupo || null },\n  fornecidos,\n  faltam: campos.filter((c) => !c[1]).map((c) => c[2]),\n} }];\n"
      },
      "id": "ca822e82-b429-a343-baef-e584f9f35461"
    },
    {
      "name": "Entrada válida?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        680,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "97489439-b514-1838-9041-177c55cc6782",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "bc74a9b3-85f3-4ac6-c076-ef9612c9e681"
    },
    {
      "name": "Pede search",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        0
      ],
      "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('search_ransomware', $input.first().json.args)];\n"
      },
      "id": "d2acdbba-3b65-bb89-9cfd-bfad128692d1"
    },
    {
      "name": "Vexday MCP search",
      "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": "e328f7a9-9b57-b727-ce1e-51c0bf901f6f"
    },
    {
      "name": "Planeja consultas",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1340,
        0
      ],
      "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// Decide as consultas da 2ª etapa pelo grau de identificação (custo previsível: 1 a 4 consultas aqui).\nconst v = $('Valida entrada').first().json;\nconst s = parseMcpResp($input.first().json, 'search_ransomware');\nif (s.err) return [{ json: { tem: false, reqs: [] } }];\nconst d = s.data.data || {};\nconst top = (d.candidates || [])[0];\nconst reqs = [];\n// grupo para o pacote de detecção: quem opera a família, confiança alta antes de média; baixa fica de fora\nconst CONF = { high: 2, medium: 1 };\nfunction ator(c) {\n  const as = (c?.actors || []).filter((a) => a.actor_id && CONF[a.confidence] !== undefined && !/refuted|disputed/i.test(a.status || ''));\n  as.sort((a, b) => ((b.predicate === 'operates_family') - (a.predicate === 'operates_family')) || (CONF[b.confidence] - CONF[a.confidence]));\n  return as[0]?.actor_id || null;\n}\nif (d.identification === 'probable' && top?.family?.id) {\n  const fid = top.family.id;\n  reqs.push(mcpReq('get_ransomware_family', { family_id: fid, lang: v.lang }, { k: 'familia' }).json);\n  reqs.push(mcpReq('find_decryptors', { family_id: fid }, { k: 'decryptors' }).json);\n  reqs.push(mcpReq('get_recovery_guidance', { family_id: fid, lang: v.lang }, { k: 'guia' }).json);\n  const a = ator(top);\n  if (a) reqs.push(mcpReq('get_detection_pack', { actor_id: a }, { k: 'pacote' }).json);\n} else {\n  // ambígua ou inconclusiva: sem família definida, só o guia geral\n  reqs.push(mcpReq('get_recovery_guidance', { lang: v.lang }, { k: 'guia' }).json);\n}\nreturn [{ json: { tem: true, reqs } }];\n"
      },
      "id": "706974a9-9286-7838-220e-e9bcd6ceda7d"
    },
    {
      "name": "Tem consultas?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1560,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "f6ebf764-1c0e-30b1-ea1f-5c6bb77e859e",
              "leftValue": "={{ $json.tem }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c31aaa09-5719-2ca9-4a5c-fb60b74325b2"
    },
    {
      "name": "Separa consultas",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1780,
        -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\nreturn $input.first().json.reqs.map((r) => ({ json: r }));\n"
      },
      "id": "ce2e1eec-cfa4-1483-a552-a1b0f486f7f3"
    },
    {
      "name": "Vexday MCP detalhes",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2000,
        -100
      ],
      "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": "8517f9b0-74e9-4fe2-ada3-cce4368cfaaa"
    },
    {
      "name": "Confere guia",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2220,
        -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// Guia da família recusado (isError) → pede o guia geral. Erro fatal (401, limite) não pede nada: o relatório mostra o erro.\nconst res = zipMcp($('Separa consultas').all(), $input.all());\nconst g = res.find((r) => r.ctx?.k === 'guia');\nconst precisa = !res.some((r) => r.fatal) && !!g && !!g.toolError && !!g.args?.family_id;\nconst lang = $('Valida entrada').first().json.lang;\nreturn [{ json: { precisa, motivo: precisa ? g.err : null, ...(precisa ? mcpReq('get_recovery_guidance', { lang }, { k: 'guia_geral' }).json : {}) } }];\n"
      },
      "id": "f81eaa55-45f5-f5ff-1413-677429282bfd"
    },
    {
      "name": "Guia geral?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2440,
        -100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "570194cf-b988-f580-58bc-3de67d4bee51",
              "leftValue": "={{ $json.precisa }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "ea39be87-516f-39dc-4dd9-63af294afd5e"
    },
    {
      "name": "Vexday MCP guia geral",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2660,
        -200
      ],
      "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": "f2a35e99-3a34-83d8-60d1-0cb97f935e70"
    },
    {
      "name": "Monta relatório",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2880,
        100
      ],
      "parameters": {
        "jsCode": "// Vexday | T06 - Monta o relatório de identificação de ransomware.\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', []);\nconst ran = (n) => { try { return $(n).isExecuted; } catch (e) { return false; } };\nconst out = (o) => [{ json: o }];\nconst GUIA_GERAL_URL = `https://vexday.io/${inp.lang || 'pt'}/ransomware/guia`;\n\nfunction erro(msg, consultas) {\n  return out({\n    ok: false, source: inp.source,\n    report: { ok: false, erro: msg, entrada: inp.entrada || null, consultas: consultas || 0 },\n    html: page('Erro | Vexday', `<p class=\"muted\">Vexday · Identificação de ransomware</p><h1>Não foi possível identificar</h1><div class=\"err\">${esc(msg)}</div>`),\n    markdown: null, notifyItems: [],\n  });\n}\n\n// ---------- validação e consultas ----------\nif (!inp.valid) return erro(inp.erro, 0);\nconst sR = parseMcpResp($('Vexday MCP search').first().json, 'search_ransomware');\nif (sR.err) return erro(sR.fatal ? sR.err : `O Vexday recusou a busca: ${sR.err}`, 1);\nconst S = sR.data.data || {};\nconst det = ran('Vexday MCP detalhes') ? zipMcp($('Separa consultas').all(), $('Vexday MCP detalhes').all()) : [];\nconst geralR = ran('Vexday MCP guia geral') ? parseMcpResp($('Vexday MCP guia geral').first().json, 'get_recovery_guidance') : null;\nconst consultas = 1 + det.length + (geralR ? 1 : 0);\nconst fatal = [...det, ...(geralR ? [geralR] : [])].find((r) => r.fatal);\nif (fatal) return erro(fatal.err, consultas);\nconst by = (k) => det.find((r) => r.ctx?.k === k) || null;\n\n// ---------- normalização ----------\nconst IDENT = { probable: 'provável', ambiguous: 'ambígua', inconclusive: 'inconclusiva' };\nconst ident = IDENT[S.identification] ? S.identification : 'inconclusive';\nconst KIND = { extension: 'extensão', note_filename: 'nome da nota', note: 'nome da nota', hash: 'hash', name: 'nome', alias: 'apelido', actor: 'grupo' };\nconst ESTADO = {\n  confirmed: 'ferramenta pública confirmada para a família',\n  conditional: 'condicional: depende da variante e das condições do fabricante',\n  no_known_tool: 'sem ferramenta pública conhecida',\n  inconclusive: 'inconclusivo: a família não foi identificada',\n  unverified: 'listado pelo No More Ransom, sem checagem da variante',\n  incompatible: 'incompatível',\n};\nconst est = (s) => ESTADO[s] || (s ? String(s) : 'n/d');\nconst AVISO = {\n  preserve: 'Preserve os arquivos cifrados, a nota de resgate e os backups antes de tentar qualquer coisa.',\n  work_on_copy: 'Teste qualquer ferramenta numa cópia dos arquivos, em ambiente isolado, seguindo as instruções do fabricante.',\n  variant_matters: 'Decryptor de uma família não garante recuperação para todas as variantes.',\n};\nconst httpUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : null);\nconst evid = (m) => ({ tipo: KIND[m.kind] || m.kind, valor: m.value ?? null, fonte: m.evidence?.source || null,\n  titulo: m.evidence?.title || null, url: httpUrl(m.evidence?.url), variante: m.variant_id || null });\nconst grupos = (as) => (as || []).filter((a) => a.actor_id || a.actor).slice(0, 5)\n  .map((a) => ({ id: a.actor_id || null, nome: a.actor || a.actor_id, confianca: a.confidence || null, status: a.status || null }));\nconst cand = (c) => ({ id: c.family?.id || null, nome: c.family?.name || c.family?.id || 'sem nome', mitre: c.family?.mitre_id || null,\n  plataformas: c.family?.platforms || [], evidencias: (c.matched_on || []).map(evid), grupos: grupos(c.actors) });\n\nconst cands = S.candidates || [];\nconst totalCand = S.total_candidates ?? cands.length;\nconst avisos = [...new Set((S.warnings || []).map((w) => AVISO[w.code] || w.text).filter(Boolean))];\n\n// ---------- família (só com identificação provável) ----------\nlet familia = null, recuperacao = null, decryptors = [], pacote = null;\nconst falhas = [];\nif (ident === 'probable' && cands[0]) {\n  const c0 = cand(cands[0]);\n  const famR = by('familia');\n  const F = famR?.data?.data || null;\n  if (famR?.err) falhas.push(`Perfil da família: ${famR.err}`);\n  const sig = (k) => [...new Set((F?.signatures || []).filter((s) => s.kind === k).map((s) => s.value))].slice(0, 12);\n  familia = {\n    ...c0,\n    nome: F?.family?.name || c0.nome,\n    descricao: F?.family?.description ? String(F.family.description).slice(0, 700) : null,\n    plataformas: F?.family?.platforms?.length ? F.family.platforms : c0.plataformas,\n    mitre: F?.family?.mitre_id || c0.mitre,\n    apelidos: (F?.aliases || []).map((a) => a.alias).filter(Boolean).slice(0, 10),\n    extensoes: sig('extension'),\n    notas: [...sig('note_filename'), ...sig('note')].slice(0, 12),\n    grupos: F?.actors?.length ? grupos(F.actors) : c0.grupos,\n  };\n\n  // recuperação: estado da família e por variante (estado do catálogo, não promessa)\n  const decR = by('decryptors');\n  if (decR?.err) falhas.push(`Decryptors: ${decR.err}`);\n  const rec = decR?.data?.data?.recovery || F?.recovery || S.recovery || {};\n  const nomeVar = {};\n  for (const vv of (F?.variants || [])) if (vv && vv.id) nomeVar[vv.id] = vv.name || vv.id;\n  const porVar = [{ variante: 'família (variante não identificada)', estado: rec.state || null, estado_pt: est(rec.state) }];\n  const rbv = decR?.data?.data?.recovery_by_variant || F?.recovery_by_variant || {};\n  for (const [vid, vv] of Object.entries(rbv)) {\n    const st = typeof vv === 'string' ? vv : vv?.state;\n    porVar.push({ variante: nomeVar[vid] || vid, estado: st || null, estado_pt: est(st) });\n  }\n  recuperacao = { estado: rec.state || null, estado_pt: est(rec.state), por_variante: porVar,\n    nota: 'Estado registrado no Vexday para a família e suas variantes. Não é garantia de recuperação.' };\n  decryptors = (rec.decryptors || []).filter((x) => httpUrl(x.official_url)).map((x) => ({\n    nome: x.name || x.decryptor_id, fabricante: x.vendor || null, link_oficial: httpUrl(x.official_url), manual: httpUrl(x.docs_url),\n    compatibilidade: x.state || null, condicoes: x.conditions || null, variante: x.variant_id ? (nomeVar[x.variant_id] || x.variant_id) : null,\n    disponibilidade: x.availability || null, verificado_em: day(x.last_verified_at),\n  }));\n\n  // pacote de detecção do grupo: contagens e YARA; itens restritos só contados\n  const pkR = by('pacote');\n  if (pkR) {\n    if (pkR.err) pacote = { grupo: pkR.args?.actor_id || null, erro: pkR.err };\n    else {\n      const P = pkR.data?.data || {};\n      const iocs = Array.isArray(P.iocs) ? P.iocs : [];\n      const abertos = iocs.filter((x) => !x.restricted);\n      const porTipo = abertos.reduce((m, x) => { const t = x.type || x.ioc_type || 'outro'; m[t] = (m[t] || 0) + 1; return m; }, {});\n      pacote = {\n        grupo: P.actor || P.actor_id || pkR.args?.actor_id || null,\n        indicadores: abertos.length, por_tipo: porTipo, restritos: iocs.length - abertos.length,\n        yara: (Array.isArray(P.yara) ? P.yara : []).filter((y) => !y.restricted).map((y) => ({ arquivo: y.filename || y.name || 'regra.yar', conteudo: String(y.content ?? y.rule ?? '').slice(0, 20000) })),\n        nota: P.note || null,\n      };\n    }\n  }\n}\n\n// ---------- candidatos (ambígua) ----------\nconst candidatos = ident === 'ambiguous' ? cands.slice(0, 3).map(cand) : [];\n\n// ---------- guia de recuperação ----------\nlet guiaR = by('guia');\nlet guiaFallback = false;\nif (guiaR?.err && geralR) { guiaFallback = true; guiaR = geralR; }\nlet guia = null;\nif (guiaR && !guiaR.err) {\n  const G = guiaR.data?.data || {};\n  guia = { escopo: G.scope === 'family' ? 'família' : 'geral', titulo: G.title || 'Guia de recuperação', publicado_em: day(G.published_at),\n    idioma: G.lang || inp.lang, blocos: Array.isArray(G.blocks) ? G.blocks : [], caiu_para_geral: guiaFallback };\n} else if (guiaR?.err) falhas.push(`Guia de recuperação: ${guiaR.err}`);\nconst runTxt = (r) => (r.a !== undefined ? `${r.a}${httpUrl(r.href) ? ` (${r.href})` : ''}` : String(r.b ?? r.i ?? r.code ?? r.t ?? ''));\nconst runHtml = (r) => (r.a !== undefined ? `<a href=\"${esc(safeUrl(r.href))}\" rel=\"noopener noreferrer\">${esc(r.a)}</a>`\n  : r.b !== undefined ? `<b>${esc(r.b)}</b>` : r.i !== undefined ? `<i>${esc(r.i)}</i>` : r.code !== undefined ? `<code>${esc(r.code)}</code>` : esc(r.t ?? ''));\nconst runs = (rs, f) => (Array.isArray(rs) ? rs.map(f).join('') : f({ t: rs }));\nfunction guiaHtml(bs) {\n  return bs.map((b) => {\n    if (b.type === 'h') return `<h3>${runs(b.text, runHtml)}</h3>`;\n    if (b.type === 'ul' || b.type === 'ol') return `<${b.type}>${(b.items || []).map((it) => `<li>${runs(it, runHtml)}</li>`).join('')}</${b.type}>`;\n    return `<p>${runs(b.text, runHtml)}</p>`;\n  }).join('\\n');\n}\nfunction guiaTexto(bs) {\n  const L = [];\n  for (const b of bs) {\n    if (b.type === 'ul' || b.type === 'ol') (b.items || []).forEach((it, k) => L.push(`${b.type === 'ol' ? (k + 1) + '.' : '-'} ${runs(it, runTxt)}`));\n    else L.push(b.type === 'h' ? `## ${runs(b.text, runTxt)}` : runs(b.text, runTxt));\n  }\n  return L;\n}\n\n// ---------- sugestões, coleta e próximos passos ----------\nconst semMatch = (S.unmatched || []).map((k) => KIND[k] || k);\nconst sugestoes = (inp.fornecidos.length === 1 || ident !== 'probable') ? inp.faltam : [];\nconst coletar = ident === 'inconclusive' ? [\n  'A extensão exata que aparece nos arquivos cifrados (copie do nome de um arquivo, com tudo depois do nome original).',\n  'O nome exato do arquivo da nota de resgate e, se houver, o e-mail, ID ou endereço .onion de contato escrito nela.',\n  'O hash SHA-256 do executável do ransomware, se ele foi encontrado (não execute o arquivo).',\n  'O nome do grupo, se a nota ou o site de vazamento citar um.',\n] : [];\nconst passos = [];\npassos.push('Contenha e preserve antes de recuperar: siga a ordem do guia abaixo.');\nif (ident === 'probable') {\n  if (decryptors.length) passos.push(`Teste o decryptor pelo link oficial numa cópia dos arquivos, em ambiente isolado, nunca nos originais. Confira as condições de compatibilidade antes.`);\n  else passos.push('Não há decryptor público conhecido para esta família: a recuperação depende de backup. Desconfie de quem oferece decryptor fora das páginas oficiais.');\n  if (pacote && !pacote.erro && (pacote.indicadores || pacote.yara.length)) passos.push(`Cace no ambiente os indicadores e as regras YARA do pacote de detecção do grupo ${pacote.grupo}.`);\n} else {\n  passos.push('Colete os indicadores que faltam e rode de novo para chegar a uma família.');\n  passos.push('Não teste decryptor antes de confirmar a família: ferramenta errada pode danificar arquivos.');\n}\npassos.push('Registre o incidente e veja no guia as obrigações de comunicação (ANPD, regulador do setor).');\n\n// ---------- relatório ----------\nconst rep = {\n  ok: true,\n  entrada: inp.entrada, tipo_hash: inp.tipo_hash,\n  identificacao: ident, identificacao_pt: IDENT[ident], total_candidatos: totalCand,\n  sem_correspondencia: semMatch,\n  familia, candidatos, recuperacao, decryptors,\n  aviso_decryptor: decryptors.length ? AVISO.work_on_copy : null,\n  guia: guia ? { escopo: guia.escopo, titulo: guia.titulo, publicado_em: guia.publicado_em, idioma: guia.idioma, caiu_para_geral: guia.caiu_para_geral, texto: guiaTexto(guia.blocos) } : null,\n  guia_url: GUIA_GERAL_URL,\n  pacote, sugestoes, coletar, proximos_passos: passos, avisos, falhas, consultas,\n  attribution: (sR.data.attribution?.sources || []).map((s) => s.name),\n  attribution_url: sR.data.attribution?.all_sources || null,\n};\n\n// frases curtas reaproveitadas\nconst evTxt = (es) => es.slice(0, 3).map((e) => `${e.tipo} ${e.valor}${e.fonte ? ` (${e.fonte})` : ''}`).join('; ');\nlet titulo, fId, nivel;\nif (ident === 'probable') {\n  titulo = `Ransomware: ${familia.nome} (identificação provável)`;\n  fId = `Família provável: ${familia.nome}. Evidência: ${evTxt(familia.evidencias) || 'n/d'}.`;\n  nivel = 3;\n} else if (ident === 'ambiguous') {\n  titulo = `Ransomware: identificação ambígua (${totalCand} candidatas)`;\n  fId = `Identificação ambígua: ${totalCand} família(s) batem. Mais prováveis: ${candidatos.map((c) => c.nome).join(', ')}.`;\n  nivel = 2;\n} else {\n  titulo = 'Ransomware: identificação inconclusiva';\n  fId = `Nenhuma família bate com os indicadores${semMatch.length ? ` (sem correspondência: ${semMatch.join(', ')})` : ''}.`;\n  nivel = 2;\n}\nconst fRec = recuperacao ? `Recuperação: ${recuperacao.estado_pt}. ${decryptors.length ? `${decryptors.length} decryptor(s) com link oficial.` : 'Nenhum decryptor público.'}` : 'Recuperação: depende de identificar a família.';\nconst fPack = !pacote ? null : pacote.erro ? `Pacote de detecção: a consulta falhou (${pacote.erro}).`\n  : (!pacote.indicadores && !pacote.yara.length) ? `Pacote de detecção de ${pacote.grupo}: vazio no Vexday.`\n  : `Pacote de detecção de ${pacote.grupo}: ${pacote.yara.length} regra(s) YARA, ${pacote.indicadores} indicador(es)${pacote.restritos ? ` + ${pacote.restritos} restrito(s) só no Vexday` : ''}.`;\nconst fEntrada = Object.entries(inp.entrada).filter(([, v]) => v).map(([k, v]) => `${k} ${String(v).slice(0, 70)}`).join(' · ');\n\nconst notifyItems = buildNotify(canais, {\n  titulo, nivel, rodape: `Vexday | T06 · ${consultas} consulta(s)`, url: null,\n  linhas: [`Indicadores: ${fEntrada}`, fId, fRec, fPack, sugestoes.length ? `Afinaria: ${sugestoes.join('; ')}.` : null].filter(Boolean),\n});\nconst markdown = [`**${titulo}**`, `• Indicadores: ${fEntrada}`, `• ${fId}`, `• ${fRec}`, fPack ? `• ${fPack}` : '', GUIA_GERAL_URL].filter(Boolean).join('\\n').slice(0, 1900);\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 evLi = (e) => `<li>${esc(e.tipo)} <b>${esc(e.valor)}</b>${e.variante ? ` <span class=\"muted\">(variante ${esc(e.variante)})</span>` : ''}${e.fonte ? ` <span class=\"muted\">· fonte ${esc(e.fonte)}</span>` : ''}${e.url ? ` · <a href=\"${esc(e.url)}\" rel=\"noopener noreferrer\">${esc(e.titulo || 'evidência')}</a>` : (e.titulo ? ` <span class=\"muted\">· ${esc(e.titulo)}</span>` : '')}</li>`;\nconst grLi = (g) => `<li>${esc(g.nome)} <span class=\"muted\">(confiança ${esc(g.confianca || 'n/d')}${g.status ? ', ' + esc(g.status) : ''})</span></li>`;\nconst cls = ident === 'probable' ? 'crit' : 'high';\nlet corpo = '';\nif (familia) {\n  corpo += `\n<h2>Família</h2>\n<p><b>${esc(familia.nome)}</b>${familia.mitre ? ` <span class=\"muted\">· MITRE ${esc(familia.mitre)}</span>` : ''}${familia.plataformas.length ? ` <span class=\"muted\">· ${esc(familia.plataformas.join(', '))}</span>` : ''}</p>\n${familia.descricao ? `<p>${para(familia.descricao)}</p>` : ''}\n<p class=\"muted\">Evidência da identificação:</p>${li(familia.evidencias, evLi)}\n${familia.apelidos.length ? `<p><b>Apelidos:</b> ${esc(familia.apelidos.join(', '))}</p>` : ''}\n${familia.extensoes.length ? `<p><b>Extensões conhecidas:</b> ${esc(familia.extensoes.join(', '))}</p>` : ''}\n${familia.notas.length ? `<p><b>Notas de resgate conhecidas:</b> ${esc(familia.notas.join(', '))}</p>` : ''}\n<p class=\"muted\">Grupos que usam:</p>${li(familia.grupos, grLi)}\n\n<h2>Recuperação</h2>\n<p class=\"warn\">${esc(recuperacao.nota)}</p>\n<table><tr><th>Variante</th><th>Estado</th></tr>${recuperacao.por_variante.map((r) => `<tr><td>${esc(r.variante)}</td><td>${esc(r.estado_pt)}</td></tr>`).join('')}</table>\n<h2>Decryptors públicos</h2>\n${decryptors.length ? `<p class=\"warn\">${esc(AVISO.work_on_copy)} Só links oficiais do fabricante ou do No More Ransom.</p>\n<table><tr><th>Ferramenta</th><th>Compatibilidade</th><th>Condições</th></tr>${decryptors.map((x) => `<tr><td><a href=\"${esc(x.link_oficial)}\" rel=\"noopener noreferrer\">${esc(x.nome)}</a><br><span class=\"muted\">${esc(x.fabricante || '')}${x.manual ? ` · <a href=\"${esc(x.manual)}\" rel=\"noopener noreferrer\">manual</a>` : ''}${x.verificado_em ? ` · verificado ${esc(x.verificado_em)}` : ''}</span></td><td>${esc(est(x.compatibilidade))}${x.variante ? `<br><span class=\"muted\">variante ${esc(x.variante)}</span>` : ''}</td><td>${para(x.condicoes || '')}</td></tr>`).join('')}</table>`\n    : '<p>Nenhum decryptor público conhecido para esta família. A recuperação depende de backup.</p>'}`;\n}\nif (candidatos.length) {\n  corpo += `\n<h2>Famílias candidatas</h2>\n<p>${esc(totalCand)} família(s) batem com os indicadores. As ${candidatos.length} primeiras, com a evidência:</p>\n${candidatos.map((c) => `<h3>${esc(c.nome)}${c.mitre ? ` <span class=\"muted\">· MITRE ${esc(c.mitre)}</span>` : ''}</h3>${li(c.evidencias, evLi)}${c.grupos.length ? `<p class=\"muted\">Grupos: ${esc(c.grupos.map((g) => g.nome).join(', '))}</p>` : ''}`).join('')}`;\n}\nif (ident === 'inconclusive') {\n  corpo += `\n<h2>Nenhuma família identificada</h2>\n<p>${esc(fId)}</p>\n<h2>O que coletar a mais</h2>${li(coletar, (x) => `<li>${esc(x)}</li>`)}`;\n}\nif (sugestoes.length) corpo += `<h2>Indicadores que afinariam</h2>${li(sugestoes, (x) => `<li>${esc(x)}</li>`)}`;\nif (pacote) {\n  corpo += `<h2>Pacote de detecção</h2><p>${esc(fPack)}</p>`;\n  if (!pacote.erro && Object.keys(pacote.por_tipo).length) corpo += `<p class=\"muted\">Por tipo: ${esc(Object.entries(pacote.por_tipo).map(([t, n]) => `${n} ${t}`).join(', '))}</p>`;\n  for (const y of (pacote.yara || [])) corpo += `<details><summary>${esc(y.arquivo)}</summary><pre style=\"white-space:pre-wrap;font-size:12px\">${esc(y.conteudo)}</pre></details>`;\n}\ncorpo += `\n<h2>Próximos passos</h2><ol>${passos.map((p) => `<li>${esc(p)}</li>`).join('')}</ol>\n${avisos.length ? `<h2>Avisos</h2>${li(avisos, (x) => `<li>${esc(x)}</li>`)}` : ''}\n<h2>${esc(guia ? guia.titulo : 'Guia de recuperação')}</h2>\n${guia ? `${guia.caiu_para_geral ? '<p class=\"warn\">A família não tem guia próprio publicado neste idioma. Abaixo, o guia geral.</p>' : ''}<p class=\"muted\">Guia ${esc(guia.escopo)}${guia.publicado_em ? ', publicado em ' + esc(guia.publicado_em) : ''}.</p>${guiaHtml(guia.blocos)}`\n    : `<p>O guia não pôde ser carregado. Use o <a href=\"${esc(GUIA_GERAL_URL)}\" rel=\"noopener noreferrer\">guia geral no Vexday</a>.</p>`}\n${falhas.length ? `<h2>Consultas que falharam</h2>${li(falhas, (x) => `<li>${esc(x)}</li>`)}` : ''}`;\n\nconst html = page(`${titulo} | Vexday`, `\n<p class=\"muted\">Vexday · Identificação de ransomware</p>\n<h1>${esc(ident === 'probable' ? familia.nome : 'Família não confirmada')}</h1>\n<p><span class=\"tag ${cls}\">Identificação ${esc(IDENT[ident])}</span><span class=\"muted\">${esc(fEntrada)}</span></p>\n<p>${esc(fId)}</p>\n<p>${esc(fRec)}</p>\n${corpo}\n<footer>\n<p>Fontes: ${esc(rep.attribution.join(' · '))}${rep.attribution_url ? ` · <a href=\"${esc(safeUrl(rep.attribution_url))}\" rel=\"noopener noreferrer\">todas as fontes e licenças</a>` : ''}</p>\n<p>Gerado por Vexday | T06 · ${esc(consultas)} consulta(s). Confira a fonte antes de agir.</p>\n</footer>`);\n\nreturn out({ ok: true, source: inp.source, report: rep, markdown, html, notifyItems });\n"
      },
      "id": "111739ab-835f-c0c7-8efc-83e3dd374a14"
    },
    {
      "name": "Itens de notificação",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3100,
        -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.\nreturn ($input.first().json.notifyItems || []).map((n) => ({ json: n }));\n"
      },
      "id": "c6bb184e-5474-deaa-d7cb-e18903f1c29c"
    },
    {
      "name": "Envia notificações",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3320,
        -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": "924f2d2f-2eed-d436-fb80-d344e7bc159e"
    },
    {
      "name": "Veio do formulário?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3100,
        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": "12b83294-6ebc-a5d7-cbb0-8e95ea88cfec"
    },
    {
      "name": "Mostra relatório",
      "type": "n8n-nodes-base.form",
      "typeVersion": 2.3,
      "position": [
        3320,
        -80
      ],
      "parameters": {
        "operation": "completion",
        "respondWith": "showText",
        "responseText": "={{ $json.html }}"
      },
      "id": "051f70cc-7566-b0fd-86dc-3254583800f7"
    },
    {
      "name": "Resposta JSON",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3320,
        80
      ],
      "parameters": {
        "mode": "raw",
        "jsonOutput": "={{ JSON.stringify({ ...$json.report, markdown: $json.markdown }) }}",
        "options": {}
      },
      "id": "d49c1e1d-e134-0dac-485f-473ee879f47f"
    },
    {
      "name": "Leia-me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -460,
        -300
      ],
      "parameters": {
        "content": "## Vexday | T06 - Identificação de ransomware\n\nRecebe o que foi achado na máquina (extensão, nome da nota, hash, família ou grupo) e devolve a família provável com a evidência, o estado de recuperação por variante, os decryptors (só link oficial), o guia de recuperação e o pacote de detecção do grupo. Sem IA: tudo vem do catálogo do Vexday.\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 identificação gasta cota.\n3. Ajuste o Config e ative.\n\nPlano: SOC ou MSSP\nCusto: 2 consultas (ambígua ou inconclusiva) a 5 (provável com grupo); 6 se o guia da família for recusado",
        "width": 420,
        "height": 520
      },
      "id": "fa3744df-1e4a-0471-3eb6-992987a93484"
    },
    {
      "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 (guia e textos do Vexday)\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": "4b38e2f9-9879-e71e-ddfc-8054170c3a1a"
    },
    {
      "name": "Webhook doc",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -460,
        260
      ],
      "parameters": {
        "content": "### Webhook\n`POST /webhook/vexday-t06-ransomware` com o header de autenticação:\n```json\n{\"extensao\": \".akira\", \"nota\": \"akira_readme.txt\",\n \"hash\": \"<sha256>\", \"familia\": \"Akira\", \"grupo\": \"Akira\", \"lang\": \"pt\"}\n```\nPelo menos um campo. Resposta JSON: `ok`, `erro`, relatório e `markdown`.",
        "width": 420,
        "height": 250,
        "color": 7
      },
      "id": "8e3eae30-9b44-2fe2-85a1-badd3032813b"
    }
  ],
  "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": "Entrada válida?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Entrada válida?": {
      "main": [
        [
          {
            "node": "Pede search",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Monta relatório",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pede search": {
      "main": [
        [
          {
            "node": "Vexday MCP search",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP search": {
      "main": [
        [
          {
            "node": "Planeja consultas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Planeja consultas": {
      "main": [
        [
          {
            "node": "Tem consultas?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tem consultas?": {
      "main": [
        [
          {
            "node": "Separa consultas",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Monta relatório",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Separa consultas": {
      "main": [
        [
          {
            "node": "Vexday MCP detalhes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP detalhes": {
      "main": [
        [
          {
            "node": "Confere guia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confere guia": {
      "main": [
        [
          {
            "node": "Guia geral?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Guia geral?": {
      "main": [
        [
          {
            "node": "Vexday MCP guia geral",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Monta relatório",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP guia geral": {
      "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": []
}
