{
  "name": "Vexday | T04 - Boletim semanal de ameaças (v0.1)",
  "nodes": [
    {
      "name": "Segunda 08:10",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        100
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "10 8 * * 1"
            }
          ]
        }
      },
      "id": "299bc30e-08e6-db3e-21a0-c0671e2238b9"
    },
    {
      "name": "Executar agora (POST)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "00a76711-5707-42a6-7fc1-b42aecdd109a",
      "parameters": {
        "httpMethod": "POST",
        "path": "vexday-t04-executar",
        "authentication": "basicAuth",
        "responseMode": "onReceived",
        "options": {}
      },
      "id": "7579df9a-31fb-2389-7259-92f19153b68d"
    },
    {
      "name": "Config",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        200
      ],
      "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": "a17fa375-9141-e547-5be7-45c99ae76790",
              "name": "janela_dias",
              "value": "7",
              "type": "string"
            },
            {
              "id": "145031a4-71fb-f3ae-b0f1-81675e122902",
              "name": "pais",
              "value": "BR",
              "type": "string"
            },
            {
              "id": "84a94b2d-c5c1-595d-ae03-7fa9275b112e",
              "name": "setores_interesse",
              "value": "[\"Financial Services\", \"Technology\"]",
              "type": "string"
            },
            {
              "id": "4188319f-5db2-acc0-31a4-14fa8ec6ba2f",
              "name": "cliente",
              "value": "",
              "type": "string"
            },
            {
              "id": "303ab8fb-6501-b84c-446c-2f9b6abe2f00",
              "name": "lang",
              "value": "pt",
              "type": "string"
            },
            {
              "id": "f23898f2-26e4-cf75-9c11-eac15b1594bd",
              "name": "url_relatorio",
              "value": "",
              "type": "string"
            },
            {
              "id": "66e6c627-5ffd-d558-a8ea-57ed101f990c",
              "name": "canais",
              "value": "[]",
              "type": "string"
            }
          ]
        }
      },
      "id": "cfdeb7f6-2594-2a59-b925-b931e094930c"
    },
    {
      "name": "Pede dados",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        200
      ],
      "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// Três consultas: incidentes verificados, vítimas de ransomware e alertas da stack na janela.\nconst cfg = $('Config').first().json;\nconst dias = Math.max(1, Number(cfg.janela_dias || 7));\nconst desde = isoDaysAgo(dias);\nconst pais = cfg.pais || 'BR';\nconst tag = String(cfg.cliente || '').trim() || null;\nreturn [\n  mcpReq('search_incidents', { country: pais, since: desde, page_size: 20, lang: cfg.lang || 'pt' }, { k: 'incidentes' }),\n  mcpReq('search_victims', { country: pais, since: desde, page_size: 100 }, { k: 'vitimas' }),\n  // limit 500 é o máximo do list_my_alerts (campo note, 20/11). Mesmo custo: 1 consulta.\n  mcpReq('list_my_alerts', tag ? { days: dias, tag, limit: 500 } : { days: dias, limit: 500 }, { k: 'alertas' }),\n];\n"
      },
      "id": "33630979-279d-f0bf-c6ee-b807778f80df"
    },
    {
      "name": "Vexday MCP",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        680,
        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": "93e388c9-3e26-ce39-0464-8951cf1e6008"
    },
    {
      "name": "Monta boletim",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        200
      ],
      "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// Monta o boletim: sua stack, incidentes verificados no país, ransomware por setor e grupo.\nconst cfg = $('Config').first().json;\nconst canais = cfgJson(cfg, 'canais', []);\nconst setoresCfg = cfgJson(cfg, 'setores_interesse', []);\nconst setores = setoresCfg.map((s) => String(s).toLowerCase());\nconst VER = { real: 'real', unverified: 'não verificado', false: 'falso', fake: 'falso', recycled: 'reciclado', partial: 'parcial' };\nconst CONF = { confirmed: 'confirmado', claimed: 'só alegado', likely: 'provável', probable: 'provável', possible: 'possível', low: 'baixa', medium: 'média', high: 'alta' };\nconst tr = (m, v) => m[String(v || '').toLowerCase()] || v || 'n/d';\nconst dias = Math.max(1, Number(cfg.janela_dias || 7));\nconst cliente = String(cfg.cliente || '').trim();\nconst res = Object.fromEntries(zipMcp($('Pede dados').all(), $input.all()).map((r) => [r.ctx.k, r]));\nconst fatal = Object.values(res).find((r) => r.quota || r.auth);\nif (fatal) throw new Error(`Vexday: ${fatal.err}`);\n\nconst inc = res.incidentes?.data?.results || [];\n// Igual aos alertas: o search_incidents devolve só a página (page_size 20) e o total real (piloto de 20/11).\nconst incTotal = Math.max(Number(res.incidentes?.data?.total) || 0, inc.length);\nconst vit = res.vitimas?.data?.results || [];\nconst vitTotal = res.vitimas?.data?.total ?? vit.length;\nconst al = res.alertas?.data?.alerts || [];\n// O list_my_alerts corta no limit e devolve o total real: conte pelo total, nunca pelo tamanho da lista.\nconst alTotal = Math.max(Number(res.alertas?.data?.total) || 0, al.length);\nconst alCorte = al.length < alTotal ? ` (lista com os ${al.length} mais recentes)` : '';\nconst avisos = Object.values(res).filter((r) => r.err).map((r) => `${r.tool}: ${r.err}`);\n\nconst conta = (arr, f) => Object.entries(arr.reduce((a, x) => { const k = f(x) || 'n/d'; a[k] = (a[k] || 0) + 1; return a; }, {})).sort((a, b) => b[1] - a[1]);\nconst porSetor = conta(vit, (v) => v.sector);\nconst porGrupo = conta(vit, (v) => v.group_name);\nconst doSetor = vit.filter((v) => setores.includes(String(v.sector || '').toLowerCase()));\nconst imediatos = al.filter((a) => a.level === 'immediate');\nconst RAZAO = { new: 'nova', kev: 'KEV', exploit: 'PoC pública', epss: 'EPSS', severity: 'gravidade', gov_br: 'gov.br', malicious: 'pacote malicioso',\n  domain_ransomware: 'domínio em leak site', domain_employees: 'funcionários em infostealer', domain_users: 'usuários em infostealer' };\nconst alvo = (a) => a.cve_id || a.advisory || a.domain || 'n/d';\nconst fim = new Date().toISOString().slice(0, 10), ini = isoDaysAgo(dias);\n\nconst html = page(`Boletim semanal de ameaças${cliente ? ' · ' + cliente : ''}`, `\n<p class=\"muted\">Vexday · Boletim de ameaças · ${esc(ini)} a ${esc(fim)}${cliente ? ' · ' + esc(cliente) : ''}</p>\n<h1>A semana em ameaças</h1>\n<div class=\"grid\">\n<div class=\"card\"><span class=\"muted\">Alertas da sua stack</span><b>${alTotal}</b><span class=\"muted\">${imediatos.length} imediato(s)${al.length < alTotal ? ` entre os ${al.length} mais recentes` : ''}</span></div>\n<div class=\"card\"><span class=\"muted\">Incidentes verificados</span><b>${incTotal}</b><span class=\"muted\">${esc(cfg.pais || 'BR')}</span></div>\n<div class=\"card\"><span class=\"muted\">Vítimas de ransomware</span><b>${esc(vitTotal)}</b><span class=\"muted\">alegações em leak sites</span></div>\n<div class=\"card\"><span class=\"muted\">Do seu setor</span><b>${doSetor.length}</b><span class=\"muted\">${esc(setoresCfg.join(', ') || 'configure setores_interesse')}</span></div>\n</div>\n${avisos.length ? `<p class=\"warn\">${esc(avisos.join(' | '))}</p>` : ''}\n<h2>Sua stack</h2>\n${al.length ? `${alCorte ? `<p class=\"muted\">${esc(alTotal)} alerta(s) na janela${esc(alCorte)}.</p>` : ''}<table><tr><th>Nível</th><th>Alvo</th><th>Motivo</th><th>Tecnologia / cliente</th><th>Quando</th></tr>${al.slice(0, 40).map((a) => `<tr><td>${esc(a.level === 'immediate' ? 'imediato' : a.level)}</td><td>${a.cve_id ? `<a href=\"https://vexday.io/pt/cve/${esc(a.cve_id)}\" rel=\"noopener noreferrer\">${esc(a.cve_id)}</a>` : esc(alvo(a))}</td><td>${esc(RAZAO[a.reason] || a.reason)}</td><td>${esc((a.matched || []).map((m) => m.name + ((m.tags || []).length ? ` (${m.tags.join(', ')})` : '')).join('; '))}</td><td>${esc(day(a.created_at))}</td></tr>`).join('')}</table>` : '<p class=\"muted\">Nenhum alerta na semana.</p>'}\n<h2>Incidentes verificados (método MORGUE)</h2>\n${inc.length ? `${inc.length < incTotal ? `<p class=\"muted\">Mostrando os ${inc.length} mais recentes de ${esc(incTotal)}.</p>` : ''}<ul>${inc.map((i) => `<li><b>${esc(i.headline)}</b> <span class=\"muted\">· ${esc(i.victim || '')} · ${esc(i.sector || '')} · veredito: ${esc(tr(VER, i.verdict))} · ${esc(tr(CONF, i.confidence))}</span><br>${esc(String(i.bluf || '').slice(0, 320))}${String(i.bluf || '').length > 320 ? '…' : ''}</li>`).join('')}</ul>` : '<p class=\"muted\">Nenhum incidente publicado na janela.</p>'}\n<h2>Ransomware no país</h2>\n<p>${esc(vitTotal)} organização(ões) listada(s) em sites de extorsão.${vit.length < vitTotal ? ` Analisando as ${vit.length} mais recentes.` : ''}</p>\n${porGrupo.length ? `<p><b>Grupos mais ativos:</b> ${porGrupo.slice(0, 6).map(([g, n]) => `${esc(g)} (${n})`).join(', ')}</p>` : ''}\n${porSetor.length ? `<p><b>Setores mais atingidos:</b> ${porSetor.slice(0, 6).map(([s, n]) => `${esc(s)} (${n})`).join(', ')}</p>` : ''}\n${doSetor.length ? `<h2>No seu setor</h2><table><tr><th>Organização</th><th>Grupo</th><th>Setor</th><th>Data</th></tr>${doSetor.map((v) => `<tr><td>${esc(v.victim)}</td><td>${esc(v.group_name)}</td><td>${esc(v.sector)}</td><td>${esc(v.attack_date)}</td></tr>`).join('')}</table>` : ''}\n<footer><p>Vítimas de ransomware são alegações dos criminosos, não confirmações das organizações. Fontes: Vexday (sites de vazamento dos grupos, CISA KEV, CTIR Gov, CISC e incidentes verificados pelo Vexday).</p></footer>`);\n$getWorkflowStaticData('global').ultimo = { html, em: Date.now() };\n\nconst urlRel = String(cfg.url_relatorio || '').trim();\nconst linhas = [\n  `Sua stack: ${alTotal} alerta(s)${alCorte}, ${imediatos.length} imediato(s)${imediatos.length ? ': ' + imediatos.slice(0, 5).map(alvo).join(', ') : ''}`,\n  `Incidentes verificados: ${incTotal}${inc.length ? ' · ' + inc.slice(0, 3).map((i) => i.headline).join(' | ').slice(0, 300) : ''}`,\n  `Ransomware: ${vitTotal} vítima(s)${porGrupo.length ? ' · grupos: ' + porGrupo.slice(0, 3).map(([g, n]) => `${g} (${n})`).join(', ') : ''}`,\n  doSetor.length ? `Atenção: ${doSetor.length} no seu setor: ${doSetor.slice(0, 4).map((v) => v.victim).join(', ')}` : 'Nenhuma vítima nos setores monitorados.',\n  ...avisos.map((a) => `Aviso: ${a}`),\n];\nconst notifyItems = buildNotify(canais, { titulo: `Boletim semanal de ameaças${cliente ? ' · ' + cliente : ''}`, linhas,\n  url: /^https?:\\/\\//.test(urlRel) ? urlRel : null, nivel: imediatos.length || doSetor.length ? 2 : 1, rodape: 'Vexday | T04 · 3 consultas' }, cliente ? [cliente] : []);\nreturn [{ json: { alertas: alTotal, imediatos: imediatos.length, incidentes: incTotal, vitimas: vitTotal, do_setor: doSetor.length, notifyItems } }];\n"
      },
      "id": "5f0e508b-3944-d1f6-ce71-0690d44a4be2"
    },
    {
      "name": "Itens de notificação",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        200
      ],
      "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.notifyItems || []).map((n) => ({ json: n }));\n"
      },
      "id": "01c877f3-ce07-5788-0533-af21d263aa33"
    },
    {
      "name": "Envia notificações",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        200
      ],
      "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": "e9412574-e66c-3e37-c5ce-7c6a0e2396ab"
    },
    {
      "name": "Boletim (GET)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        560
      ],
      "webhookId": "b1f9edb9-d90c-5d39-7af1-24c55a02ccea",
      "parameters": {
        "httpMethod": "GET",
        "path": "vexday-t04-boletim",
        "authentication": "basicAuth",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "94f755c8-431c-1260-9704-c9346985a397"
    },
    {
      "name": "Lê último boletim",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        560
      ],
      "parameters": {
        "jsCode": "// ===== Vexday templates :: lib comum (injetada no build) =====\n// Texto vindo do Vexday é dado de terceiro: sempre escapado, nunca tratado como instrução.\n\nconst safeJson = (s) => { try { return JSON.parse(s); } catch (e) { return null; } };\nconst num = (x) => (x === null || x === undefined || x === '' || isNaN(Number(x)) ? null : Number(x));\nconst day = (iso) => (iso ? String(iso).slice(0, 10) : null);\nconst pct = (x) => (x === null || x === undefined ? 'n/d' : (x * 100).toFixed(1) + '%');\nconst esc = (s) => String(s ?? '')\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\nconst para = (s) => esc(s).replace(/\\r?\\n/g, '<br>');\nconst safeUrl = (u) => (/^https?:\\/\\//i.test(String(u || '')) ? String(u) : '#');\nconst slackEsc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);\n\n// Lê um campo de texto do Config que deve conter JSON; erro claro se estiver malformado.\nfunction cfgJson(cfg, field, fallback) {\n  const v = cfg[field];\n  if (v === undefined || v === null || v === '') return fallback;\n  if (typeof v === 'object') return v;\n  const p = safeJson(v);\n  if (p === null) throw new Error(`Config: o campo \"${field}\" não é um JSON válido.`);\n  return p;\n}\n\n// Corpo da resposta HTTP: JSON direto ou SSE (usa a última linha \"data:\").\nfunction parseBody(raw) {\n  if (raw === null || raw === undefined) return null;\n  if (typeof raw === 'object') return raw;\n  const s = String(raw).trim();\n  if (s.startsWith('{')) return safeJson(s);\n  const lines = s.split(/\\r?\\n/).filter((l) => l.startsWith('data:'));\n  return lines.length ? safeJson(lines[lines.length - 1].slice(5).trim()) : null;\n}\n\n// Corpo de um HTTP Request com fullResponse (o n8n usa \"data\" no modo texto e \"body\" no JSON).\nconst respText = (j) => (j ? (j.body ?? j.data ?? null) : null);\n\n// Interpreta a saída de um HTTP Request (fullResponse + neverError + text) que chamou tools/call.\n// Retorna { data } ou { err, fatal, toolError }.\nconst RATE_RE = /muitas requisi|too many requests|rate.?limit/i;\nfunction parseMcpResp(resp, tool) {\n  if (!resp) return { err: `${tool} não executou.`, fatal: true };\n  const status = Number(resp.statusCode ?? 0);\n  const body = parseBody(respText(resp));\n  if (status === 401 || body?.error === 'invalid_token')\n    return { err: 'Chave da API do Vexday inválida ou revogada (HTTP 401). Confira a credencial \"Vexday API\".', fatal: true, auth: true };\n  if (status === 403) return { err: `O plano da conta não libera ${tool} (HTTP 403).`, fatal: true };\n  if (status === 429) return { err: 'Limite diário de consultas do Vexday atingido (HTTP 429).', fatal: true, quota: true };\n  if (status >= 400) return { err: `Erro HTTP ${status} ao chamar ${tool}.`, fatal: true };\n  if (!body) return { err: `Resposta ilegível de ${tool}.`, fatal: true };\n  if (body.error) return { err: `Erro em ${tool}: ${body.error.message || JSON.stringify(body.error)}`, fatal: true };\n  const r = body.result || {};\n  const text = r.content?.[0]?.text ?? '';\n  if (r.isError) {\n    const msg = String(text).replace(/^Error executing tool [\\w]+:\\s*/, '');\n    // Limite por minuto: o Vexday devolve como erro da tool com HTTP 200, não 429 (visto em 20/11: \"máx 30/min\").\n    if (RATE_RE.test(msg)) return { err: `Limite por minuto do Vexday atingido em ${tool}: ${msg.slice(0, 160)}`, fatal: true, quota: true, rate: true };\n    return { err: msg, toolError: true };\n  }\n  const data = safeJson(text);\n  if (data === null) return { err: `Resposta inesperada de ${tool}.`, fatal: true };\n  return { data };\n}\n\n// Item de requisição para o nó \"Vexday MCP\". O corpo JSON-RPC vai pronto em \"rpc\":\n// o sandbox de expressões do n8n bloqueia acesso a campos chamados \"arguments\".\nfunction mcpReq(tool, args, ctx) {\n  return { json: { tool, args: args || {}, ctx: ctx ?? null,\n    rpc: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args || {} } }) } };\n}\n\n// Junta as requisições preparadas com as respostas do HTTP Request (mesma ordem, 1 para 1).\nfunction zipMcp(reqItems, respItems) {\n  return reqItems.map((rq, i) => {\n    const r = parseMcpResp(respItems[i]?.json, rq.json.tool);\n    return { ...r, tool: rq.json.tool, args: rq.json.args, ctx: rq.json.ctx };\n  });\n}\n\nfunction attributionOf(results) {\n  const names = new Set();\n  for (const r of results) for (const s of (r?.data?.attribution?.sources || [])) names.add(s.name);\n  return [...names];\n}\n\n// Página HTML com CSP rígida no <meta> (sem script). opts.claro = tema claro, mais seguro em e-mail.\nconst CSS_ESCURO = `body{margin:0;background:#0b0b0c;color:#f2f1ee;font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\nmain{max-width:880px;margin:0 auto;padding:32px 20px 64px}\nh1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:32px 0 8px;border-top:1px solid #26262a;padding-top:20px}\n.muted{color:#8e8e93}.tag{display:inline-block;padding:2px 10px;border-radius:99px;font-size:13px;font-weight:600;margin-right:6px}\n.crit{background:#ff453a22;color:#ff6b61}.high{background:#ff9f0a22;color:#ffb340}.med{background:#ffd60a22;color:#ffd60a}.low{background:#30d15822;color:#4cd964}\n.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin:16px 0}\n.card{background:#141416;border:1px solid #26262a;border-radius:10px;padding:12px 14px}.card b{display:block;font-size:20px}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #26262a;vertical-align:top}th{color:#8e8e93;font-weight:600}\na{color:#f96a02}ul{padding-left:20px}li{margin:3px 0}.warn{background:#ff9f0a14;border:1px solid #ff9f0a55;border-radius:10px;padding:10px 14px}\n.err{background:#ff453a14;border:1px solid #ff453a55;border-radius:10px;padding:14px}footer{margin-top:40px;font-size:13px;color:#8e8e93}`;\nconst CSS_CLARO = `body{margin:0;background:#ffffff;color:#1c1c1e;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif}\nmain{max-width:720px;margin:0 auto;padding:28px 20px 48px}h1{font-size:24px;margin:0 0 4px}\nh2{font-size:16px;margin:28px 0 8px;border-top:1px solid #e5e5ea;padding-top:18px}.muted{color:#6e6e73}\ntable{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid #e5e5ea;vertical-align:top}th{color:#6e6e73;font-weight:600}\na{color:#c2410c}ul{padding-left:20px}li{margin:3px 0}.warn{background:#fff4e5;border:1px solid #f5c27a;border-radius:8px;padding:10px 14px}\nfooter{margin-top:36px;font-size:12px;color:#6e6e73}`;\nfunction page(title, inner, opts) {\n  const claro = !!(opts && opts.claro);\n  const bodyStyle = claro ? ' style=\"margin:0;background:#ffffff;color:#1c1c1e\"' : '';\n  return `<!DOCTYPE html><html lang=\"pt-BR\"><head><meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src https: data:\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(title)}</title>\n<style>${claro ? CSS_CLARO : CSS_ESCURO}</style></head><body${bodyStyle}><main>${inner}</main></body></html>`;\n}\n\n// ---------- notificações ----------\n// canais: [{ \"tipo\": \"discord|slack|teams|json\", \"url\": \"https://...\", \"tags\": [\"cliente-acme\"] (opcional) }]\n// msg: { titulo, linhas: [string], url, nivel: 0..3, rodape }\n// Retorna itens prontos para um HTTP Request genérico: { url, body }.\nconst NIVEL_TAG = ['[BAIXA]', '[MÉDIA]', '[ALTA]', '[CRÍTICA]'];\nconst NIVEL_TEAMS = ['Good', 'Default', 'Warning', 'Attention'];\nconst NIVEL_COR = ['2ECC71', 'F1C40F', 'E67E22', 'E74C3C'];\n\nfunction canaisPara(canais, tags) {\n  const ts = (tags && tags.length) ? tags : [];\n  return (canais || []).filter((c) => {\n    if (!/^https:\\/\\//i.test(String(c.url || '')) && !/^http:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?\\//i.test(String(c.url || ''))) return false; // http só local\n    if (!c.tags || !c.tags.length) return true;           // canal geral recebe tudo\n    return ts.some((t) => c.tags.includes(t));            // canal de cliente só recebe o cliente\n  });\n}\n\nfunction buildNotify(canais, msg, tags) {\n  const nivel = Math.max(0, Math.min(3, msg.nivel ?? 0));\n  const out = [];\n  for (const c of canaisPara(canais, tags)) {\n    const tipo = String(c.tipo || 'json').toLowerCase();\n    let body;\n    if (tipo === 'discord') {\n      const txt = [`**${NIVEL_TAG[nivel]} ${msg.titulo}**`, ...(msg.linhas || []), msg.url || '', msg.rodape ? `-# ${msg.rodape}` : '']\n        .filter(Boolean).join('\\n');\n      body = { content: txt.slice(0, 1990), allowed_mentions: { parse: [] } };\n    } else if (tipo === 'slack') {\n      const txt = [`*${NIVEL_TAG[nivel]} ${slackEsc(msg.titulo)}*`, ...(msg.linhas || []).map(slackEsc),\n        msg.url ? `<${msg.url}|Abrir>` : '', msg.rodape ? `_${slackEsc(msg.rodape)}_` : ''].filter(Boolean).join('\\n');\n      body = { text: txt.slice(0, 39000) };\n    } else if (tipo === 'teams') {\n      // Webhook de Workflows do Teams (Power Automate) com Adaptive Card.\n      const items = [\n        { type: 'TextBlock', text: `${NIVEL_TAG[nivel]} ${msg.titulo}`, color: NIVEL_TEAMS[nivel], weight: 'Bolder', size: 'Medium', wrap: true },\n        ...(msg.linhas || []).map((l) => ({ type: 'TextBlock', text: l, wrap: true, spacing: 'Small' })),\n      ];\n      if (msg.rodape) items.push({ type: 'TextBlock', text: msg.rodape, isSubtle: true, size: 'Small', wrap: true });\n      const card = { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', type: 'AdaptiveCard', version: '1.4', body: items };\n      if (msg.url) card.actions = [{ type: 'Action.OpenUrl', title: 'Abrir', url: msg.url }];\n      body = { type: 'message', attachments: [{ contentType: 'application/vnd.microsoft.card.adaptive', content: card }] };\n    } else {\n      body = { titulo: msg.titulo, linhas: msg.linhas || [], url: msg.url || null, nivel, tags: tags || [], rodape: msg.rodape || null };\n    }\n    out.push({ url: c.url, tipo, body });\n  }\n  return out;\n}\n\n// ---------- normalização de nomes (fornecedores x vítimas) ----------\nconst LEGAL = /\\b(ltda|ltd|eireli|me|epp|s\\.?\\s?a\\.?|sa|inc|incorporated|corp|corporation|co|company|cia|companhia|llc|plc|gmbh|ag|bv|nv|srl|spa|group|grupo|holding|holdings)\\b/g;\nfunction normName(s) {\n  return String(s || '')\n    .normalize('NFD').replace(/[̀-ͯ]/g, '')\n    .toLowerCase()\n    .replace(/^https?:\\/\\//, '').replace(/^www\\./, '')\n    .replace(/\\.(com|net|org|gov|edu|io|co)(\\.[a-z]{2})?$/, '').replace(/\\.[a-z]{2}$/, '')\n    .replace(/[^a-z0-9 ]+/g, ' ')\n    .replace(LEGAL, ' ')\n    .replace(/\\s+/g, ' ').trim();\n}\n\n// Comparação de tempo constante para hex (HMAC).\nfunction timingSafeEqualHex(a, b) {\n  a = String(a || ''); b = String(b || '');\n  let diff = a.length ^ b.length;\n  const n = Math.max(a.length, b.length);\n  for (let i = 0; i < n; i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);\n  return diff === 0;\n}\n// ===== fim da lib =====\n\nconst sd = $getWorkflowStaticData('global');\nconst html = sd.ultimo?.html || page('Sem relatório', '<h1>Ainda não há relatório</h1><p class=\"muted\">Rode o workflow uma vez (execução agendada ou manual publicada).</p>');\nreturn [{ json: { html } }];\n"
      },
      "id": "74228e54-306d-8d93-f0b1-f74b56ecb83e"
    },
    {
      "name": "Devolve HTML",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        460,
        560
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.html }}",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "text/html; charset=utf-8"
              },
              {
                "name": "Content-Security-Policy",
                "value": "default-src 'none'; style-src 'unsafe-inline'"
              },
              {
                "name": "Cache-Control",
                "value": "no-store"
              }
            ]
          }
        }
      },
      "id": "ec8a68c9-ab4b-5ef2-5963-4d71dd74473f"
    },
    {
      "name": "Leia-me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        -330
      ],
      "parameters": {
        "content": "## Vexday | T04 - Boletim semanal de ameaças\n\nToda segunda: o que mudou na sua stack, os incidentes verificados pelo Vexday no país (conteúdo próprio, método MORGUE) e o ransomware da semana por grupo e setor, com destaque para os setores que você acompanha.\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 nos webhooks `Executar agora` e `Boletim (GET)`.\n3. Ajuste o Config e ative.\n\nPlano: SOC/MSSP\nCusto: 3 consultas por boletim",
        "width": 440,
        "height": 440
      },
      "id": "55341811-4733-d588-e51f-c7ee02b41a00"
    },
    {
      "name": "Ajuda do Config",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        200,
        -470
      ],
      "parameters": {
        "content": "### Config\n- `setores_interesse`: setores como o Vexday escreve nas vítimas (inglês): `Financial Services`, `Healthcare`, `Technology`, `Manufacturing`, `Government`, `Education`…\n- `cliente`: tag de um cliente (filtra os alertas e roteia os canais)\n- `url_relatorio`: URL de produção do `Boletim (GET)`\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": 480,
        "height": 380,
        "color": 5
      },
      "id": "cf572802-24da-6b21-dda6-c3ad0bb332e3"
    }
  ],
  "connections": {
    "Segunda 08:10": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Executar agora (POST)": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Pede dados",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pede dados": {
      "main": [
        [
          {
            "node": "Vexday MCP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vexday MCP": {
      "main": [
        [
          {
            "node": "Monta boletim",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Monta boletim": {
      "main": [
        [
          {
            "node": "Itens de notificação",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Itens de notificação": {
      "main": [
        [
          {
            "node": "Envia notificações",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Boletim (GET)": {
      "main": [
        [
          {
            "node": "Lê último boletim",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lê último boletim": {
      "main": [
        [
          {
            "node": "Devolve HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
