-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import crypto from 'crypto' | ||
import { RequestHandler } from 'express' | ||
import helmet from 'helmet' | ||
|
||
import config from '../../config/config' | ||
|
||
import { CSP_CORE_DIRECTIVES } from './constants' | ||
|
||
const helmetMiddlewares = () => { | ||
// Only add the "Strict-Transport-Security" header if request is https. | ||
const hstsMiddleware: RequestHandler = (req, res, next) => { | ||
if (req.secure) { | ||
helmet.hsts({ maxAge: 400 * 24 * 60 * 60 })(req, res, next) // 400 days | ||
} else next() | ||
} | ||
|
||
const generateNonceMiddleware: RequestHandler = (req, res, next) => { | ||
res.locals.nonce = | ||
res.locals.nonce || crypto.randomBytes(32).toString('hex') | ||
|
||
next() | ||
} | ||
const xssFilterMiddleware = helmet.xssFilter() | ||
|
||
const noSniffMiddleware = helmet.noSniff() | ||
|
||
const ieNoOpenMiddlware = helmet.ieNoOpen() | ||
|
||
const dnsPrefetchControlMiddleware = helmet.dnsPrefetchControl() | ||
|
||
const hidePoweredByMiddleware = helmet.hidePoweredBy() | ||
|
||
const referrerPolicyMiddleware = helmet.referrerPolicy({ | ||
policy: 'strict-origin-when-cross-origin', | ||
}) | ||
|
||
const cspCoreDirectives = CSP_CORE_DIRECTIVES | ||
|
||
const cspOptionalDirectives = config.isDev | ||
? // Remove upgradeInsecureRequest CSP header if config.isDev | ||
// See https://github.com/helmetjs/helmet for use of null to disable default | ||
{ upgradeInsecureRequests: null } | ||
: null | ||
|
||
const contentSecurityPolicyMiddleware = helmet.contentSecurityPolicy({ | ||
useDefaults: true, | ||
directives: { | ||
...cspCoreDirectives, | ||
...cspOptionalDirectives, | ||
}, | ||
}) | ||
return [ | ||
generateNonceMiddleware, | ||
xssFilterMiddleware, | ||
noSniffMiddleware, | ||
ieNoOpenMiddlware, | ||
dnsPrefetchControlMiddleware, | ||
hidePoweredByMiddleware, | ||
hstsMiddleware, | ||
referrerPolicyMiddleware, | ||
contentSecurityPolicyMiddleware, | ||
] | ||
} | ||
|
||
export default helmetMiddlewares |