all repos — red-anatomia @ 43cc40161c75c7c9bb5bef2c1ce2d551b7f24484

red-anatomia

src/report/model.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
import type {
  Detection,
  Observations,
  Report,
  InfraResumo,
  SegurancaResumo,
  Rastreamento,
} from '../core/types.js';
import { detectar } from '../detection/engine.js';
import { heuristicas } from '../detection/heuristics.js';
import { carregarDataset } from '../detection/dataset.js';
import { TECNOLOGIAS, significadoGenerico } from '../knowledge/tecnologias.js';
import { inferirArquitetura } from '../knowledge/arquitetura.js';

export function montarRelatorio(obs: Observations): Report {
  const doMotor = detectar(obs);
  const doHeuristico = heuristicas(obs, doMotor);
  const deteccoes = enriquecer([...doMotor, ...doHeuristico]);

  return {
    alvo: {
      urlSolicitada: obs.urlSolicitada,
      urlFinal: obs.urlFinal || obs.urlSolicitada,
      modo: obs.modo,
    },
    redirecionamentos: obs.redirecionamentos,
    deteccoes,
    infraestrutura: montarInfra(obs, deteccoes),
    anatomia: obs.anatomia,
    arquiteturaProvavel: inferirArquitetura(deteccoes, obs),
    seguranca: montarSeguranca(obs),
    rastreamento: montarRastreamento(deteccoes, obs),
    alertasLegado: montarAlertasLegado(obs, deteccoes),
    lighthouse: obs.lighthouse,
    naoDeterminado: montarNaoDeterminado(obs, deteccoes),
    avisos: obs.avisos,
  };
}

function enriquecer(deteccoes: Detection[]): Detection[] {
  const ds = carregarDataset();
  return deteccoes.map((d) => ({
    ...d,
    significado:
      TECNOLOGIAS[d.nome]?.significado ??
      ds.tecnologias[d.nome]?.description ??
      significadoGenerico(d.categorias),
  }));
}

const CABECALHOS_SEGURANCA: [string, string][] = [
  ['HSTS', 'strict-transport-security'],
  ['CSP', 'content-security-policy'],
  ['X-Frame-Options', 'x-frame-options'],
  ['X-Content-Type-Options', 'x-content-type-options'],
  ['Referrer-Policy', 'referrer-policy'],
  ['Permissions-Policy', 'permissions-policy'],
];

const NOTAS = ['F', 'F', 'E', 'D', 'C', 'B', 'A'];

function montarSeguranca(obs: Observations): SegurancaResumo | undefined {
  if (!Object.keys(obs.headers).length) return undefined;
  const presentes: string[] = [];
  const ausentes: string[] = [];
  for (const [rotulo, header] of CABECALHOS_SEGURANCA) {
    if (obs.headers[header] != null) presentes.push(rotulo);
    else ausentes.push(rotulo);
  }
  const pontos = presentes.length;
  return { nota: NOTAS[pontos] ?? 'F', pontos, total: CABECALHOS_SEGURANCA.length, presentes, ausentes };
}

const CATEGORIAS_RASTREIO = new Set([
  'Analytics',
  'Tag managers',
  'Advertising',
  'Marketing automation',
  'Customer data platform',
  'Retargeting',
]);

function montarRastreamento(deteccoes: Detection[], obs: Observations): Rastreamento {
  const rastreadores = deteccoes.filter((d) =>
    d.categorias.some((c) => CATEGORIAS_RASTREIO.has(c)),
  ).length;
  return { rastreadores, dominiosTerceiros: dominiosExternos(obs).length };
}

function montarAlertasLegado(obs: Observations, deteccoes: Detection[]): string[] {
  const alertas: string[] = [];
  const feno = obs.html + ' ' + obs.scriptSrc.join(' ') + ' ' + obs.linksAssets.join(' ');

  if (/[?&/=]UA-\d{4,}/.test(feno)) {
    alertas.push('Universal Analytics (UA-…): descontinuado pelo Google em 2023.');
  }
  if (/jquery[.-]migrate/i.test(feno)) {
    alertas.push('jQuery Migrate: costuma indicar base de código legada.');
  }
  if (/\.swf(\?|$|")/i.test(feno)) {
    alertas.push('Adobe Flash (.swf): tecnologia morta desde 2020.');
  }
  if (deteccoes.some((d) => d.nome === 'AngularJS')) {
    alertas.push('AngularJS (Angular 1.x): sem suporte oficial desde 2022.');
  }
  return alertas;
}

function montarInfra(obs: Observations, deteccoes: Detection[]): InfraResumo {
  const protocolo = obs.protocolo
    ? [
        obs.protocolo.http2 ? 'HTTP/2' : 'HTTP/1.1',
        obs.protocolo.http3Anunciado ? 'HTTP/3 anunciado (Alt-Svc)' : undefined,
      ]
        .filter(Boolean)
        .join(' · ')
    : undefined;

  const cdn =
    deteccoes.find((d) => d.categorias.includes('CDN'))?.nome ?? obs.cdnAparente ?? undefined;

  return {
    cdn,
    servidor: obs.servidorAparente,
    protocolo,
    certificado: obs.certificado,
    dns: obs.dns,
    dominiosExternos: dominiosExternos(obs),
    emailNoDns: !!(obs.dns?.mx && obs.dns.mx.length > 0),
  };
}

function dominiosExternos(obs: Observations): string[] {
  let hostAlvo = '';
  try {
    hostAlvo = new URL(obs.urlFinal || obs.urlSolicitada).hostname.replace(/^www\./, '');
  } catch {
    /* ignore */
  }
  const hosts = new Set<string>();
  const fontes = [...obs.scriptSrc, ...obs.linksAssets, ...(obs.browser?.dominiosTerceiros ?? [])];
  for (const ref of fontes) {
    try {
      const h = new URL(ref, obs.urlFinal || obs.urlSolicitada).hostname;
      const raiz = h.replace(/^www\./, '');
      if (raiz && raiz !== hostAlvo && !raiz.endsWith('.' + hostAlvo)) hosts.add(raiz);
    } catch {
      /* relativo, mesmo host */
    }
  }
  return [...hosts].sort().slice(0, 30);
}

function montarNaoDeterminado(obs: Observations, deteccoes: Detection[]): string[] {
  const itens: string[] = [];
  const temCategoria = (c: string) => deteccoes.some((d) => d.categorias.includes(c));
  const tem = (n: string) => deteccoes.some((d) => d.nome === n);

  if (!temCategoria('Databases') && !tem('MySQL')) itens.push('banco de dados utilizado');
  if (!temCategoria('Programming languages')) itens.push('linguagem do servidor');
  if (obs.cdnAparente || temCategoria('CDN')) itens.push('servidor de origem (escondido atrás da CDN)');

  const php = deteccoes.find((d) => d.nome === 'PHP');
  if (php && !php.versao) itens.push('versão exata do PHP');

  if (obs.protocolo && !obs.protocolo.http3Anunciado) {
    itens.push('uso real de HTTP/3 (não anunciado nos cabeçalhos)');
  }
  if (obs.modo === 'rapido') {
    itens.push('conteúdo carregado por JavaScript (rode com --completo para observar)');
  }

  return itens;
}