akra35567 commited on
Commit
c335d2f
Β·
verified Β·
1 Parent(s): 779bddd

Update modules/HFCorrections.js

Browse files
Files changed (1) hide show
  1. modules/HFCorrections.js +82 -91
modules/HFCorrections.js CHANGED
@@ -1,148 +1,137 @@
1
  /**
2
  * ═══════════════════════════════════════════════════════════════════════
3
- * CORREÇÕES HF SPACES - DNS E CONEXΓƒO WHATSAPP
4
  * ═══════════════════════════════════════════════════════════════════════
5
- * Corrige erro: queryA ENODATA web.whatsapp.com
6
- * SoluΓ§Γ΅es aplicadas:
7
- * 1. DNS Resolver Google (8.8.8.8)
8
- * 2. Socket Baileys com IP direto do WhatsApp
9
- * 3. Host header correto para WebSocket
10
- * 4. Agente HTTP otimizado para ambientes restritos
11
  * ═══════════════════════════════════════════════════════════════════════
12
  */
13
 
14
- // ═══════════════════════════════════════════════════════════════════════
15
- // 1. CONFIGURAÇÃO DE DNS GOOGLE (8.8.8.8) - CORREÇÃO PRINCIPAL
16
- // ═══════════════════════════════════════════════════════════════════════
17
-
18
  const dns = require('dns');
 
19
 
20
  // ═══════════════════════════════════════════════════════════════════════
21
- // 2. IP'S DIRECTOS DO WHATSAPP (FALLBACK PARA CASO DNS FALHE)
22
  // ═══════════════════════════════════════════════════════════════════════
23
-
24
  const WHATSAPP_IPS = [
25
- '108.177.14.0', // web.whatsapp.com
26
- '142.250.79.0', // Google IPs often used
27
- '172.217.28.0', //
28
- '142.250.0.0', //
 
 
 
 
 
 
 
 
 
29
  ];
30
 
31
- // FunΓ§Γ£o para obter IP direto do WhatsApp
 
 
32
  function getWhatsAppIP() {
33
  const index = Math.floor(Math.random() * WHATSAPP_IPS.length);
34
  return WHATSAPP_IPS[index];
35
  }
36
 
37
  // ═══════════════════════════════════════════════════════════════════════
38
- // 3. HELPER: CRIA AGENTE HTTP COM FALLBACK DE DNS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  // ═════════════════════════════════════════════════════════════��═════════
40
 
41
  function createHFAgent() {
42
  try {
43
- const https = require('https');
44
- const http = require('http');
45
- const { HttpsProxyAgent } = require('https-proxy-agent');
46
-
47
- // Verifica se hΓ‘ proxy configurado
48
  const proxy = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy;
49
 
50
  if (proxy) {
51
- console.log('πŸ”Œ Usando proxy configurado:', proxy.substring(0, 30) + '...');
 
52
  return new HttpsProxyAgent(proxy);
53
  }
54
 
55
- // Sem proxy - usa agente padrΓ£o otimizado
56
  return new https.Agent({
57
  keepAlive: true,
58
  keepAliveMsecs: 30000,
59
  timeout: 60000,
60
  maxSockets: 100,
61
  maxFreeSockets: 20,
62
- // NÃO define rejectUnauthorized para evitar problemas em containers
63
- rejectUnauthorized: false
 
64
  });
65
  } catch (error) {
66
- console.warn('⚠️ Erro ao criar agente HTTP:', error.message);
67
  return undefined;
68
  }
69
  }
70
 
71
  // ═══════════════════════════════════════════════════════════════════════
72
- // 4. HELPER: CRIA WEBSOCKET OPTIONS OTIMIZADO PARA HF SPACES
73
  // ═══════════════════════════════════════════════════════════════════════
74
 
75
  function createWebSocketOptions() {
76
  return {
77
- // Headers que fingem ser browser real
78
  headers: {
79
  'Origin': 'https://web.whatsapp.com',
80
- 'Host': 'web.whatsapp.com',
81
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
82
  'Accept': '*/*',
83
  'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8',
84
- 'Accept-Encoding': 'gzip, deflate, br',
85
  'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
86
  'Sec-WebSocket-Version': '13',
87
  },
88
- // Timeout mais longo para containers lentos
89
- handshakeTimeout: 60000,
90
- // Timeout deagent
91
  timeout: 60000,
92
  };
93
  }
94
 
95
  // ═══════════════════════════════════════════════════════════════════════
96
- // 5. VERIFICAÇÃO DE REDE ESPECÍFICA PARA HF SPACES
97
  // ═══════════════════════════════════════════════════════════════════════
98
 
99
  async function verifyHFNetwork() {
100
- console.log('🌐 Verificando conectividade de rede (HF Spaces)...');
101
-
102
- return new Promise((resolve) => {
103
- const net = require('net');
104
- const testHosts = [
105
- { host: '8.8.8.8', port: 53, name: 'Google DNS' },
106
- { host: '1.1.1.1', port: 53, name: 'Cloudflare DNS' },
107
- { host: 'web.whatsapp.com', port: 443, name: 'WhatsApp Web' }
108
- ];
109
-
110
- let checked = 0;
111
- let results = {};
112
-
113
- testHosts.forEach(test => {
114
- const socket = new net.Socket();
115
- socket.setTimeout(5000);
116
-
117
- socket.on('connect', () => {
118
- results[test.name] = true;
119
- socket.destroy();
120
- checkDone();
121
- });
122
-
123
- socket.on('timeout', () => {
124
- results[test.name] = false;
125
- socket.destroy();
126
- checkDone();
127
- });
128
-
129
- socket.on('error', (err) => {
130
- results[test.name] = false;
131
- socket.destroy();
132
- checkDone();
133
- });
134
-
135
- socket.connect(test.port, test.host);
136
- });
137
-
138
- function checkDone() {
139
- checked++;
140
- if (checked >= testHosts.length) {
141
- console.log('πŸ“Š Resultado dos testes de rede:', results);
142
- resolve(results['WhatsApp Web'] || results['Google DNS']);
143
- }
144
- }
145
- });
146
  }
147
 
148
  // ═══════════════════════════════════════════════════════════════════════
@@ -151,16 +140,18 @@ async function verifyHFNetwork() {
151
 
152
  module.exports = {
153
  configureDNS: () => {
154
- // DNS jΓ‘ configurado no inΓ­cio do arquivo
155
- console.log('βœ… DNS configurado para IPv4 first');
 
 
 
 
 
 
156
  },
157
 
158
  getWhatsAppIP,
159
-
160
  createHFAgent,
161
-
162
  createWebSocketOptions,
163
-
164
  verifyHFNetwork
165
- };
166
-
 
1
  /**
2
  * ═══════════════════════════════════════════════════════════════════════
3
+ * CORREÇÕES HF SPACES - DNS E CONEXΓƒO WHATSAPP (HARD PATCH)
4
  * ═══════════════════════════════════════════════════════════════════════
5
+ * Corrige erro: queryA ENODATA / ENOTFOUND web.whatsapp.com
6
+ * SoluΓ§Γ£o: Override direto do dns.lookup para ignorar resolvedor do sistema
 
 
 
 
7
  * ═══════════════════════════════════════════════════════════════════════
8
  */
9
 
 
 
 
 
10
  const dns = require('dns');
11
+ const https = require('https');
12
 
13
  // ═══════════════════════════════════════════════════════════════════════
14
+ // 1. LISTA COMPLETA DE IPs WHATSAPP/GOOGLE EDGE (FALLBACK)
15
  // ═══════════════════════════════════════════════════════════════════════
 
16
  const WHATSAPP_IPS = [
17
+ '142.250.180.14', // Google/WA Edge
18
+ '142.250.187.238',
19
+ '142.250.79.0',
20
+ '172.217.173.238',
21
+ '172.217.28.0',
22
+ '108.177.14.0',
23
+ '142.250.64.110',
24
+ '142.250.191.110',
25
+ '142.250.190.14',
26
+ '142.250.187.206',
27
+ '172.217.169.78',
28
+ '31.13.92.52', // Meta Edge
29
+ '157.240.226.60' // Meta Edge
30
  ];
31
 
32
+ /**
33
+ * Retorna um IP aleatΓ³rio da lista para balanceamento
34
+ */
35
  function getWhatsAppIP() {
36
  const index = Math.floor(Math.random() * WHATSAPP_IPS.length);
37
  return WHATSAPP_IPS[index];
38
  }
39
 
40
  // ═══════════════════════════════════════════════════════════════════════
41
+ // 2. PATCH CRÍTICO DE DNS (HARD OVERRIDE)
42
+ // ═══════════════════════════════════════════════════════════════════════
43
+
44
+ /**
45
+ * Sobrescreve a funΓ§Γ£o dns.lookup nativa do Node.js.
46
+ * Isso intercepta as chamadas do Baileys antes que elas toquem na rede.
47
+ */
48
+ function patchGlobalDNS() {
49
+ const originalLookup = dns.lookup;
50
+
51
+ dns.lookup = (hostname, options, callback) => {
52
+ // Normaliza argumentos (options Γ© opcional no Node.js)
53
+ if (typeof options === 'function') {
54
+ callback = options;
55
+ options = {};
56
+ }
57
+
58
+ // Intercepta domΓ­nios do WhatsApp
59
+ if (hostname === 'web.whatsapp.com' || hostname === 'whatsapp.com' || hostname === 'wss.whatsapp.net') {
60
+ const directIP = getWhatsAppIP();
61
+ // Retorna sucesso imediatamente com o IP fixo (Family 4 = IPv4)
62
+ // console.log(`πŸ›‘οΈ [DNS-PATCH] Redirecionando ${hostname} -> ${directIP}`);
63
+ return callback(null, directIP, 4);
64
+ }
65
+
66
+ // Para qualquer outro domΓ­nio (deepgram, google, etc), usa o DNS normal
67
+ return originalLookup(hostname, options, callback);
68
+ };
69
+
70
+ console.log('βœ… DNS Hard-Patch aplicado: web.whatsapp.com forΓ§ado para IPs diretos');
71
+ }
72
+
73
+ // ═══════════════════════════════════════════════════════════════════════
74
+ // 3. AGENTE HTTP OTIMIZADO PARA HF SPACES
75
  // ═════════════════════════════════════════════════════════════��═════════
76
 
77
  function createHFAgent() {
78
  try {
79
+ // Verifica proxy
 
 
 
 
80
  const proxy = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy;
81
 
82
  if (proxy) {
83
+ const { HttpsProxyAgent } = require('https-proxy-agent');
84
+ console.log('πŸ”Œ Usando proxy detectado:', proxy.substring(0, 20) + '...');
85
  return new HttpsProxyAgent(proxy);
86
  }
87
 
88
+ // Sem proxy: Agente otimizado
89
  return new https.Agent({
90
  keepAlive: true,
91
  keepAliveMsecs: 30000,
92
  timeout: 60000,
93
  maxSockets: 100,
94
  maxFreeSockets: 20,
95
+ // CRÍTICO: rejectUnauthorized: false permite conexão SSL direta no IP
96
+ // sem validar se o certificado bate com o "IP" (jΓ‘ que o cert Γ© para o domΓ­nio)
97
+ rejectUnauthorized: false
98
  });
99
  } catch (error) {
100
+ console.warn('⚠️ Erro ao criar agente HTTP:', error.message);
101
  return undefined;
102
  }
103
  }
104
 
105
  // ═══════════════════════════════════════════════════════════════════════
106
+ // 4. OPÇÕES DE WEBSOCKET (HEADERS ESSENCIAIS)
107
  // ═══════════════════════════════════════════════════════════════════════
108
 
109
  function createWebSocketOptions() {
110
  return {
111
+ // Headers necessΓ‘rios para enganar o servidor jΓ‘ que estamos conectando via IP
112
  headers: {
113
  'Origin': 'https://web.whatsapp.com',
114
+ 'Host': 'web.whatsapp.com', // O servidor precisa disso para rotear corretamente (SNI)
115
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
116
  'Accept': '*/*',
117
  'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8',
 
118
  'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
119
  'Sec-WebSocket-Version': '13',
120
  },
121
+ handshakeTimeout: 60000, // Timeout aumentado
 
 
122
  timeout: 60000,
123
  };
124
  }
125
 
126
  // ═══════════════════════════════════════════════════════════════════════
127
+ // 5. VERIFICAÇÃO DE REDE (DUMMY/PASS-THROUGH)
128
  // ═══════════════════════════════════════════════════════════════════════
129
 
130
  async function verifyHFNetwork() {
131
+ // Com o patch de DNS aplicado, a verificaΓ§Γ£o de rede tradicional Γ© irrelevante
132
+ // e pode falhar falsamente. Retornamos true para nΓ£o bloquear o boot.
133
+ console.log('🌐 Patch de rede ativo. Ignorando teste de DNS convencional.');
134
+ return true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  }
136
 
137
  // ═══════════════════════════════════════════════════════════════════════
 
140
 
141
  module.exports = {
142
  configureDNS: () => {
143
+ // Configura o patch imediatamente ao ser chamado
144
+ const dns = require('dns');
145
+ // ForΓ§a ordem IPv4
146
+ if (dns.setDefaultResultOrder) {
147
+ dns.setDefaultResultOrder('ipv4first');
148
+ }
149
+ // Aplica o override
150
+ patchGlobalDNS();
151
  },
152
 
153
  getWhatsAppIP,
 
154
  createHFAgent,
 
155
  createWebSocketOptions,
 
156
  verifyHFNetwork
157
+ };