all repos — red-anatomia @ main

red-anatomia

src/collectors/dns.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
import { Resolver } from 'node:dns/promises';
import type { Observations, DnsInfo } from '../core/types.js';

export async function coletarDns(obs: Observations): Promise<void> {
  let host: string;
  try {
    host = new URL(obs.urlFinal || obs.urlSolicitada).hostname;
  } catch {
    return;
  }

  const resolver = new Resolver({ timeout: 5000, tries: 2 });
  const dns: DnsInfo = {};

  await Promise.all([
    tentar(() => resolver.resolve4(host)).then((r) => r && (dns.a = r)),
    tentar(() => resolver.resolve6(host)).then((r) => r && (dns.aaaa = r)),
    tentar(() => resolver.resolveCname(host)).then((r) => r && (dns.cname = r)),
    tentar(() => resolver.resolveNs(host)).then((r) => r && (dns.ns = r)),
    tentar(() => resolver.resolveTxt(host)).then(
      (r) => r && (dns.txt = r.map((partes) => partes.join(''))),
    ),
    tentar(() => resolver.resolveMx(host)).then(
      (r) => r && (dns.mx = r.map((m) => ({ prioridade: m.priority, servidor: m.exchange }))),
    ),
  ]);

  if (!dns.mx && host.startsWith('www.')) {
    const raiz = host.slice(4);
    const mx = await tentar(() => resolver.resolveMx(raiz));
    if (mx) dns.mx = mx.map((m) => ({ prioridade: m.priority, servidor: m.exchange }));
  }

  obs.dns = dns;
}

async function tentar<T>(fn: () => Promise<T>): Promise<T | undefined> {
  try {
    return await fn();
  } catch {
    return undefined;
  }
}