Express JS Important NPM Packages Related to Security
Few words before we start
When you create a website or application, it means you are ready to show it thousands of people on the internet. Your customer/audience may be legit, but some of them will try to tamper your application. So you need to follow the following golden rules
- “Never trust your audience when it comes to your application’s security”
- Always validate the user input before getting it into the server.
- Always encode the user inputs before printing them on to the screen.
helmet
The helmet is really like a helmet for your applications. It protects your application by setting up various HTTP headers.
const express = require('express')
const helmet = require('helmet')
const app = express()
app.use(helmet())
express-session
The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data.
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
secure: true
}
}))
cookie-session
A simple cookie-based session middleware, that allows storing cookies.It does not require any database/resources on the server side, though the total session data cannot exceed the browser’s max cookie size.
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.use(cookieSession({
name: 'session',
keys: [ /* secret keys */ ],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))
JOI
Object schema description language and validator for JavaScript objects by hapi. It is very useful to validate the user input.
const Joi = require('joi');
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email({
minDomainAtoms: 2
})
}).with('username', 'birthyear').without('password', 'access_token');
// Return result.
const result = Joi.validate({
username: 'abc',
birthyear: 1994
}, schema);
// result.error === null -> valid
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate({
username: 'abc',
birthyear: 1994
}, schema, function(err, value) {}); // err === null -> valid
express-rate-limit
You may aware of the brute force attack. express-rate-limit is a middleware for express routes that rate-limits incoming requests, increasing the delay with each request in a Fibonacci-like sequence.
const rateLimit = require("express-rate-limit");app.enable("trust proxy");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
});// apply to all requests
app.use(limiter);
express-jwt-permissions
A middleware that checks JWT tokens for permissions. It is very useful to build a user access control system.
var guard = require('express-jwt-permissions')()app.use(guard.check('admin'))
express-mongo-sanitize
Express middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.
var express = require('express'),
bodyParser = require('body-parser'),
mongoSanitize = require('express-mongo-sanitize');
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// To remove data, use:
app.use(mongoSanitize());
// Or, to replace prohibited characters with _, use:
app.use(mongoSanitize({
replaceWith: '_'
}))
hpp
Express middleware to protect against HTTP Parameter Pollution attacks. To know more read Chetan Karande’s slides
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
// ...
var hpp = require('hpp');
// ...
// Make sure the body is parsed beforehand.
app.use(bodyParser.urlencoded());app.use(hpp()); // <- THIS IS THE NEW LINE// Add your own middlewares afterwards, e.g.:
app.get('/search', function(req, res, next) { /* ... */ });
// They are safe from HTTP Parameter Pollution now.
dotenv
Dotenv is a zero-dependency module that loads environment variables from a .env
file into process.env.
. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
var express = require('express'),
bodyParser = require('body-parser'),
dotenv = require('dotenv');
var app = express();dotenv.config();
dotenv.config({
path: "../.env"
});
csurf
The csurf is a CSRF protection middleware.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({
cookie: true
})
var parseForm = bodyParser.urlencoded({
extended: false
})
// create express app
var app = express()
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// pass the csrfToken to the view
res.render('send', {
csrfToken: req.csrfToken()
})
})
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed')
})
I wish you happy coding.