-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
354 lines (296 loc) · 11.3 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
'use strict';
/* eslint no-console: 0 no-unused-vars: 0 */
const appInsights = require('app/components/app-insights');
const logger = require('app/components/logger');
const compression = require('compression');
const path = require('path');
const express = require('express');
const rewrite = require('express-urlrewrite');
const session = require('express-session');
const nunjucks = require('nunjucks');
const routes = require(`${__dirname}/app/routes`);
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const config = require('config');
const utils = require(`${__dirname}/app/components/utils`);
const packageJson = require(`${__dirname}/package`);
const helmet = require('helmet');
const {csrfSync, csrfSyncOptions} = require('csrf-sync');
const healthcheck = require(`${__dirname}/app/healthcheck`);
const fs = require('fs');
const https = require('https');
const {v4: uuidv4} = require('uuid');
const uuid = uuidv4();
const sanitizeRequestBody = require('app/middleware/sanitizeRequestBody');
const isEmpty = require('lodash').isEmpty;
const invoker = require('app/middleware/invoker');
const permissionsPolicy = require('permissions-policy');
exports.init = function (isA11yTest = false, a11yTestSession = {}, ftValue) {
const app = express();
const port = config.app.port;
const releaseVersion = packageJson.version;
const useHttps = config.app.useHttps.toLowerCase();
const govUkFrontendPath = path.resolve(require.resolve('govuk-frontend'), '../../');
// Initialise Azure Application Insights
appInsights.initAppInsights();
// Application settings
app.set('view engine', 'html');
app.set('views', ['app/steps', 'app/views']);
const isDev = app.get('env') === 'development';
const njkEnv = nunjucks.configure([
'app/steps',
'app/views',
govUkFrontendPath
], {
noCache: isDev,
express: app
});
const globals = {
currentYear: new Date().getFullYear(),
gtmId: config.gtmId,
enableTracking: config.enableTracking,
links: config.links,
nonce: uuid,
basePath: config.app.basePath
};
njkEnv.addGlobal('globals', globals);
app.use(compression());
app.use(rewrite(`${globals.basePath}/public/*`, '/public/$1'));
app.enable('trust proxy');
// Security library helmet to verify 11 smaller middleware functions
app.use(helmet());
// Content security policy to allow just assets from same domain
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ['\'self\''],
fontSrc: ['\'self\' data:', 'fonts.gstatic.com'],
scriptSrc: [
'\'self\'',
'\'sha256-GUQ5ad8JK5KmEWmROf3LZd9ge94daqNvd8xy9YS1iDw=\'',
'\'sha256-AaA9Rn5LTFZ5vKyp3xOfFcP4YbyOjvWn2up8IKHVAKk=\'',
'\'sha256-G29/qSW/JHHANtFhlrZVDZW1HOkCDRc78ggbqwwIJ2g=\'',
'https://www.google-analytics.com',
'https://*.googletagmanager.com',
'https://*.dynatrace.com',
'vcc-eu4.8x8.com',
'vcc-eu4b.8x8.com',
`'nonce-${uuid}'`
],
connectSrc: [
'\'self\'',
'https://*.google-analytics.com',
'https://*.analytics.google.com',
'https://*.googletagmanager.com',
'https://*.dynatrace.com',
'https://*.g.doubleclick.net'
],
workerSrc: ['\'self\'', 'blob:'],
mediaSrc: ['\'self\''],
frameSrc: ['vcc-eu4.8x8.com', 'vcc-eu4b.8x8.com'],
imgSrc: [
'\'self\'',
'\'self\' data:',
'https://*.google-analytics.com',
'https://*.analytics.google.com',
'https://*.googletagmanager.com',
'https://*.dynatrace.com',
'https://*.g.doubleclick.net',
'vcc-eu4.8x8.com',
'vcc-eu4b.8x8.com',
'ssl.gstatic.com',
'www.gstatic.com'
],
styleSrc: [
'\'self\'',
'\'unsafe-inline\'',
'tagmanager.google.com',
'fonts.googleapis.com'
],
frameAncestors: ['\'self\'']
},
browserSniff: false,
setAllHeaders: false
}));
// Http public key pinning
app.use(helmet.hpkp({
maxAge: 900,
sha256s: ['AbCdEf123=', 'XyzABC123=']
}));
// Referrer policy for helmet
app.use(helmet.referrerPolicy({
policy: 'origin'
}));
app.use(helmet.noCache());
app.use(helmet.xssFilter({setOnOldIE: true}));
app.use((req, res, next) => {
res.removeHeader('Accept-Ranges');
next();
});
app.use(permissionsPolicy({
features: {
camera: [],
microphone: [],
geolocation: []
},
})
);
const staticOptions = {
cacheControl: true,
setHeaders: (res) => res.setHeader('Cache-Control', 'max-age=604800'),
acceptRanges: false,
};
// Middleware to serve static assets
app.use('/public/stylesheets', express.static(`${__dirname}/public/stylesheets`, staticOptions));
app.use('/public/images', express.static(`${__dirname}/app/assets/images`, staticOptions));
app.use('/public/javascripts/govuk-frontend', express.static(govUkFrontendPath, staticOptions));
app.use('/public/javascripts', express.static(`${__dirname}/app/assets/javascripts`, staticOptions));
app.use('/public/javascripts', express.static(`${__dirname}/public/javascripts`, staticOptions));
app.use('/public/pdf', express.static(`${__dirname}/app/assets/pdf`));
app.use('/assets', express.static(`${govUkFrontendPath}/govuk/assets`, staticOptions));
// Elements refers to icon folder instead of images folder
app.use(favicon(path.join(govUkFrontendPath, 'govuk', 'assets', 'images', 'favicon.ico')));
// Support for parsing data in POSTs
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
// Send assetPath to all views
app.use((req, res, next) => {
res.locals.asset_path = `${globals.basePath}/public/`;
next();
});
// Support session data
app.use(session({
proxy: config.redis.proxy,
resave: config.redis.resave,
saveUninitialized: config.redis.saveUninitialized,
secret: config.redis.secret,
cookie: {
httpOnly: config.redis.cookie.httpOnly,
sameSite: config.redis.cookie.sameSite
},
store: utils.getStore(config.redis, session)
}));
healthcheck.setup(app);
app.use((req, res, next) => {
if (!req.session) {
return next(new Error('Unable to reach redis'));
}
if (isA11yTest && !isEmpty(a11yTestSession)) {
req.session = Object.assign(req.session, a11yTestSession);
}
next();
});
app.use((req, res, next) => {
req.session.cookie.secure = req.protocol === 'https';
next();
});
app.use((req, res, next) => {
if (!req.session.language) {
req.session.language = 'en';
}
if (req.query && req.query.lng && config.languages.includes(req.query.lng)) {
req.session.language = req.query.lng;
}
if (isA11yTest && !isEmpty(a11yTestSession)) {
req.session = Object.assign(req.session, a11yTestSession);
}
next();
});
const csrfOptions = csrfSync({
getTokenFromRequest: (req) => {
return req.body._csrf;
}, // Used to retrieve the token submitted by the user in a form
});
const {
csrfSynchronisedProtection,
generateToken,
} = csrfSync(csrfOptions);
if (config.app.useCSRFProtection === 'true') {
app.use((req, res, next) => {
// Exclude Dynatrace Beacon POST requests from CSRF check
if (req.method === 'POST' && req.path.startsWith('/rb_')) {
next();
} else {
csrfSynchronisedProtection(req, res, next);
}
});
}
app.get('/csrf-token', (req, res) => {
const csrfToken = generateToken(req);
res.json({ csrfToken });
});
app.use((req, res, next) => {
const csrfToken = generateToken(req);
res.locals.csrfToken = csrfToken;
next();
});
// Add variables that are available in all views
app.use(function (req, res, next) {
const commonContent = require(`app/resources/${req.session.language}/translation/common`);
res.locals.govuk = commonContent.govuk;
res.locals.serviceName = commonContent.serviceName;
res.locals.releaseVersion = releaseVersion;
next();
});
// Force HTTPs on production connections
if (useHttps === 'true') {
app.use(utils.forceHttps);
}
app.post('*', sanitizeRequestBody);
app.use(`${config.livenessEndpoint}`, (req, res) => {
res.json({status: 'UP'});
});
app.use((req, res, next) => {
res.locals.launchDarkly = {};
if (ftValue) {
res.locals.launchDarkly.ftValue = ftValue;
}
next();
});
app.use(`${config.app.basePath}/`, (req, res, next) => {
if (req.query.id && req.query.id !== req.session.regId) {
delete req.session.form;
}
req.session.regId = req.query.id || req.session.regId || req.sessionID;
next();
}, routes);
// Start the app
let http;
if (['development', 'testing'].includes(config.nodeEnvironment)) {
const sslDirectory = path.join(__dirname, 'app', 'resources', 'localhost-ssl');
const sslOptions = {
minVersion: 'TLSv1.2',
key: fs.readFileSync(path.join(sslDirectory, 'localhost.key')),
cert: fs.readFileSync(path.join(sslDirectory, 'localhost.crt'))
};
const server = https.createServer(sslOptions, app);
http = server.listen(port, () => {
console.log(`Application started: http://localhost:${port}${config.app.basePath}`);
});
} else {
http = app.listen(port, () => {
console.log(`Application started: http://localhost:${port}${config.app.basePath}`);
});
}
// PCQ Invoker
if (config.environment !== 'prod') {
invoker.addTo(app);
}
app.all('*', (req, res) => {
const commonContent = require(`app/resources/${req.session.language}/translation/common`);
const content = require(`app/resources/${req.session.language}/translation/errors/404`);
logger(req.sessionID).error(`Unhandled request ${req.url}`);
res.status(404).render('errors/error', {common: commonContent, content: content, error: '404'});
});
app.use((err, req, res, next) => {
const lang = req.session ? req.session.language : 'en';
const commonContent = require(`app/resources/${lang}/translation/common`);
const content = require(`app/resources/${lang}/translation/errors/500`);
logger(req.sessionID).error(err);
res.status(500).render('errors/error', {common: commonContent, content: content, error: '500'});
});
return {app, http};
};