-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
200 lines (173 loc) · 5.49 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
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
/*
* SpotXTracker - Upload and track your Spot X coordinates
* Copyright (c) 2020 John Nahlen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Module dependencies
const path = require('path');
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const helmet = require('helmet');
const compression = require('compression');
const session = require('express-session');
const MemoryStore = require('memorystore')(session);
const lusca = require('lusca');
const bodyParser = require('body-parser');
const _ = require('lodash');
const RateLimiterMemory = require('rate-limiter-flexible').RateLimiterMemory;
const rfs = require("rotating-file-stream");
// https://github.com/pillarjs/hbs
const hbs = require('hbs');
// Utilities
const isProduction = require('./utils/isProduction');
hbs.handlebars.registerHelper('eq', function(value1, value2, options) {
return options[value1 === value2 ? 'fn' : 'inverse'](this);
});
(async function() {
await require('./runSetupScriptsIfNecessary')();
}());
const createUuid = require('./utils/createUuid');
const memoryStore = new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
});
const app = express();
// view engine setup
app.set('views',path.join(__dirname,'views'));
app.set('view engine','hbs');
app.use(helmet({
/*{
directives: {
"script-src": ["'self'", "cdnjs.cloudflare.com", "maps.googleapis.com"],
},
reportOnly: true
}*/
contentSecurityPolicy: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 86400000,
sameSite: 'strict'
},
store: memoryStore,
secret: createUuid()
}));
app.use(function (req,res,next) {
res.locals.googleMapsApiKey = process.env.googleMapsApiKey;
next();
});
app.use(function (req,res,next) {
res.locals.TIMEZONE = process.env.timeZone;
next();
});
app.use(function (req,res,next) {
res.locals.env = process.env.NODE_ENV;
next();
});
app.use(function(req,res,next) {
res.locals.req = req;
next();
});
app.use(function (req,res,next) {
if (req.path === '/twilio') {
next();
return;
}
if (_.has(req.session,'authToken')) {
res.locals.signedIn = true;
}
next();
});
// Setup logging if production environment
if (isProduction()) {
// https://www.npmjs.com/package/rotating-file-stream
const accessLogStream = rfs.createStream('access.log',{
interval: '1d', // rotate daily
path: process.env.logsDir,
maxFiles: 30
});
app.use(logger('combined',{
stream: accessLogStream
}));
}
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,'public')));
const cacheControlMiddleware = function (req,res,next) {
res.setHeader('Cache-Control','public, max-age=2592000');
res.setHeader('Expires',new Date(Date.now() + 2592000000).toUTCString());
next();
};
app.get('/js/*',cacheControlMiddleware);
app.get('/css/*',cacheControlMiddleware);
app.get('/modals/*',cacheControlMiddleware);
// Temporarily block clients who are hitting the POST /login endpoint too many times, probably a script
// Essentially limits online attackers to 50 requests a day per IP.
// Although I really don't see users logging in more than 5-10 times a day at most (possibly using different devices)
const rateLimiter = new RateLimiterMemory({
storeClient: memoryStore,
keyPrefix: 'middleware',
points: 50, // 50 requests
duration: 86400, // per day by IP
blockDuration: 86400 // block for one day
});
const rateLimitMiddleware = function (pts) {
return function (req,res,next) {
rateLimiter.consume(req.ip,pts || 1).then(function () {
next();
}).catch(function () {
res.status(429).send('Too Many Requests');
});
};
};
app.get('/login',lusca.csrf());
app.post('/login',lusca.csrf(), rateLimitMiddleware(1));
require('./setupRoutes')(app);
// catch 404
app.use(function (req,res) {
res.status(404).render('404');
});
const allowedErrorMessages = ['CSRF token mismatch','CSRF token missing'];
/* Some error messages may contain sensitive information (e.g. database credentials, queries, etc.).
* Show a generic error message unless an error message is explicitly allowed.
*/
function getErrorMessage(err) {
if (allowedErrorMessages.indexOf(err.message) >= 0) {
return err.message;
}
return 'Internal Error';
}
const isCsrfTokenError = function(err) {
return err.message && (err.message === 'CSRF token mismatch' || err.message === 'CSRF token missing');
}
// error handler
app.use(function (err,req,res,next) {
const _isCsrfTokenError = isCsrfTokenError(err);
if (err && !_isCsrfTokenError) {
// This is not a CSRF error
console.error(err);
}
if (_isCsrfTokenError) {
err.status = 400; // 400 Bad Request
}
res.status(err.status || 500).render('error',{ message: getErrorMessage(err), error: err });
});
module.exports = app;