Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
352 lines (315 loc) · 11.3 KB
/
Copy pathserver.js
File metadata and controls
352 lines (315 loc) · 11.3 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
require('dotenv').config();
const express = require('express');
const { chromium } = require('playwright');
const cors = require('cors');
const { performFullScan } = require('./lib/fullscan');
const app = express();
const PORT = process.env.PORT || 9999;
// Enable CORS for all routes
app.use(cors());
app.use(express.json({ limit: '10mb' }));
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
service: 'ada-snapfix-worker',
version: '1.0.0',
timestamp: new Date().toISOString()
});
});
// Browser service endpoint (for WebSocket connections)
app.get('/browser', async (req, res) => {
try {
const browser = await chromium.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--disable-web-security',
'--disable-features=VizDisplayCompositor',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-field-trial-config',
'--disable-ipc-flooding-protection',
'--memory-pressure-off',
'--max_old_space_size=4096'
]
});
const browserWSEndpoint = browser.wsEndpoint();
res.json({
success: true,
wsEndpoint: browserWSEndpoint,
message: 'Browser launched successfully'
});
} catch (error) {
console.error('Failed to launch browser:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
// Fullscan API endpoint
app.post('/api/scan', async (req, res) => {
// Create an AbortController to handle timeouts and cancellation
const abortController = new AbortController();
const signal = abortController.signal;
let sseClosed = false;
// Set up a timeout for the entire scan process
const maxScanDuration = 180000; // 3 minutes timeout for single URL scan
const timeoutId = setTimeout(() => {
console.log(`Scan timeout reached (${maxScanDuration / 1000} seconds). Terminating scan.`);
abortController.abort();
}, maxScanDuration);
try {
const { url } = req.body;
if (!url) {
clearTimeout(timeoutId);
return res.status(400).json({ error: 'URL is required' });
}
console.log('Starting fullscan for URL:', url);
// Set response headers for streaming
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type'
});
// Create a sendLog function for streaming logs
const sendLog = (message, type = 'log') => {
try {
if (sseClosed) return;
const safeMessage = String(message || '').substring(0, 1000);
const data = JSON.stringify({
type,
message: safeMessage,
timestamp: new Date().toISOString()
});
try { console.log(`[${type.toUpperCase()}] ${safeMessage}`); } catch {}
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${data}\n\n`);
}
} catch (error) {
try { console.error('Error in sendLog:', error); } catch {}
}
};
// Set up abort signal handler
signal.addEventListener('abort', () => {
try {
sendLog('Scan timeout reached. Terminating scan.', 'error');
const timeoutError = JSON.stringify({
type: 'error',
message: `Scan timeout reached (${maxScanDuration / 1000} seconds). Terminating scan.`,
metadata: { scanType: 'timeout' }
});
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${timeoutError}\n\n`);
}
if (res && !res.writableEnded) {
try { res.write(`event: done\ndata: {}\n\n`); } catch {}
try { res.end(); } catch {}
}
} catch (error) {
try { console.error('Error in abort handler:', error); } catch {}
try { if (res && !res.writableEnded) res.end(); } catch {}
} finally {
sseClosed = true;
}
});
// Perform the fullscan with streaming logs and abort signal
let results;
try {
results = await performFullScan(url, sendLog, signal);
} catch (scanError) {
console.error('Fullscan execution error:', scanError);
// Enhanced diagnostics: Log detailed error information
console.error('Fullscan execution error details:', scanError.stack);
// Avoid premature end; rely on guarded SSE writes
// Debugging information: Log request details
console.log('Request details during error:', {
url: req.body.url,
headers: req.headers,
method: req.method
});
if (!signal.aborted) {
sendLog(`Scan execution failed: ${scanError.message}`, 'error');
const errorData = JSON.stringify({
type: 'error',
message: `Scan execution failed: ${scanError.message}`,
timestamp: new Date().toISOString()
});
try {
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${errorData}\n\n`);
}
if (res && !res.writableEnded) {
try { res.write(`event: done\ndata: {}\n\n`); } catch {}
try { res.end(); } catch {}
}
sseClosed = true;
} catch (writeError) {
console.error('Error writing error data:', writeError);
try { if (res && !res.writableEnded) res.end(); } catch {}
}
}
return;
}
// Only send results if the scan wasn't aborted
if (!signal.aborted) try {
// Send final results - use chunked base64 encoding for large responses
const resultsData = JSON.stringify({ type: 'results', data: results });
// Always encode large results as base64 and split into chunks
if (resultsData.length > 2000) { // 2KB limit - very conservative
const encodedResults = Buffer.from(resultsData).toString('base64');
// Split into chunks of 1000 characters
const chunkSize = 1000;
const chunks = [];
for (let i = 0; i < encodedResults.length; i += chunkSize) {
chunks.push(encodedResults.slice(i, i + chunkSize));
}
try {
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${JSON.stringify({ type: 'results-encoded-start', totalChunks: chunks.length })}\n\n`);
for (let i = 0; i < chunks.length; i++) {
if (res.writableEnded) break;
if (res.writable) res.write(`data: ${JSON.stringify({ type: 'results-encoded-chunk', chunkIndex: i, data: chunks[i] })}\n\n`);
}
if (!res.writableEnded && res.writable) {
res.write(`data: ${JSON.stringify({ type: 'results-encoded-end' })}\n\n`);
}
}
} catch (writeError) {
console.error('Error writing chunked results:', writeError);
}
} else {
try {
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${resultsData}\n\n`);
}
} catch (writeError) {
console.error('Error writing results:', writeError);
}
}
try {
if (res && !res.writableEnded) {
try { if (res.writable) res.write(`event: done\ndata: {}\n\n`); } catch {}
try { res.end(); } catch {}
sseClosed = true;
}
} catch (endError) {
console.error('Error sending completion signal:', endError);
try { if (res && !res.writableEnded) res.end(); } catch (finalEndError) {
console.error('Error ending response:', finalEndError);
}
}
} catch (error) {
console.error('Fullscan error:', error);
if (!res.headersSent) {
res.status(500).json({
error: 'Internal server error',
message: error.message
});
} else {
const safeErrorMessage = String(error.message || 'Unknown error').substring(0, 500);
const errorData = JSON.stringify({
type: 'error',
message: safeErrorMessage,
timestamp: new Date().toISOString()
});
try {
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${errorData}\n\n`);
}
if (res && !res.writableEnded) {
try { res.write(`event: done\ndata: {}\n\n`); } catch {}
try { res.end(); } catch {}
}
} catch (writeError) {
console.error('Error writing error data:', writeError);
try { if (res && !res.writableEnded) res.end(); } catch (endError) {
console.error('Error ending response after error:', endError);
}
}
}
} finally {
// Clean up resources
clearTimeout(timeoutId);
}
} catch (error) {
console.error('Fullscan error:', error);
if (!res.headersSent) {
res.status(500).json({
error: 'Internal server error',
message: error.message
});
} else {
const safeErrorMessage = String(error.message || 'Unknown error').substring(0, 500);
const errorData = JSON.stringify({
type: 'error',
message: safeErrorMessage,
timestamp: new Date().toISOString()
});
try {
if (res && !res.writableEnded && res.writable) {
res.write(`data: ${errorData}\n\n`);
}
if (res && !res.writableEnded) {
try { res.write(`event: done\ndata: {}\n\n`); } catch {}
try { res.end(); } catch {}
}
} catch (writeError) {
console.error('Error writing error data:', writeError);
try { if (res && !res.writableEnded) res.end(); } catch (endError) {
console.error('Error ending response after error:', endError);
}
}
}
} finally {
clearTimeout(timeoutId);
}
});
// Regular scan endpoint (non-streaming)
app.post('/api/scan-sync', async (req, res) => {
try {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
console.log('Starting sync fullscan for URL:', url);
// Create a dummy sendLog function for non-streaming
const sendLog = (message, type = 'log') => {
console.log(`[${type.toUpperCase()}] ${message}`);
};
// Perform the fullscan
const results = await performFullScan(url, sendLog);
res.json(results);
} catch (error) {
console.error('Sync fullscan error:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message
});
}
});
// Global error handlers to prevent unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Promise Rejection at:', promise, 'reason:', reason);
// Don't exit the process, just log the error
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
// Don't exit the process, just log the error
});
// Start server
app.listen(PORT, () => {
console.log(`Ada SnapFix Worker running on port ${PORT}`);
console.log(`Health check: http://localhost:${PORT}/health`);
console.log(`Browser endpoint: http://localhost:${PORT}/browser`);
console.log(`Fullscan endpoint: http://localhost:${PORT}/api/scan`);
console.log(`Sync scan endpoint: http://localhost:${PORT}/api/scan-sync`);
});
module.exports = app;