Express JS Important NPM Packages Related to Security

Express JS Important NPM Packages Related to Security

·

6 min read

Express JS Important NPM Packages Related to Security

Image for post

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

  1. Never trust your audience when it comes to your application’s security
  2. Always validate the user input before getting it into the server.
  3. 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.

Image for post

Image for post
const express **=** require('express')
const helmet **=** require('helmet')
const app **=** express()
app.use(helmet())</span>

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.

Image for post

Image for post
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {
        secure: true
    }
}))</span>

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.

Image for post

Image for post
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
}))</span>

JOI

Object schema description language and validator for JavaScript objects by hapi. It is very useful to validate the user input.

Image for post

Image for post
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</span>

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.

Image for post

Image for post
app.enable("trust proxy");

const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, 
    max: 100 
});</span><span id="c64c" class="eh lb iy as lv b gv mb mc md me mf lx r ly">//  apply to all requests
app.use(limiter);</span>

express-jwt-permissions

A middleware that checks JWT tokens for permissions. It is very useful to build a user access control system.

Image for post

Image for post
app.use(guard.check('admin'))</span>

express-mongo-sanitize

Express middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.

Image for post

Image for post
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: '_'
}))</span>

hpp

Express middleware to protect against HTTP Parameter Pollution attacks. To know more read Chetan Karande’s slides

Image for post

Image for post
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());</span><span id="f36a" class="eh lb iy as lv b gv mb mc md me mf lx r ly">app.use(hpp()); // <- THIS IS THE NEW LINE</span><span id="1f36" class="eh lb iy as lv b gv mb mc md me mf lx r ly">// Add your own middlewares afterwards, e.g.:
app.get('/search', function(req, res, next) { /* ... */ });
// They are safe from HTTP Parameter Pollution now.</span>

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.

Image for post

Image for post
var express = require('express'),
    bodyParser = require('body-parser'),
    dotenv = require('dotenv');
var app = express();</span><span id="ea3c" class="eh lb iy as lv b gv mb mc md me mf lx r ly">dotenv.config();
dotenv.config({
    path: "../.env"
});</span>

csurf

The csurf is a CSRF protection middleware.

Image for post

Image for post
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')
})</span>

I wish you happy coding.

If you enjoyed this article, please clap it up and share it so that others can find it!