Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if (!!env.get("ENABLE_GELF_LOGS")) {
messina = require("messina");
logger = messina("login.webmaker.org-" + env.get("NODE_ENV") || "development");
logger.init();
http.use(logger.middleware());
} else if (!env.get("DISABLE_HTTP_LOGGING")) {
http.use(express.logger());
}
http.use(helmet.iexss());
http.use(helmet.contentTypeOptions());
http.use(helmet.xframe());
if (!!env.get("FORCE_SSL")) {
http.use(helmet.hsts());
http.enable("trust proxy");
}
http.use(express.json());
http.use(express.urlencoded());
http.use(webmakerAuth.cookieParser());
http.use(webmakerAuth.cookieSession());
// Setup locales with i18n
http.use(i18n.middleware({
supported_languages: env.get("SUPPORTED_LANGS"),
default_lang: "en-US",
mappings: require("webmaker-locale-mapping"),
translation_directory: path.resolve(__dirname, "../../locale")
}));
spiderDetectorMiddleware(req, res, next);
});
app.use(session({
store: db.sessionStore,
secret: nconf.get('secret'),
key: nconf.get('sessionKey'),
cookie: setupCookie(),
resave: nconf.get('sessionResave') || false,
saveUninitialized: nconf.get('sessionSaveUninitialized') || false,
}));
app.use(helmet());
app.use(helmet.referrerPolicy({ policy: 'strict-origin-when-cross-origin' }));
if (meta.config['hsts-enabled']) {
app.use(helmet.hsts({
maxAge: meta.config['hsts-maxage'],
includeSubDomains: !!meta.config['hsts-subdomains'],
preload: !!meta.config['hsts-preload'],
}));
}
app.use(middleware.addHeaders);
app.use(middleware.processRender);
auth.initialize(app, middleware);
app.use(middleware.autoLocale); // must be added after auth middlewares are added
var toobusy = require('toobusy-js');
toobusy.maxLag(meta.config.eventLoopLagThreshold);
toobusy.interval(meta.config.eventLoopInterval);
}
public configure(app: App): void {
const logger = new Logger();
app.Express
// Enabling the cors headers
.options('*', cors())
.use(cors())
// Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help!
.use(helmet())
.use(helmet.noCache())
.use(helmet.hsts({
maxAge: 31536000,
includeSubdomains: true
}))
// Compress response bodies for all request that traverse through the middleware
.use(compression())
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
.use(bodyParser.json())
.use(bodyParser.urlencoded({
extended: true
}))
// Serve static filles like images from the public folder
.use(express.static(path.join(__dirname, '..', 'public'), { maxAge: 31557600000 }))
const onFinished = require('on-finished')
const cookieParser = require('cookie-parser')
const csurf = require('csurf')
const csrfExcludeRoutes = require('./constants/csrf-exclude-routes')
const auth = require('basic-auth')
const RateLimit = require('express-rate-limit')
const cookieSession = require('cookie-session')
var app = express()
// Use gzip compression - remove if possible via reverse proxy/Azure gateway.
app.use(compression())
// Set security headers.
app.use(helmet())
app.use(helmet.hsts({ maxAge: 5184000 }))
// Configure Content Security Policy
// Hashes for inline Gov Template script entries
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'",
'www.google-analytics.com',
"'sha256-+6WnXIl4mbFTCARd8N3COQmT3bJJmo32N8q8ZSQAIcU='",
"'sha256-G29/qSW/JHHANtFhlrZVDZW1HOkCDRc78ggbqwwIJ2g='"],
styleSrc: ["'self'"],
fontSrc: ['data:'],
imgSrc: ["'self'", 'www.google-analytics.com']
}
}))
process.on('SIGTERM', () => {
this.log('fatal', 'Received SIGTERM');
process.emit('cleanup');
});
process.on('SIGINT', () => {
this.log('fatal', 'Received SIGINT');
process.emit('cleanup');
});
/**
* Security.
*/
const ninetyDaysInMilliseconds = moment.duration(90, 'days').asMilliseconds();
app.use(helmet());
app.use(helmet.hidePoweredBy({setTo: `${hydra.getServiceName()}/${hydra.getInstanceVersion()}`}));
app.use(helmet.hsts({maxAge: ninetyDaysInMilliseconds}));
if (this.config.cors) {
app.use(cors(Object.assign({}, this.config.cors)));
} else {
app.use(cors());
}
if (this.config.bodyParser) {
let bodyParserConfig = Object.assign({json: {}, urlencoded: {extended: false}}, this.config.bodyParser);
app.use(bodyParser.json(bodyParserConfig.json));
app.use(bodyParser.urlencoded(bodyParserConfig.urlencoded));
} else {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
}
private initSecurityHeaders() {
this.app.disable('x-powered-by');
this.app.use(
helmet({
frameguard: {action: 'deny'},
}),
);
this.app.use(helmet.noSniff());
this.app.use(helmet.xssFilter());
this.app.use(
helmet.hsts({
includeSubDomains: true,
maxAge: 31536000,
preload: true,
}),
);
this.app.use(
helmet.contentSecurityPolicy({
browserSniff: true,
directives: this.config.SERVER.CSP,
disableAndroid: false,
loose: !this.config.SERVER.DEVELOPMENT,
reportOnly: false,
setAllHeaders: false,
}),
);
this.app.use(
app.use( express.logger( config.logger ) );
}
app.use( function( req, res, next ) {
var allowed = [ "/static/bower/font-awesome/font/" ];
for ( var i = 0; i < allowed.length; i++ ) {
if ( req.url.substring( 0, allowed[ i ].length ) === allowed[ i ] ) {
res.header( "Access-Control-Allow-Origin", "*" );
}
}
next();
});
app.use(helmet.iexss());
app.use(helmet.contentTypeOptions());
if ( !!config.FORCE_SSL ) {
app.use( helmet.hsts() );
app.enable( "trust proxy" );
}
app.use( express.compress() )
.use( lessMiddleware(rtltrForLess({
once: config.OPTIMIZE_CSS,
dest: tmpDir,
src: WWW_ROOT,
compress: config.OPTIMIZE_CSS,
yuicompress: config.OPTIMIZE_CSS,
optimization: config.OPTIMIZE_CSS ? 0 : 2
})))
.use( requirejsMiddleware({
src: WWW_ROOT,
dest: tmpDir,
debug: config.DEBUG,
once: config.OPTIMIZE_JS,
defaultSrc: ['"self"']
}
}),
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');
});
module.exports.initHelmetHeaders = (app) => {
const SIX_MONTHS = 15778476000;
app.use(helmet.frameguard());
app.use(helmet.xssFilter());
app.use(helmet.noSniff());
app.use(helmet.ieNoOpen());
app.use(helmet.hsts({
maxAge: SIX_MONTHS,
includeSubDomains: true,
force: true,
}));
app.disable('x-powered-by');
};