The Startup
Published in

The Startup

5 Node.js Packages To Prevent Common Security Vulnerabilities

Build robust apps

Security cameras
Photo by Scott Webb on Unsplash.

Some will think about security when developing an application and some may not. During the development phase, security is very critical. Let’s look at the basics before jumping into the post. What’s API protection, for example, and why is it so important? API security is the protection of the integrity of the APIs we use and own. Nowadays, most companies are using the API to link services and move data. If the API is broken, exposed, or hacked, it will result in a breach of the data. So, on the basis of the information transferred, we need to consider the level of API security that we are going to implement in the application. In this article, I will show some useful npm packages that will help us to avoid common security issues.

1. Use Helmet

Helmet.js is a Node.js module that helps protected HTTP headers. It is implemented in the sense of express applications. We may also claim that helmet.js helps to secure express applications. Sets various HTTP headers to avoid attacks such as Cross-Site-Scripting (XSS), clickjacking, etc.

Why HTTP header protection is important: often developers ignore HTTP headers. Since HTTP headers can leak sensitive information about the application, it is therefore essential to use the headers in a safe manner.

Node-Modules included in Helmet.js are: Helmet.js comes with more built-in modules to improve the protection of the Express program.

  • X-Frame-Options: is used to avoid ClickJacking.
  • Content-Security-Policy: Sets up the Security Policy.
  • Cache-Control: is used to disable Client-Side caching.
  • Expect-CT: Used for the handling of Certificate Transparency.
  • X-DNS-Prefetch-Control: is used to control DNS browser retrieval.
  • X-Powered-By: is used to delete the X-Powered-By header. X-Powered-The server version and its vendor are leaked by the header.
  • Public-Key-Pins: is used to pin the public HTTP key.
  • X-XSS-Protection: is used to provide protection to XSS attacks.
  • Strict-Transport-Security: is used for the HTTP Strict Transport Policy.
  • X-Download-Options: it is limited to different Download-Options.
  • X-Content-Type-Options: is used to avoid a Sniffing attack.
  • Referrer-Policy: is used to cover the header of the referrer.

2. Use Cookies Securely

To ensure that cookies don’t open up your app to exploits, don’t use the default session cookie name and set cookie security options appropriately.

There are two main middleware cookie session modules:

  • express-session replaces express.session middleware built into Express 3.x.
  • cookie-session replaces express.cookieSession middleware built into Express 3.x.

The main difference between these two modules is how they save cookie session data. The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store; see the list of compatible session stores.

Don’t use the default session cookie name

Using the default session cookie name can open your app to attacks. To avoid this problem, use generic cookie names; for example, using express-session middleware:

var session = require('express-session')
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 's3Cur3',
name: 'sessionId'
}))

Set cookie security options

Set the following cookie options to enhance security:

  • secure - Ensures the browser only sends the cookie over HTTPS.
  • httpOnly - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.
  • domain - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.
  • path - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.
  • expires - use to set the expiration date for persistent cookies.

Here is an example using cookie-session middleware:

var session = require('cookie-session')
var express = require('express')
var app = express()
var expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
name: 'session',
keys: ['key1', 'key2'],
cookie: {
secure: true,
httpOnly: true,
domain: 'example.com',
path: 'foo/bar',
expires: expiryDate
}
}))

3. Prevent NoSQL injections

SQL Injection is a common attack vector, but it is no longer as prevalent as it used to be. There are several modern applications that use NoSQL databases. Attackers will try to invade our application with this NoSQL injection. It is therefore very important to take this problem into account. I’m going to illustrate this problem with an example and a solution to this issue.

From the above example as you can see it’s returning the token without the email. Using the above operator attacker can be able to get the email address that belongs to the application. If we used password-encryption they can’t do the same but what if the user used some common password as above. This is a very serious vulnerability in the application. How can we overcome this issue?

To overcome this issue you can use the express-mongo-sanitize package. Don’t think much that you need to code a lot to solve this issue. Simply using this package and initialize it as the express middleware in server.js before defining your routes will solve this issue.

$ npm I express-mongo-sanitize to install the package to your node application. Then import the package to your server.js file.

const mongoSanitize = require(“express-mongo-sanitize”);

After this initialize the package using:

app.use(mongoSanitize());

See how easily we solved this issue with the express-mongo-sanitize package.

4. Prevent ReDoS Attack

The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly.

Use safe-regex to ensure your regular expressions are not susceptible to regular expression denial of service attacks.

WARNING: This module has both false positives and false negatives. Use vuln-regex-detector for improved accuracy.

Example

Suppose you have a script named safe.js:

var safe = require('safe-regex');var regex = process.argv.slice(2).join(' ');console.log(safe(regex));

This is its behavior:

$ node safe.js '(x+x+)+y'
false
$ node safe.js '(beep|boop)*'
true
$ node safe.js '(a+){10}'
false
$ node safe.js '\blocation\s*:[^:\n]+\b(Oakland|San Francisco)\b'
true

5. Prevent CSRF Attack

Cross-site Request Forgery (CSRF) vulnerabilities occur when a web server receives a malicious request from a trusted browser. An attacker can create a malicious link that lets them, for example, transfer money from a user’s online bank account to another account. The attacker can use social engineering to make the user click this link. Because the user is already logged in, the server executes the action using their account.

Use csurf middleware to protect against cross-site request forgery (CSRF).

Node.js CSRF protection middleware requires either a session middleware or cookie-parser to be initialized first.

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

15 Regular Expression Tricks & Tips for You

How to create a Chrome Extension

My Journey from PHP & Wordpress to FullStack Javascript

How I built a Chrome Extension to aid Work from Home

How To Create a Dynamic Select Box With the Select2 Library

Creating a Basic HTML Select Box With Select2 Library

JavaScript’s Reduce Method

Deep Linking React Native App for OAuth 2.0. The basics.

Typescript Typing (unusual)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Developer Jas

Developer Jas

Full Stack Developer | Problem Solver | Helper :)

More from Medium

Building Your Own E-Commerce Keystone.js-Based System — Access Control

A grocery store

HTTP Logging with Morgan and Winston

How to Build a Webex Chatbot in Node.js

Run PostgreSQL with Docker locally and connect to it with Node.js