-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
219 lines (188 loc) · 6.52 KB
/
main.js
File metadata and controls
219 lines (188 loc) · 6.52 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const helmet = require('helmet');
const morgan = require('morgan');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./api/config/swagger');
// Import security middleware
const { rateLimiter, sanitizeBody, validateIdParam } = require('./api/middleware/securityMiddleware');
const { notFoundHandler, globalErrorHandler } = require('./api/middleware/errorHandler');
const app = express();
const PORT = process.env.PORT || 5000;
// ===========================================
// SWAGGER DOCUMENTATION (Before Helmet to avoid CSP issues)
// ===========================================
// Swagger UI options with CDN-hosted assets for Vercel compatibility
const swaggerUiOptions = {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'SDE Roadmap API Docs',
customCssUrl: 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.11.0/swagger-ui.min.css',
customJs: [
'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.11.0/swagger-ui-bundle.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.11.0/swagger-ui-standalone-preset.min.js'
],
swaggerOptions: {
persistAuthorization: true,
url: '/api-docs.json',
},
};
// Swagger UI - mounted BEFORE Helmet to avoid CSP blocking its assets
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, swaggerUiOptions));
// Serve swagger spec as JSON (also before Helmet)
app.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
// ===========================================
// SECURITY MIDDLEWARE
// ===========================================
// Helmet - Set security HTTP headers (after Swagger to not block Swagger UI)
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://sde-roadmap-alpha.vercel.app"],
},
},
crossOriginEmbedderPolicy: false, // Allow embedding for images/PDFs
crossOriginResourcePolicy: { policy: "cross-origin" }, // Allow cross-origin resource sharing
}));
// Rate Limiting - Protect against DDoS and brute-force attacks
app.use(rateLimiter);
// Request Logging - Morgan
app.use(morgan('combined'));
// ===========================================
// CORS CONFIGURATION
// ===========================================
const allowedOrigins = [
'https://sde-roadmap-alpha.vercel.app',
'http://localhost:3000',
'http://localhost:3001',
];
app.use(cors({
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl)
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
credentials: true,
optionsSuccessStatus: 200,
maxAge: 86400, // Cache preflight requests for 24 hours
}));
// ===========================================
// BODY PARSING WITH LIMITS
// ===========================================
// Limit JSON body size to prevent large payload attacks
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true, limit: '10kb' }));
// Sanitize request body to prevent XSS
app.use(sanitizeBody);
// ===========================================
// STATIC FILES
// ===========================================
app.use('/pdf', express.static(path.join(__dirname, 'pdf')));
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use('/notes', express.static(path.join(__dirname, 'notes')));
// ===========================================
// ROUTES
// ===========================================
// Import Routes
const roadmapRoutes = require('./api/routes/roadmapRoutes');
const videoRoutes = require('./api/routes/videoRoutes');
const questionRoutes = require('./api/routes/questionRoutes');
const notesRoutes = require('./api/routes/notesRoutes');
// Use Routes
app.use('/api/roadmap', roadmapRoutes);
app.use('/api/videos', videoRoutes);
app.use('/api/questions', questionRoutes);
app.use('/api/notes', notesRoutes);
/**
* @swagger
* /:
* get:
* summary: API root endpoint
* tags: [Health]
* responses:
* 200:
* description: API status information
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: success
* message:
* type: string
* example: SDE Roadmap API is running!
* version:
* type: string
* example: 1.0.0
* documentation:
* type: string
* example: /api-docs
*/
app.get('/', (req, res) => {
res.json({
status: 'success',
message: 'SDE Roadmap API is running!',
version: '1.0.0',
documentation: '/api-docs',
});
});
/**
* @swagger
* /health:
* get:
* summary: Health check endpoint
* tags: [Health]
* responses:
* 200:
* description: Server health status
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: healthy
* timestamp:
* type: string
* format: date-time
*/
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
});
});
// ===========================================
// ERROR HANDLING
// ===========================================
// Handle 404 - Route not found
app.use(notFoundHandler);
// Global error handler
app.use(globalErrorHandler);
// ===========================================
// START SERVER
// ===========================================
if (require.main === module) {
app.listen(PORT, () => {
console.log(`🚀 Server is running on port ${PORT}`);
console.log(`📚 API Documentation: http://localhost:${PORT}/api-docs`);
console.log(`🔒 Security features enabled: Helmet, Rate Limiting, CORS, XSS Protection`);
});
}
module.exports = app; // Export the app for Vercel