-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
163 lines (139 loc) · 4.27 KB
/
app.js
File metadata and controls
163 lines (139 loc) · 4.27 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
import morgan from 'morgan';
import express from 'express';
import qs from 'qs';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import mongoSanitize from 'express-mongo-sanitize';
import hpp from 'hpp';
import cookieParser from 'cookie-parser';
import compression from 'compression';
import cors from 'cors';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import AppError from './utils/appError.js';
import globalErrorHandler from './controllers/errorController.js';
import tourRouter from './routes/tourRoutes.js';
import userRouter from './routes/userRoutes.js';
import reviewRouter from './routes/reviewRoutes.js';
import bookingRouter from './routes/bookingRoutes.js';
import { webhookCheckout } from './controllers/bookingController.js';
import viewRouter from './routes/viewRoutes.js';
const app = express();
// Base path to project folder
const __dirname = path.dirname(fileURLToPath(import.meta.url));
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// ------------ 1) Middleware Functions -------------
// Serving static files
app.use(express.static(path.join(__dirname, 'public')));
// Set security HTTP headers with CSP configuration
const fontSrcUrls = [
'https://fonts.googleapis.com/',
'https://fonts.gstatic.com/',
];
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
connectSrc: [
"'self'",
'https://api.stripe.com',
'https://natours-xd6l.onrender.com',
],
scriptSrc: ["'self'", 'https://js.stripe.com'],
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com/'],
workerSrc: ["'self'", 'blob:'],
objectSrc: [],
imgSrc: [
"'self'",
'blob:',
'data:',
'https://*.tile.openstreetmap.org',
'https://a.tile.openstreetmap.org',
'https://b.tile.openstreetmap.org',
'https://c.tile.openstreetmap.org',
],
fontSrc: ["'self'", ...fontSrcUrls],
frameSrc: [
"'self'",
'https://js.stripe.com',
'https://hooks.stripe.com',
'https://checkout.stripe.com',
],
childSrc: [
"'self'",
'https://js.stripe.com',
'https://hooks.stripe.com',
'https://checkout.stripe.com',
],
},
}),
);
// Development Logging
if (process.env.NODE_ENV === 'development') app.use(morgan('dev'));
// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!',
});
app.use('/api', limiter);
app.post(
'/webhook-checkout',
express.raw({ type: 'application/json' }),
webhookCheckout,
);
// Body parser, reading data from body into req.body
app.use(express.json({ limit: '10kb' }));
app.use(cookieParser());
// Set query parser AFTER body parser
app.set('query parser', str => qs.parse(str));
// FIX: Make req.query writable before mongoSanitize (EXPRESS 5 COMPATIBILITY)
app.use((req, res, next) => {
// Create a writable copy of req.query
const queryObj = { ...req.query };
// Redefine req.query as a writable property
Object.defineProperty(req, 'query', {
value: queryObj,
writable: true,
enumerable: true,
configurable: true,
});
next();
});
// Data sanitization against NoSQL query injection - configure for Express 5
app.use(mongoSanitize());
// Prevent parameter pollution
app.use(
hpp({
whitelist: [
'duration',
'ratingsQuantity',
'ratingsAverage',
'maxGroupSize',
'difficulty',
'price',
],
}),
);
// Compress all responses sent to clients
app.use(compression());
// Test middleware
app.use((request, response, next) => {
request.requestTime = new Date().toISOString();
next();
});
app.use(cors());
// ------------- 3) Routes -------------
app.use('/', viewRouter);
app.use('/api/v1/tours', tourRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/reviews', reviewRouter);
app.use('/api/v1/bookings', bookingRouter);
// Fix for Express 5: Replace app.all('*', ...) with catch-all middleware
app.use((request, response, next) => {
next(new AppError(`Can't find ${request.originalUrl} on this server!`, 404));
});
// ERROR-HANDLING MIDDLEWARE
app.use(globalErrorHandler);
export default app;