akra35567 commited on
Commit
5b397d2
Β·
verified Β·
1 Parent(s): b8e0b7e

Create HFCorrections.js

Browse files
Files changed (1) hide show
  1. modules/HFCorrections.js +187 -0
modules/HFCorrections.js ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ═══════════════════════════════════════════════════════════════════════
3
+ * HF SPACES CORRECTIONS - CORREÇÕES CRÍTICAS PARA HUGGING FACE SPACES
4
+ * ═══════════════════════════════════════════════════════════════════════
5
+ * Este mΓ³dulo contΓ©m correΓ§Γ΅es especΓ­ficas para o ambiente HF Spaces:
6
+ * - DNS fixes para web.whatsapp.com
7
+ * - ConfiguraΓ§Γ£o de WebSocket com IP direto
8
+ * - Fallback de conectividade
9
+ * ═══════════════════════════════════════════════════════════════════════
10
+ */
11
+
12
+ const dns = require('dns');
13
+ const https = require('https');
14
+ const http = require('http');
15
+
16
+ // IPs conhecidos do WhatsApp Web (atualizado Janeiro 2026)
17
+ const WHATSAPP_IPS = [
18
+ '108.177.14.0',
19
+ '108.177.15.0',
20
+ '142.250.79.0',
21
+ '142.250.80.0',
22
+ '142.250.81.0',
23
+ '172.217.28.0',
24
+ '172.217.162.0',
25
+ '172.217.163.0'
26
+ ];
27
+
28
+ // Cache de IP direto
29
+ let cachedWhatsAppIP = null;
30
+ let lastDNSResolve = 0;
31
+ const DNS_CACHE_TTL = 60000; // 1 minuto
32
+
33
+ /**
34
+ * ObtΓ©m IP direto do WhatsApp (com cache)
35
+ */
36
+ function getWhatsAppDirectIP() {
37
+ const now = Date.now();
38
+ if (cachedWhatsAppIP && (now - lastDNSResolve) < DNS_CACHE_TTL) {
39
+ return cachedWhatsAppIP;
40
+ }
41
+
42
+ // Retorna IP aleatΓ³rio da lista
43
+ const ip = WHATSAPP_IPS[Math.floor(Math.random() * WHATSAPP_IPS.length)];
44
+ cachedWhatsAppIP = ip;
45
+ lastDNSResolve = now;
46
+
47
+ console.log(`πŸ“ IP WhatsApp direto: ${ip}`);
48
+ return ip;
49
+ }
50
+
51
+ /**
52
+ * Inicializa correΓ§Γ΅es de DNS para HF Spaces
53
+ */
54
+ function initializeHFSDNSCorrections() {
55
+ console.log('πŸ”§ Inicializando correΓ§Γ΅es DNS para HF Spaces...');
56
+
57
+ // 1. ForΓ§a IPv4 para todas as operaΓ§Γ΅es DNS
58
+ try {
59
+ dns.setDefaultResultOrder('ipv4first');
60
+ console.log('βœ… DNS: Ordem forΓ§ada para IPv4');
61
+ } catch (e) {
62
+ console.warn('⚠️ Não foi possível definir ordem DNS:', e.message);
63
+ }
64
+
65
+ // 2. Sobrescreve resolve4 para usar IP direto em caso de falha
66
+ const originalResolve4 = dns.resolve4.bind(dns);
67
+
68
+ dns.resolve4 = function(hostname, options, callback) {
69
+ if (typeof options === 'function') {
70
+ callback = options;
71
+ options = { timeout: 10000, family: 4 };
72
+ }
73
+
74
+ // Para web.whatsapp.com, usa IP direto
75
+ if (hostname === 'web.whatsapp.com' || hostname === 'whatsapp.com') {
76
+ const ip = getWhatsAppDirectIP();
77
+ console.log(`πŸ”„ DNS redirect: ${hostname} -> ${ip}`);
78
+
79
+ // Retorna IP formatado para DNS
80
+ setTimeout(() => {
81
+ callback(null, [ip]);
82
+ }, 10);
83
+ return;
84
+ }
85
+
86
+ // Para outros domΓ­nios, usa resoluΓ§Γ£o normal
87
+ originalResolve4(hostname, options, (err, addresses) => {
88
+ if (err && (err.code === 'ENODATA' || err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN')) {
89
+ console.log(`πŸ”„ DNS fallback para ${hostname}, tentando novamente...`);
90
+ setTimeout(() => {
91
+ originalResolve4(hostname, options, callback);
92
+ }, 2000);
93
+ } else {
94
+ callback(err, addresses);
95
+ }
96
+ });
97
+ };
98
+
99
+ // 3. Sobrescreve resolve (genΓ©rico) tambΓ©m
100
+ const originalResolve = dns.resolve.bind(dns);
101
+
102
+ dns.resolve = function(hostname, rrtype, callback) {
103
+ if (typeof rrtype === 'function') {
104
+ callback = rrtype;
105
+ rrtype = 'A';
106
+ }
107
+
108
+ if (hostname === 'web.whatsapp.com' || hostname === 'whatsapp.com') {
109
+ const ip = getWhatsAppDirectIP();
110
+ setTimeout(() => {
111
+ callback(null, [ip]);
112
+ }, 10);
113
+ return;
114
+ }
115
+
116
+ originalResolve(hostname, rrtype, callback);
117
+ };
118
+
119
+ // 4. Sobrescreve lookup para IP direto
120
+ const originalLookup = dns.lookup.bind(dns);
121
+
122
+ dns.lookup = function(hostname, options, callback) {
123
+ if (typeof options === 'function') {
124
+ callback = options;
125
+ options = {};
126
+ }
127
+
128
+ if (hostname === 'web.whatsapp.com' || hostname === 'whatsapp.com') {
129
+ const ip = getWhatsAppDirectIP();
130
+ console.log(`πŸ”„ Lookup redirect: ${hostname} -> ${ip}`);
131
+ setTimeout(() => {
132
+ callback(null, ip, 4); // family 4 = IPv4
133
+ }, 10);
134
+ return;
135
+ }
136
+
137
+ originalLookup(hostname, options, callback);
138
+ };
139
+
140
+ console.log('βœ… CorreΓ§Γ΅es DNS inicializadas');
141
+ }
142
+
143
+ /**
144
+ * Cria agente HTTP otimizado para HF Spaces
145
+ */
146
+ function createCustomHTTPAgent() {
147
+ return new https.Agent({
148
+ keepAlive: true,
149
+ keepAliveMsecs: 30000,
150
+ timeout: 60000,
151
+ maxSockets: 100,
152
+ maxFreeSockets: 20,
153
+ rejectUnauthorized: false
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Verifica conectividade bΓ‘sica
159
+ */
160
+ async function checkBasicConnectivity() {
161
+ return new Promise((resolve) => {
162
+ // Teste simples de conectividade
163
+ const req = https.get('https://httpbin.org/get', { timeout: 10000 }, (res) => {
164
+ req.destroy();
165
+ resolve(res.statusCode === 200);
166
+ });
167
+
168
+ req.on('error', () => {
169
+ req.destroy();
170
+ resolve(false);
171
+ });
172
+
173
+ req.on('timeout', () => {
174
+ req.destroy();
175
+ resolve(false);
176
+ });
177
+ });
178
+ }
179
+
180
+ module.exports = {
181
+ initializeHFSDNSCorrections,
182
+ getWhatsAppDirectIP,
183
+ createCustomHTTPAgent,
184
+ checkBasicConnectivity,
185
+ WHATSAPP_IPS
186
+ };
187
+