-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
379 lines (343 loc) · 12.5 KB
/
server.js
File metadata and controls
379 lines (343 loc) · 12.5 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
const express = require('express');
const rateLimit = require('express-rate-limit');
const dotenv = require('dotenv');
const moment = require('moment');
const whatsappService = require('./whatsapp-client');
// Load environment variables
dotenv.config();
const app = express();
// Enable trust proxy - Add this before other middleware
app.set('trust proxy', 1);
app.use(express.json());
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
standardHeaders: true,
legacyHeaders: false
});
app.use(limiter);
// Middleware to check API key
const checkApiKey = (req, res, next) => {
const apiKey = req.query.key || req.headers['x-api-key'];
if (!apiKey || apiKey !== process.env.API_KEY) {
return res.status(401).json({
success: false,
error: 'Unauthorized - Invalid API key'
});
}
next();
};
// API Routes
app.get('/status', checkApiKey, (req, res) => {
res.json({
success: true,
...whatsappService.getServiceStatus()
});
});
app.get('/qr-status', checkApiKey, (req, res) => {
res.json({
success: true,
authenticated: whatsappService.isAuthenticated,
qrCode: whatsappService.qrCode,
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
});
app.post('/otp/generate', checkApiKey, async (req, res) => {
try {
const { phone } = req.body;
if (!phone) {
return res.status(400).json({
success: false,
error: 'Phone number is required',
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
}
const result = await whatsappService.generateOTP(phone);
res.json({
success: true,
...result
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
}
});
app.post('/otp/verify', checkApiKey, async (req, res) => {
try {
const { referenceId, otp } = req.body;
if (!referenceId || !otp) {
return res.status(400).json({
success: false,
error: 'Reference ID and OTP are required',
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
}
const result = await whatsappService.verifyOTP(referenceId, otp);
res.json(result);
} catch (error) {
res.status(400).json({
success: false,
error: error.message,
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
}
});
// QR Code page
app.get('/qr', checkApiKey, (req, res) => {
const html = `
<!DOCTYPE html>
<html>
<head>
<title>WhatsApp QR Code Scanner</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #f0f2f5;
font-family: Arial, sans-serif;
}
.container {
text-align: center;
padding: 2rem;
background: white;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
max-width: 500px;
width: 90%;
}
h1 {
color: #128C7E;
margin-bottom: 1rem;
}
#qrcode {
margin: 2rem 0;
padding: 1rem;
background: white;
border-radius: 8px;
}
#qrcode img {
max-width: 256px;
height: auto;
}
.status {
margin-top: 1rem;
padding: 1rem;
border-radius: 5px;
background: #f8f9fa;
color: #666;
}
.instructions {
margin-top: 1rem;
font-size: 0.9rem;
color: #666;
text-align: left;
padding: 1rem;
background: #f8f9fa;
border-radius: 5px;
}
.instructions ol {
margin: 0;
padding-left: 1.5rem;
}
.timestamp {
font-size: 0.8rem;
color: #999;
margin-top: 1rem;
}
.user-info {
font-size: 0.8rem;
color: #666;
margin-top: 1rem;
padding: 0.5rem;
background: #e9ecef;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>WhatsApp QR Code Scanner</h1>
<div class="user-info">
Logged in as: reddevil212
</div>
<div class="instructions">
<strong>How to connect:</strong>
<ol>
<li>Open WhatsApp on your phone</li>
<li>Go to Menu or Settings and select WhatsApp Web</li>
<li>Point your phone camera to this QR code</li>
<li>Authentication will happen automatically</li>
</ol>
</div>
<div id="qrcode">Loading QR Code...</div>
<div id="status" class="status">Initializing...</div>
<div class="timestamp">Last Updated: <span id="timestamp"></span></div>
</div>
<script>
function updateTimestamp() {
const now = new Date();
document.getElementById('timestamp').textContent = now.toISOString().replace('T', ' ').split('.')[0] + ' UTC';
}
async function updateQRCode() {
try {
const response = await fetch('/qr-status?key=${req.query.key}');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
const qrDiv = document.getElementById('qrcode');
const statusDiv = document.getElementById('status');
updateTimestamp();
if (data.authenticated) {
qrDiv.innerHTML = '<p style="color: #128C7E; font-weight: bold;">✓ Successfully Authenticated!</p>';
statusDiv.innerHTML = 'WhatsApp is connected and ready to use';
statusDiv.style.backgroundColor = '#d4edda';
statusDiv.style.color = '#155724';
return;
}
if (data.qrCode) {
qrDiv.innerHTML = '<img src="' + data.qrCode + '" alt="WhatsApp QR Code">';
statusDiv.innerHTML = 'Scan this QR code with WhatsApp on your phone';
statusDiv.style.backgroundColor = '#f8f9fa';
statusDiv.style.color = '#666';
} else {
qrDiv.innerHTML = 'Generating QR Code...';
statusDiv.innerHTML = 'Please wait while we initialize the connection';
statusDiv.style.backgroundColor = '#fff3cd';
statusDiv.style.color = '#856404';
}
} catch (error) {
console.error('Error:', error);
document.getElementById('status').innerHTML = 'Error loading QR code. Please refresh the page.';
document.getElementById('status').style.backgroundColor = '#f8d7da';
document.getElementById('status').style.color = '#721c24';
}
}
// Initial check
updateQRCode();
// Update every 5 seconds
setInterval(updateQRCode, 5000);
</script>
</body>
</html>
`;
res.send(html);
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Error:`, err.stack);
res.status(500).json({
success: false,
error: 'Internal server error',
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
});
// Cleanup expired OTPs periodically
setInterval(() => {
whatsappService.cleanupExpiredOTPs();
}, 5 * 60 * 1000); // Every 5 minutes
// Initialize the WhatsApp client when the server starts
const initializeWhatsApp = async () => {
try {
console.log(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Initializing WhatsApp client...`);
// Add retry logic with exponential backoff
let retries = 0;
const maxRetries = 10; // Increased max retries
while (retries < maxRetries) {
try {
await whatsappService.initializeClient();
console.log(`[${moment().utc().format()}] WhatsApp client initialized successfully`);
break;
} catch (error) {
retries++;
console.error(`[${moment().utc().format()}] WhatsApp initialization attempt ${retries} failed:`, error);
if (retries === maxRetries) throw error;
// Exponential backoff with max delay of 30 seconds
const delay = Math.min(1000 * Math.pow(2, retries), 30000);
console.log(`[${moment().utc().format()}] Waiting ${delay/1000} seconds before retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
} catch (error) {
console.error(`[${moment().utc().format()}] WhatsApp initialization error:`, error);
whatsappService.isAuthenticated = false;
// Schedule a retry after 1 minute
setTimeout(initializeWhatsApp, 60000);
}
};
// Add a health check endpoint
app.get('/health', checkApiKey, (req, res) => {
const status = whatsappService.getServiceStatus();
if (!status.authenticated) {
// Trigger reconnection if not authenticated
initializeWhatsApp().catch(console.error);
}
res.json({
success: true,
...status
});
});
// Add a manual logout endpoint
app.post('/logout', checkApiKey, async (req, res) => {
try {
if (whatsappService.client) {
await whatsappService.client.destroy();
whatsappService.isAuthenticated = false;
whatsappService.initialized = false;
whatsappService._saveAuthStatus();
}
res.json({
success: true,
message: 'Logged out successfully',
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
timestamp: moment().utc().format('YYYY-MM-DD HH:mm:ss')
});
}
});
// Add periodic health check
setInterval(() => {
const status = whatsappService.getServiceStatus();
if (!status.authenticated) {
console.log(`[${moment().utc().format()}] Service not authenticated, attempting reconnection...`);
initializeWhatsApp().catch(console.error);
}
}, 5 * 60 * 1000); // Check every 5 minutes
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Server running on port ${PORT}`);
// Initialize WhatsApp after server starts
initializeWhatsApp();
});
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Received SIGTERM signal. Shutting down gracefully...`);
try {
if (whatsappService.client) {
await whatsappService.client.destroy();
}
} catch (error) {
console.error(`[${moment().utc().format()}] Error during shutdown:`, error);
}
process.exit(0);
});
process.on('unhandledRejection', (reason, promise) => {
console.error(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Unhandled Rejection at:`, promise, 'reason:', reason);
});
process.on('uncaughtException', (error) => {
console.error(`[${moment().utc().format('YYYY-MM-DD HH:mm:ss')}] Uncaught Exception:`, error);
});
module.exports = app;