-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
120 lines (106 loc) · 3.39 KB
/
index.js
File metadata and controls
120 lines (106 loc) · 3.39 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
// Imports
// =======
const result = require("dotenv").config({ path: ".env" });
const { sanitizeRequest } = require("./middleware/sanitizeRequest");
const morgan = require("morgan");
const fs = require("fs");
const path = require("path");
const rfs = require("rotating-file-stream");
// Express
// =======
// Import express
const express = require("express");
// Import cors
const cors = require("cors");
// Import helmet
const helmet = require("helmet");
// Use express
const app = express();
// Ensure log directory exists
const logDirectory = path.join(__dirname, "logs");
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
// Create a rotating write stream
const accessLogStream = rfs.createStream("access.log", {
interval: "1d", // rotate daily
path: logDirectory,
});
// Setup morgan logging
// Use a custom format to always include the IP address
const morganFormat = ":remote-addr - :method :url :status :response-time ms";
app.use(morgan(morganFormat, { stream: accessLogStream })); // Log to file
app.use(morgan(morganFormat)); // Also log to console
// Trust first proxy
app.set("trust proxy", 1);
// Use helmet for security headers
app.use(helmet());
// Apply sanitization middleware before routes
app.use(sanitizeRequest);
// Enable reading JSON data:
app.use(express.json());
// Enable reading from html elements:
app.use(express.urlencoded({ extended: true }));
// CORS configuration
const { allowedOrigins } = require("./config/cors");
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like servers, mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
console.log("Blocked by CORS:", origin);
callback(new Error("Not allowed by CORS"));
}
},
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With",
"Accept",
"Origin",
"x-api-key",
],
exposedHeaders: ["Content-Range", "X-Content-Range"],
maxAge: 86400, // Cache preflight requests for 24 hours
};
app.use(cors(corsOptions));
// Middleware to block access to hidden files or directories like .git
app.use((req, res, next) => {
if (req.url.match(/\/\..+/)) {
return res.status(403).send("Access denied");
}
next();
});
// Block specific suspicious patterns
app.use((req, res, next) => {
const blockedPaths = ["/.git/", "/.env", "/node_modules"];
if (blockedPaths.some((path) => req.url.includes(path))) {
console.warn(`Blocked attempt to access: ${req.url}`);
return res.status(404).send("Not found");
}
next();
});
// Rate Limiter
const rateLimit = require("express-rate-limit");
// Global rate limiter
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 200, // Increased to 200 requests per windowMs
message: "Too many requests from this IP, please try again later",
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
// Apply rate limiting to all routes
app.use(globalLimiter);
// Routes:
// =======
const homeRoutes = require("./routes/home");
app.use("/", homeRoutes);
// Server Port
// ===========
const port = process.env.PORT || PORT;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});