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
|
import express, { Request, Response } from 'express';
import session from 'express-session';
import rateLimit from 'express-rate-limit';
import slowDown from 'express-slow-down';
import path from 'path';
import { env } from 'process';
import helmet from 'helmet';
import csurf from 'csurf';
const app = express();
// Middleware
const port: string = env.PORT || '2000';
const csrf = csurf({ cookie: false });
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
}));
const rateLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 30, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
const speedLimiter = slowDown({
windowMs: 15 * 60 * 1000, // 15 minutes
delayAfter: 100, // allow 100 requests per 15 minutes, then...
delayMs: 500 // begin adding 500ms of delay per request above 100:
// request # 101 is delayed by 500ms
// request # 102 is delayed by 1000ms
// request # 103 is delayed by 1500ms
// etc.
});
// This will be run behind an nginx proxy
app.enable('trust proxy');
// apply to all requests
app.use(speedLimiter);
app.use('/api', rateLimiter);
app.use(helmet());
// Add ejs as view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views/pages'));
app.use('/public', express.static(path.join(__dirname, 'public')));
app.get('/', csrf, (req: Request, res: Response) => {
res.render('index', {
errors: [],
});
});
app.get('/about', csrf, (req: Request, res: Response) => {
res.render('about');
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
|