forked from nathydre21/nepa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
237 lines (202 loc) · 7.3 KB
/
app.ts
File metadata and controls
237 lines (202 loc) · 7.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
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import { apiLimiter, ddosDetector, checkBlockedIP, ipRestriction, progressiveLimiter } from './middleware/rateLimiter';
import { configureSecurity } from './middleware/security';
import { apiKeyAuth } from './middleware/auth';
import { loggingMiddleware, setupGlobalErrorHandling, errorTracker } from './middleware/logger';
import { errorTracker as abuseDetector } from './middleware/abuseDetection';
import { captureAuditContext, auditRateLimit, auditSecurityAlert } from './middleware/auditMiddleware';
import { swaggerSpec } from './swagger';
import { upload } from './middleware/upload';
import { uploadDocument } from './controllers/DocumentController';
import { getDashboardData, generateReport, exportData } from './controllers/AnalyticsController';
import { applyPaymentSecurity, processPayment, getPaymentHistory, validatePayment } from './controllers/PaymentController';
import { setupRateLimitRoutes } from './routes/rateLimitRoutes';
import auditRoutes from './routes/auditRoutes';
import fraudRoutes from './routes/fraudRoutes';
import { auditCleanupService } from './services/AuditCleanupService';
import { registerAuditHandlers } from './databases/event-patterns/handlers/auditHandlers';
import { EventBus } from './databases/event-patterns/EventBus';
// Mock services for now - replace with actual implementations
const performanceMonitor = {
getHealthStatus: () => ({ status: 'healthy' }),
getMemoryUsage: () => ({ heapUsed: 0, heapTotal: 0, external: 0 }),
getRequestMetrics: (limit: number) => [],
getCustomMetrics: (limit: number) => []
};
const analyticsService = {
getAnalyticsData: () => ({ userEvents: [], activeUsers: 0 })
};
const app = express();
// Initialize cache system on startup
initializeCacheSystem().then(result => {
if (result.success) {
logger.info('Cache system initialized successfully', {
initializationTime: result.metrics.initializationTime,
services: result.services
});
} else {
logger.error('Cache system initialization failed', {
errors: result.errors,
warnings: result.warnings
});
}
}).catch(error => {
logger.error('Cache system initialization error:', error);
});
// Initialize logging and monitoring
logger.info('Application starting up', {
nodeEnv: process.env.NODE_ENV,
version: process.env.npm_package_version
});
// Initialize error tracking if DSN is provided
if (process.env.SENTRY_DSN) {
errorTracker.initialize({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
tracesSampleRate: parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || '0.1'),
release: process.env.npm_package_version
});
}
// 1. Comprehensive logging middleware (should be first)
app.use(...loggingMiddleware);
// 2. DDoS Protection and IP Blocking
app.use(ddosDetector);
app.use(checkBlockedIP);
app.use(ipRestriction);
// 3. Security Headers & CORS
configureSecurity(app);
// 4. Body Parsing
app.use(express.json({ limit: '10kb' })); // Limit body size for security
// 5. Progressive Rate Limiting
app.use('/api', progressiveLimiter);
// 6. Audit Context Capture (before rate limiting to capture all requests)
app.use('/api', captureAuditContext);
// 7. Advanced Rate Limiting (replaces basic rate limiting)
app.use('/api', advancedRateLimiter);
// 8. Audit rate limit breaches
app.use('/api', auditRateLimit);
// 9. Error tracking for abuse detection
app.use(abuseDetector);
// 10. Setup rate limiting routes
setupRateLimitRoutes(app);
// 11. Audit Routes
app.use('/api/audit', auditRoutes);
// 11b. Fraud detection API (ML scoring 0-100, manual review workflow, adaptive learning)
app.use('/api/fraud', fraudRoutes);
// 12. API Documentation
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use('/api-docs/v1', swaggerUi.serve, swaggerUi.setup(getVersionedSwaggerSpec('v1')));
app.use('/api-docs/v2', swaggerUi.serve, swaggerUi.setup(getVersionedSwaggerSpec('v2')));
// 11. Enhanced Health Check
app.get('/health', (req, res) => {
const healthStatus = performanceMonitor.getHealthStatus();
const memoryUsage = performanceMonitor.getMemoryUsage();
res.status(200).json({
status: 'UP',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
performance: healthStatus,
memory: {
used: memoryUsage.heapUsed,
total: memoryUsage.heapTotal,
external: memoryUsage.external
},
analytics: {
totalEvents: analyticsService.getAnalyticsData().userEvents.length,
activeUsers: analyticsService.getAnalyticsData().activeUsers
}
});
});
// 10. Monitoring endpoints (unversioned)
app.get('/api/monitoring/metrics', apiKeyAuth, (req, res) => {
const analytics = analyticsService.getAnalyticsData();
const performance = performanceMonitor.getHealthStatus();
res.json({
analytics,
performance,
requestMetrics: performanceMonitor.getRequestMetrics(100),
customMetrics: performanceMonitor.getCustomMetrics(100)
});
});
// 11. API version discovery (no auth required for discovery)
app.get('/api/versions', (_req, res) => {
res.json({
defaultVersion: apiVersioningConfig.defaultVersion,
latestVersion: apiVersioningConfig.latestVersion,
supportedVersions: apiVersioningConfig.supportedVersions,
lifecycle: apiVersioningConfig.lifecycle,
});
});
// Document Upload Route
/**
* @openapi
* /api/documents/upload:
* post:
* summary: Upload a document
* security:
* - ApiKeyAuth: []
* requestBody:
* content:
* multipart/form-data:
* schema:
* type: object
* properties:
* file:
* type: string
* format: binary
* userId:
* type: string
* responses:
* 201:
* description: Document uploaded successfully
*/
app.post('/api/documents/upload', apiKeyAuth, upload.single('file'), uploadDocument);
// Analytics Routes
/**
* @openapi
* /api/analytics/dashboard:
* get:
* summary: Get analytics dashboard data
* security:
* - ApiKeyAuth: []
* responses:
* 200:
* description: Dashboard data retrieved
*/
app.get('/api/analytics/dashboard', apiKeyAuth, getDashboardData);
/**
* @openapi
* /api/analytics/reports:
* post:
* summary: Generate and save a custom report
* security:
* - ApiKeyAuth: []
* responses:
* 201:
* description: Report created
*/
app.post('/api/analytics/reports', apiKeyAuth, generateReport);
// Export Route
app.get('/api/analytics/export', apiKeyAuth, exportData);
// Initialize audit system
const initializeAuditSystem = async () => {
try {
// Register audit event handlers
const eventBus = EventBus.getInstance();
registerAuditHandlers(eventBus);
// Start audit cleanup service
auditCleanupService.start();
logger.info('Audit system initialized successfully');
} catch (error) {
logger.error('Failed to initialize audit system:', error);
}
};
// Initialize audit system on startup
initializeAuditSystem();
export default app;
// Cache Management Routes (Admin only)
app.use('/api/cache', cacheRoutes);
// Add cache middleware to existing routes for better performance
// Note: These would be added to existing route definitions in a real implementation
export default app;