-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
760 lines (664 loc) · 22.3 KB
/
server.js
File metadata and controls
760 lines (664 loc) · 22.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
import cors from 'cors';
import session from 'express-session';
import passport from 'passport';
import cookieParser from 'cookie-parser';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import dotenv from 'dotenv';
// Import our custom modules
import {
initDatabase,
createEndpoint,
getUserEndpoints,
getEndpointById,
getEndpointByPath,
deleteEndpoint,
updateEndpointRequestCount,
createRequest,
getEndpointRequests,
getUserRequests,
deleteEndpointRequests,
deleteRequest
} from './database.js';
import { configurePassport, requireAuth, optionalAuth } from './auth.js';
// Load environment variables
dotenv.config();
// Get current directory for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: process.env.FRONTEND_URL || "http://localhost:5173",
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
credentials: true
}
});
app.use(cors({
origin: process.env.FRONTEND_URL || "http://localhost:5173",
credentials: true
}));
app.use(cookieParser());
// Session configuration
app.use(session({
secret: process.env.SESSION_SECRET || 'your-secret-key-change-this',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: 'lax',
httpOnly: true
}
}));
// Passport configuration
app.use(passport.initialize());
app.use(passport.session());
configurePassport();
// Anonymous user cookie middleware
app.use((req, res, next) => {
if (!req.cookies?.anonymous_id) {
const anonymousId = uuidv4();
res.cookie('anonymous_id', anonymousId, {
httpOnly: false,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 365 * 24 * 60 * 60 * 1000 // 1 year
});
req.anonymousId = anonymousId;
} else {
req.anonymousId = req.cookies.anonymous_id;
}
next();
});
app.use(express.json({ limit: '10mb' }));
app.use(express.text({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development'
});
});
// Build info endpoint
app.get('/build-info', (req, res) => {
try {
import('fs').then(fs => {
const buildInfoPath = join(__dirname, 'build-info.txt');
if (fs.existsSync(buildInfoPath)) {
const buildInfo = fs.readFileSync(buildInfoPath, 'utf8');
res.status(200).json({
buildInfo: buildInfo.split('\n').filter(line => line.trim()),
serverStartTime: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
nodeVersion: process.version
});
} else {
res.status(200).json({
buildInfo: ['Build info not available - file not found'],
serverStartTime: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
nodeVersion: process.version
});
}
}).catch(err => {
res.status(200).json({
buildInfo: ['Build info not available - error reading file'],
error: err.message,
serverStartTime: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
nodeVersion: process.version
});
});
} catch (error) {
res.status(500).json({
error: 'Failed to read build info',
details: error.message
});
}
});
// Serve static files in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static(join(__dirname, 'dist')));
}
// In-memory storage for anonymous users by cookie ID
const anonymousEndpoints = new Map(); // Map<anonymousId, Map<endpointId, endpoint>>
const anonymousRequests = new Map(); // Map<anonymousId, Map<requestId, request>>
// In-memory storage for auth tokens (production should use Redis)
const authTokens = new Map();
// Helper function to check authentication (session or token)
const getAuthenticatedUser = (req) => {
// Check for Bearer token first
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
const token = authHeader.replace('Bearer ', '');
const authData = authTokens.get(token);
if (authData && authData.expiresAt > new Date()) {
return authData.user;
}
}
// Fallback to session-based auth
if (req.isAuthenticated()) {
return req.user;
}
return null;
};
// Authentication routes (only if GitHub OAuth is configured)
if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {
app.get('/auth/github', passport.authenticate('github', { scope: ['user:email'] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: process.env.FRONTEND_URL }),
async (req, res) => {
// OAuth authentication successful - migration will be handled by frontend
// Create persistent auth token
const authToken = uuidv4();
authTokens.set(authToken, {
user: req.user,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours
});
// Redirect with token
res.redirect(`${process.env.FRONTEND_URL}?auth_token=${authToken}`);
}
);
} else {
// Provide fallback routes when GitHub OAuth is not configured
app.get('/auth/github', (req, res) => {
res.status(501).json({ error: 'GitHub OAuth not configured' });
});
app.get('/auth/github/callback', (req, res) => {
res.status(501).json({ error: 'GitHub OAuth not configured' });
});
}
app.post('/auth/logout', (req, res) => {
req.logout((err) => {
if (err) {
return res.status(500).json({ error: 'Logout failed' });
}
res.json({ message: 'Logged out successfully' });
});
});
// Token validation endpoint
app.post('/auth/validate-token', (req, res) => {
const { token } = req.body;
if (!token) {
return res.status(400).json({ error: 'Token required' });
}
const authData = authTokens.get(token);
if (!authData) {
return res.status(401).json({ error: 'Invalid token' });
}
if (authData.expiresAt < new Date()) {
authTokens.delete(token);
return res.status(401).json({ error: 'Token expired' });
}
res.json({
user: {
id: authData.user.id,
username: authData.user.username,
display_name: authData.user.display_name,
avatar_url: authData.user.avatar_url
}
});
});
// Token-based authentication check
app.get('/auth/me', (req, res) => {
// Check for token in headers
const authToken = req.headers.authorization?.replace('Bearer ', '');
if (authToken) {
const authData = authTokens.get(authToken);
if (authData && authData.expiresAt > new Date()) {
return res.json({
user: {
id: authData.user.id,
username: authData.user.username,
display_name: authData.user.display_name,
avatar_url: authData.user.avatar_url
}
});
} else {
if (authData) authTokens.delete(authToken);
}
}
// Fallback to session-based auth
if (req.isAuthenticated()) {
res.json({
user: {
id: req.user.id,
username: req.user.username,
display_name: req.user.display_name,
avatar_url: req.user.avatar_url
}
});
} else {
res.json({ user: null });
}
});
// Migrate anonymous endpoints to authenticated user
app.post('/auth/migrate-endpoints', async (req, res) => {
const user = getAuthenticatedUser(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
}
const { endpointIds } = req.body;
if (!endpointIds || !Array.isArray(endpointIds)) {
return res.status(400).json({ error: 'Endpoint IDs array required' });
}
try {
let migratedCount = 0;
const anonymousId = req.anonymousId;
const userEndpoints = anonymousEndpoints.get(anonymousId) || new Map();
const userRequests = anonymousRequests.get(anonymousId) || new Map();
for (const endpointId of endpointIds) {
const endpoint = userEndpoints.get(endpointId);
if (endpoint) {
// Create endpoint in database for authenticated user
await createEndpoint({
id: endpoint.id,
user_id: user.id,
name: endpoint.name,
path: endpoint.path
});
// Migrate requests
const endpointRequests = Array.from(userRequests.values())
.filter(r => r.endpointId === endpointId);
for (const request of endpointRequests) {
await createRequest({
id: request.id,
endpoint_id: endpointId,
method: request.method,
url: request.url,
headers: request.headers,
body: request.body
}).catch(err => console.error('Error migrating request:', err));
}
// Remove from anonymous storage
userEndpoints.delete(endpointId);
endpointRequests.forEach(r => userRequests.delete(r.id));
migratedCount++;
}
}
res.json({
success: true,
migratedCount,
totalRequested: endpointIds.length
});
} catch (error) {
console.error('Error during migration:', error);
res.status(500).json({ error: 'Migration failed' });
}
});
const captureRequest = (req, res, next) => {
// Flag to ensure we only capture once per request
if (req.captured) {
return next();
}
req.captured = true;
const originalEnd = res.end;
res.end = function(chunk, encoding) {
// Only capture if this is for a dynamic endpoint
if (req.endpointId) {
let body = '';
// Handle different body types from Express middleware
if (req.body !== undefined) {
if (typeof req.body === 'string') {
body = req.body;
} else if (typeof req.body === 'object') {
body = JSON.stringify(req.body, null, 2);
} else {
body = String(req.body);
}
}
const requestData = {
id: uuidv4(),
method: req.method,
url: req.originalUrl,
headers: req.headers,
body: body,
timestamp: new Date(),
endpointId: req.endpointId,
path: req.endpointPath,
subPath: req.endpointSubPath,
fullPath: req.endpointFullPath
};
// Store request based on authentication
if (req.endpoint && req.endpoint.user_id) {
// Authenticated user - store in database
createRequest({
id: requestData.id,
endpoint_id: req.endpointId,
method: requestData.method,
url: requestData.url,
headers: requestData.headers,
body: requestData.body
}).catch(err => console.error('Error storing request:', err));
} else {
// Anonymous user - store in memory by cookie ID
const anonymousId = req.anonymousId;
if (!anonymousRequests.has(anonymousId)) {
anonymousRequests.set(anonymousId, new Map());
}
anonymousRequests.get(anonymousId).set(requestData.id, requestData);
}
io.emit('new_request', requestData);
}
originalEnd.call(this, chunk, encoding);
};
next();
};
// API routes
app.get('/api/endpoints', optionalAuth, async (req, res) => {
try {
const user = getAuthenticatedUser(req);
if (user) {
// Get user's endpoints from database
const endpoints = await getUserEndpoints(user.id);
res.json(endpoints);
} else {
// Get anonymous endpoints from memory for this cookie ID
const anonymousId = req.anonymousId;
const userEndpoints = anonymousEndpoints.get(anonymousId) || new Map();
const anonymousEndpointsList = Array.from(userEndpoints.values());
res.json(anonymousEndpointsList);
}
} catch (error) {
console.error('Error fetching endpoints:', error);
res.status(500).json({ error: 'Failed to fetch endpoints' });
}
});
app.post('/api/endpoints', optionalAuth, async (req, res) => {
try {
const { name } = req.body;
const endpointId = uuidv4();
const path = uuidv4();
const endpoint = {
id: endpointId,
name,
path,
created: new Date(),
requestCount: 0
};
const user = getAuthenticatedUser(req);
if (user) {
// Save to database for authenticated users
await createEndpoint({
id: endpointId,
user_id: user.id,
name,
path
});
endpoint.user_id = user.id;
} else {
// Save to memory for anonymous users by cookie ID
const anonymousId = req.anonymousId;
if (!anonymousEndpoints.has(anonymousId)) {
anonymousEndpoints.set(anonymousId, new Map());
}
anonymousEndpoints.get(anonymousId).set(endpointId, endpoint);
}
io.emit('endpoint_created', endpoint);
res.status(201).json(endpoint);
} catch (error) {
console.error('Error creating endpoint:', error);
res.status(500).json({ error: 'Failed to create endpoint' });
}
});
app.delete('/api/endpoints/:id', optionalAuth, async (req, res) => {
try {
const { id } = req.params;
if (req.isAuthenticated()) {
// Delete from database
await deleteEndpoint(id);
await deleteEndpointRequests(id);
} else {
// Delete from memory by cookie ID
const anonymousId = req.anonymousId;
const userEndpoints = anonymousEndpoints.get(anonymousId) || new Map();
const userRequests = anonymousRequests.get(anonymousId) || new Map();
if (userEndpoints.has(id)) {
userEndpoints.delete(id);
const endpointRequests = Array.from(userRequests.values()).filter(r => r.endpointId === id);
endpointRequests.forEach(r => userRequests.delete(r.id));
} else {
return res.status(404).json({ message: 'Endpoint not found' });
}
}
io.emit('endpoint_deleted', { id });
res.status(200).json({ message: 'Endpoint deleted' });
} catch (error) {
console.error('Error deleting endpoint:', error);
res.status(500).json({ error: 'Failed to delete endpoint' });
}
});
app.get('/api/requests', optionalAuth, async (req, res) => {
try {
const user = getAuthenticatedUser(req);
if (user) {
// Get user's requests from database
const requests = await getUserRequests(user.id);
res.json(requests);
} else {
// Get anonymous requests from memory for this cookie ID
const anonymousId = req.anonymousId;
const userRequests = anonymousRequests.get(anonymousId) || new Map();
const anonymousRequestsList = Array.from(userRequests.values());
res.json(anonymousRequestsList);
}
} catch (error) {
console.error('Error fetching requests:', error);
res.status(500).json({ error: 'Failed to fetch requests' });
}
});
app.get('/api/requests/:endpointId', optionalAuth, async (req, res) => {
try {
const { endpointId } = req.params;
if (req.isAuthenticated()) {
// Get requests from database
const requests = await getEndpointRequests(endpointId);
res.json(requests);
} else {
// Get requests from memory for this cookie ID
const anonymousId = req.anonymousId;
const userRequests = anonymousRequests.get(anonymousId) || new Map();
const endpointRequests = Array.from(userRequests.values()).filter(r => r.endpointId === endpointId);
res.json(endpointRequests);
}
} catch (error) {
console.error('Error fetching endpoint requests:', error);
res.status(500).json({ error: 'Failed to fetch requests' });
}
});
// Delete a specific request
app.delete('/api/requests/:id', optionalAuth, async (req, res) => {
try {
const { id } = req.params;
const user = getAuthenticatedUser(req);
if (user) {
// For authenticated users, delete from database
const deleted = await deleteRequest(id);
if (deleted) {
// Emit real-time update to connected clients
io.emit('requestDeleted', { requestId: id });
res.json({ message: 'Request deleted successfully' });
} else {
res.status(404).json({ error: 'Request not found' });
}
} else {
// For anonymous users, delete from memory
const anonymousId = req.anonymousId;
const userRequests = anonymousRequests.get(anonymousId) || new Map();
if (userRequests.has(id)) {
userRequests.delete(id);
// Emit real-time update to connected clients
io.emit('requestDeleted', { requestId: id });
res.json({ message: 'Request deleted successfully' });
} else {
res.status(404).json({ error: 'Request not found' });
}
}
} catch (error) {
console.error('Error deleting request:', error);
res.status(500).json({ error: 'Failed to delete request' });
}
});
// Serve React app for all non-API routes in production
if (process.env.NODE_ENV === 'production') {
app.get('*', (req, res, next) => {
// Skip if it's an API route or a dynamic endpoint
if (req.url.startsWith('/api/') || req.url.startsWith('/auth/') || req.url.startsWith('/health')) {
return next();
}
// If the URL looks like a UUID (dynamic endpoint), let it pass through
const pathSegment = req.url.split('/')[1];
if (pathSegment && pathSegment.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)) {
return next();
}
// Serve the React app
res.sendFile(join(__dirname, 'dist', 'index.html'));
});
}
// Catch-all route for dynamic endpoints (base path)
app.all('/:path', captureRequest, async (req, res) => {
try {
const { path } = req.params;
let endpoint;
// Try to find endpoint in database first
endpoint = await getEndpointByPath(path);
if (!endpoint) {
// Try to find in anonymous endpoints - search ALL anonymous users, not just current cookie
for (const [anonymousId, userEndpoints] of anonymousEndpoints) {
endpoint = Array.from(userEndpoints.values()).find(ep => ep.path === path);
if (endpoint) {
// Found the endpoint! Set the correct anonymousId for request tracking
req.anonymousId = anonymousId;
break;
}
}
}
if (!endpoint) {
return res.status(404).json({
error: 'Endpoint not found',
message: `No endpoint found for path: ${path}`
});
}
// Set endpoint data for request tracking
req.endpointId = endpoint.id;
req.endpoint = endpoint;
req.endpointPath = path;
req.endpointSubPath = undefined; // No sub-path for base route
req.endpointFullPath = path;
// Update request count
if (endpoint.user_id) {
// Database endpoint
await updateEndpointRequestCount(endpoint.id);
} else {
// Anonymous endpoint
const anonymousId = req.anonymousId;
const userEndpoints = anonymousEndpoints.get(anonymousId) || new Map();
userEndpoints.set(endpoint.id, {
...endpoint,
requestCount: endpoint.requestCount + 1
});
}
// Send successful response
res.status(200).json({
message: 'Request received successfully',
timestamp: new Date(),
endpoint: endpoint.name,
method: req.method,
path: path
});
} catch (error) {
console.error('Error handling dynamic endpoint:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Catch-all route for dynamic endpoints (with optional sub-paths)
app.all('/:path/*', captureRequest, async (req, res) => {
try {
const { path } = req.params;
const subPath = req.params[0]; // The wildcard part
const fullPath = `${path}/${subPath}`;
let endpoint;
// Try to find endpoint in database first (using only the base path)
endpoint = await getEndpointByPath(path);
if (!endpoint) {
// Try to find in anonymous endpoints - search ALL anonymous users, not just current cookie
for (const [anonymousId, userEndpoints] of anonymousEndpoints) {
endpoint = Array.from(userEndpoints.values()).find(ep => ep.path === path);
if (endpoint) {
// Found the endpoint! Set the correct anonymousId for request tracking
req.anonymousId = anonymousId;
break;
}
}
}
if (!endpoint) {
return res.status(404).json({
error: 'Endpoint not found',
message: `No endpoint found for path: ${path}`
});
}
// Set endpoint data for request tracking
req.endpointId = endpoint.id;
req.endpoint = endpoint;
req.endpointPath = path;
req.endpointSubPath = subPath;
req.endpointFullPath = fullPath;
// Update request count
if (endpoint.user_id) {
// Database endpoint
await updateEndpointRequestCount(endpoint.id);
} else {
// Anonymous endpoint
const anonymousId = req.anonymousId;
const userEndpoints = anonymousEndpoints.get(anonymousId) || new Map();
userEndpoints.set(endpoint.id, {
...endpoint,
requestCount: endpoint.requestCount + 1
});
}
// Send successful response
res.status(200).json({
message: 'Request received successfully',
timestamp: new Date(),
endpoint: endpoint.name,
method: req.method,
path: path,
subPath: subPath,
fullPath: fullPath
});
} catch (error) {
console.error('Error handling dynamic endpoint:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
io.on('connection', async (socket) => {
// Send initial data - endpoints and requests are now handled by HTTP requests
// with cookie-based identification
socket.on('disconnect', () => {
// Client disconnected
});
});
// Initialize database and start server
const PORT = process.env.PORT || 3001;
async function startServer() {
try {
await initDatabase();
console.log('Database initialized');
server.listen(PORT, () => {
console.log(`HookDebug server running on port ${PORT}`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
startServer();