@gospime/express-helmet-csp
Version:
Express helmet with Content security policy
41 lines (32 loc) • 1.13 kB
JavaScript
const helmet = require('helmet');
const uuidv4 = require('uuid/v4');
const isProduction = process.env.NODE_ENV === 'production';
const generate = (request, response, next) => {
response.locals.nonce = uuidv4().replace(/\-/g, '');
next();
};
const nonce = (request, response) => `'nonce-${response.locals.nonce}'`;
const _s = "'self'";
const _i = "'unsafe-inline'";
const _e = "'unsafe-eval'";
// https://helmetjs.github.io/docs/csp/
const cspDirectives = {
defaultSrc: [_s],
connectSrc: [_s, nonce], // ajax, websocket
scriptSrc: [_s, !isProduction ? _e : null, nonce].filter(Boolean),
styleSrc: [_s, _i, 'fonts.googleapis.com'],
fontSrc: [_s, 'fonts.gstatic.com'],
imgSrc: [_s, 'https:', 'data:'],
upgradeInsecureRequests: true,
reportUri: '/cspviola'
};
module.exports = (app, clientDirectives = {}) => {
app.use(generate);
const directives = { ...cspDirectives, ...clientDirectives };
app
// Production Best Practices
// http://expressjs.com/en/advanced/best-practice-security.html
.use(helmet())
.use(helmet.noCache())
.use(helmet.contentSecurityPolicy({ directives }));
};