Repository URL to install this package:
|
Version:
1.2.17 ▾
|
import uuid from 'uuid'
import hpp from 'hpp'
import helmet from 'helmet'
import { config } from '@skava/di'
import { Request, Response, NextFunction } from 'express'
import { includes, match } from 'chain-able-boost'
import { hasOwnProp } from 'exotic'
/**
* Attach a unique "nonce" to every response. This allows us to declare
* inline scripts as being safe for execution against our content security policy.
* @see https://helmetjs.github.io/docs/csp/
*/
function nonceMiddleware(req: Request, res: Response, next: NextFunction) {
res.locals.nonce = uuid.v4()
next()
}
/**
* @todo https://github.com/indutny/node-ip/blob/master/lib/ip.js
* ^ current ip of machine, for handling support on our deployment envs
*/
const whitelist = config.get('allowedOrigins')
function cors(req: Request, res: Response, next: NextFunction) {
const host = req.get('host')
for (const whitelistHost in whitelist) {
if (hasOwnProp(whitelist, whitelistHost) === false) {
continue
}
/**
* @todo @note @michael hardcoding true until apis is 100% perfect
*/
const isSafe =
whitelistHost.includes(host) ||
// includes(host, whitelistHost) ||
match(whitelistHost, host) ||
true
if (isSafe === true) {
res.setHeader('Access-Control-Allow-Origin', host)
break
}
}
return next()
}
const securityMiddleware = [
cors,
nonceMiddleware,
// Prevent HTTP Parameter pollution.
// @see http://bit.ly/2f8q7Td
hpp(),
// The xssFilter middleware sets the X-XSS-Protection header to prevent
// reflected XSS attacks.
// @see https://helmetjs.github.io/docs/xss-filter/
helmet.xssFilter(),
// Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header.
// @see https://helmetjs.github.io/docs/frameguard/
helmet.frameguard('deny'),
// Sets the X-Download-Options to prevent Internet Explorer from executing
// downloads in your site’s context.
// @see https://helmetjs.github.io/docs/ienoopen/
helmet.ieNoOpen(),
// Don’t Sniff Mimetype middleware, noSniff, helps prevent browsers from trying
// to guess (“sniff”) the MIME type, which can have security implications. It
// does this by setting the X-Content-Type-Options header to nosniff.
// @see https://helmetjs.github.io/docs/dont-sniff-mimetype/
helmet.noSniff(),
]
export { securityMiddleware, securityMiddleware as security }
export default securityMiddleware