Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
extended: true
}));
app.use(bodyParser.json());
app.use(compression({level: 9})); //use compression
app.use(methodOverride());
// CookieParser should be above session
app.use(cookieParser());
// connect flash for flash messages
//app.use(flash());
// Use helmet to secure Express headers
// app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "x-openrtb-version,Content-Type,*");
res.header("X-Frame-Options", "ALLOWALL");
if (req.method === 'OPTIONS') {
console.log("INFO: Browser send OPTIONS request.");
res.statusCode = 204;
return res.end();
} else {
return next();
}
};
// Set compression before any routes
app.use(compression({ threshold: 512 }));
app.use(cookieParser());
app.io.session(session);
auth.setup(app, session, core);
// Security protections
app.use(helmet.frameguard());
app.use(helmet.hidePoweredBy());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.xssFilter());
app.use(helmet.hsts({
maxAge: 31536000,
includeSubdomains: true,
force: httpsEnabled,
preload: true
}));
app.use(helmet.contentSecurityPolicy({
defaultSrc: ['\'none\''],
connectSrc: ['*'],
scriptSrc: ['\'self\'', '\'unsafe-eval\''],
styleSrc: ['\'self\'', 'fonts.googleapis.com', '\'unsafe-inline\''],
fontSrc: ['\'self\'', 'fonts.gstatic.com'],
mediaSrc: ['\'self\''],
objectSrc: ['\'self\''],
imgSrc: ['* data:']
}));
function initHelmetHeaders(app) {
// Use helmet to secure Express headers
app.use(helmet.xssFilter());
app.use(helmet.noSniff());
app.use(helmet.frameguard());
app.use(helmet.ieNoOpen());
app.use(crossdomain());
app.use(helmet.hidePoweredBy());
}
private middleware(): void {
this.express.use(passport.initialize());
// required for passport to initlize it
this.express.use(expressSession({ secret: 'bla bla' }));
this.express.use(passport.session());
// initlize session
this.express.use(logger('dev'));
this.express.disable('x-powered-by');
this.express.disable('etag');
this.express.use(helmet());
this.express.use(boom());
this.express.use(helmet.noCache({ noEtag: true })); // set Cache-Control header
this.express.use(helmet.noSniff()); // set X-Content-Type-Options header
this.express.use(helmet.frameguard()); // set X-Frame-Options header
this.express.use(helmet.xssFilter()); // set X-XSS-Protection header
// logger logs on console
this.express.use(bodyParser.urlencoded({ extended: false, limit: '5mb' })); // parse application/x-www-form-urlencoded
this.express.use(bodyParser.json()); // parse application/json
// enable CORS
this.express.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, PATCH, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, api_key, Authorization, Referer');
next();
});
// register all custom Middleware
this.express.use(cors({ optionsSuccessStatus: 200 }));
this.express.use(cookieParser()); // cookies-parser
// manage session by cookies
this.express.set('views', path.join(__dirname, 'views')); // setting views
this.express.set('view engine', 'hbs');
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
// connect flash for flash messages
app.use(flash());
// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
// If the error object doesn't exists
if (!err) return next();
if (config.get('useDatadog') && config.get('datadogHost')) {
_log.info('Recording DataDog timing stats for all responses');
app.use(middleware.datadogTiming({ _HotShots }));
}
// Set HTTP Strict Transport Security headers
app.use(middleware.hsts());
// Sets X-Frame-Options
app.use(middleware.frameguard());
// Sets x-content-type-options:"nosniff"
app.use(helmet.noSniff());
// Sets x-xss-protection:"1; mode=block"
app.use(helmet.xssFilter());
// CSP configuration.
app.use(middleware.csp());
// Serve assets locally from node ap (no-op by default).
if (config.get('enableNodeStatics')) {
app.use(middleware.serveAssetsLocally());
}
// This middleware adds `universalCookies` to the Express request.
app.use(cookiesMiddleware());
// Following the ops monitoring Dockerflow convention, return version info at
// this URL. See: https://github.com/mozilla-services/Dockerflow
app.get('/__version__', viewFrontendVersionHandler());
// For AMO, this helps differentiate from /__version__ served by addons-server.
// objectSrc: [ "'none'" ],
// mediaSrc: [ "'none'" ],
childSrc: ["'self'"],
},
}
: null;
if (enableCSP) {
app.use(helmet.contentSecurityPolicy(cspConfig));
}
// The xssFilter middleware sets the X-XSS-Protection header to prevent
// reflected XSS attacks.
// @see https://helmetjs.github.io/docs/xss-filter/
app.use(helmet.xssFilter());
// Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header.
// We disable this for embedding
// @see https://helmetjs.github.io/docs/frameguard/
app.use(helmet.frameguard('false'));
// Sets the X-Download-Options to prevent Internet Explorer from executing
// downloads in your site’s context.
// @see https://helmetjs.github.io/docs/ienoopen/
app.use(helmet.ieNoOpen());
// Strict-Transport-Security: https://github.com/helmetjs/hsts
app.use(
helmet.hsts({
maxAge: ms(hstsMA) / 1000,
includeSubdomains: true,
preload: true,
helmet.featurePolicy({
features: {
fullscreen: ['"self"'],
vibrate: ['"none"'],
payment: ['"none"'],
syncXhr: ['"none"']
}
}),
helmet.referrerPolicy({ policy: 'same-origin' }),
helmet.frameguard({
action: 'deny'
}),
helmet.hsts({
maxAge: 15768000 //Six Months in Seconds
}),
helmet.xssFilter(),
helmet.noSniff(),
cors({
origin: '*',
methods: 'GET',
preflightContinue: false,
optionsSuccessStatus: 204
})
);
app.get('/', (req, res) => {
res.send('Hello There');
});
/**
* Login using the Spotify API (This is only a Redirect)
*/
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secrets.sessionSecret,
store: new MongoStore({
url: secrets.db,
'autoReconnect': true
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.disable('x-powered-by');
app.use(helmet.xssFilter());
app.use(helmet.noSniff());
app.use(helmet.xframe());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var trusted = [
"'self'",
'*.freecodecamp.com',
'*.gstatic.com',
'*.google-analytics.com',
'*.googleapis.com',
'*.google.com',
'*.gstatic.com',
function addMiddleware(server) {
server.use(express.static(path.join(APP_PATH, 'static')))
server.use(bodyParser.json())
server.use(hpp())
server.use(helmet.contentSecurityPolicy({
defaultSrc: [ "'self'" ],
scriptSrc: [ "'self'" ],
styleSrc: [ "'self'" ],
imgSrc: [ "'self'" ],
connectSrc: [ "'self'", 'ws:' ],
fontSrc: [ "'self'" ],
objectSrc: [ "'none'" ],
mediaSrc: [ "'none'" ],
frameSrc: [ "'none'" ]
}))
server.use(helmet.xssFilter())
server.use(helmet.frameguard('deny'))
server.use(helmet.ieNoOpen())
server.use(helmet.noSniff())
}