-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
124 lines (100 loc) · 5 KB
/
app.js
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
const path = require("path");
const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const rateLimit = require("express-rate-limit");
const mongoSanitize = require("express-mongo-sanitize");
const helmet = require("helmet");
const hpp = require("hpp");
const morgan = require("morgan");
const xss = require("xss-clean");
const globalErrorHandler = require("./controllers/errorController");
const AppError = require("./utils/AppError");
const tourRouter = require("./routes/tourRoutes");
const userRouter = require("./routes/userRoutes");
const bookingsRouter = require("./routes/bookingRoutes");
const reviewRouter = require("./routes/reviewRoutes");
const viewRouter = require("./routes/viewRoutes");
const app = express();
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));
//When running the application behind a reverse proxy or load balancer (common in production environments,
// here, a free cloud provider), the client's IP address might be hidden behind these
//proxy servers. By setting trust proxy to true, Express will trust the values of headers
// like X-Forwarded-For, making express-rate-limit accurately identify users even when
// the application is behind a proxy.
// When you have multiple servers (S1, S2, S3) behind a reverse proxy, each server doesn't
// have direct visibility into the rate limiting that the other servers are applying. Each
// server independently handles the incoming requests it receives. This can lead to a
// situation where the total rate limit across all servers might exceed the intended rate
// limit. To mitigate this we can use a central rate limiter instead of on the server.
// This project is for learning so rate limit is not a big concern here.
// ************** TODO **********
// https://github.com/express-rate-limit/express-rate-limit/wiki/Troubleshooting-Proxy-Issues
app.set("trust proxy", true);
// app.use(
// cors({
// origin: ["https://checkout.stripe.com"],
// })
// );
app.use(helmet());
// When the client-side code requests an image from another URL, such as an external API or a different domain,
//the browser will attempt to load the image. At this point, the CSP comes into play. The browser checks the CSP
//directives defined in the server's **response headers** or in the helmet.contentSecurityPolicy() middleware configuration.
// Directives specify the allowed sources for different types of resources (e.g., scripts, stylesheets, images, etc.).
app.use(
helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
// for loading external images for map using leaflet
imgSrc: ["'self'", "https: data:"],
scriptSrc: ["'self'", "https://js.stripe.com/v3/"],
frameSrc: ["'self'", "https://js.stripe.com/v3/"],
// for parcel bundler to establish connection between client and dev server for hot module replacement by creating a ws:// connection
connectSrc: ["'self'", "blob:", "wss:", "ws://localhost:*"],
},
})
);
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}
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.use(express.json({ limit: "10kb" }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// for nosql injection and xss attacks
app.use(mongoSanitize());
app.use(xss());
// app.use(compression());
// To protect against HTTP Parameter Pollution attacks, ( /endpoint?name=john&name=doe -> /endpoint?name=doe )
// We can whitelist some of the params which might be needed.
app.use(
hpp({
whitelist: ["duration", "price", "difficulty", "role"],
})
);
// configuring Express to serve static files from the "leaflet" directory, which is located in the node_modules
// therefore enabling the usage of the Leaflet.js library's static files by routing requests with "/leaflet"
app.use("/leaflet", express.static(path.join(__dirname, "node_modules/leaflet/dist")));
app.use(express.static(path.join(__dirname, "public")));
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", bookingsRouter);
// captures all requests for API endpoints that do not match any defined routes and responds with an error message
// indicating that the requested URL does not exist on the server.
app.all("*", (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
// This is a middleware that handles all error in the app
// When next(err) is called, Express looks for error-handling middleware that matches the signature (err, req, res, next).
// The next(err) function triggers the execution of the globalErrorHandler middleware, skipping any regular middleware that may be defined after it
// uncaught exception and unhandled rejection errors are handled in server using process module
app.use(globalErrorHandler);
module.exports = app;