BOOK THIS SPACE FOR AD
ARTICLE ADNode.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project! Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant. A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.
Input validation— node-input-validator
Authentication— okta
Error handlingData leak preventionlogging and monitoringUsing linter pluginsHTTP response headers— Helmet
Input validation is performed to ensure only properly formed data is entering the workflow in an information system, preventing malformed data from persisting in the database and triggering malfunction of various downstream components. Input validation should happen as early as possible in the data flow, preferably as soon as the data is received from the external party.
Node Input Validator or NIV is a validation library for NodeJs, inspired by Laravel. Node Input Validator has a vast collection of inbuilt rules. This package is fully customizable or expendable with rules, messages, nicknames (used to change attributes in error messages), etc. Many times the NIV collection of rules would be sufficient for the project, But sometimes even in small projects you may need to validate some attribute under custom conditions, there may be database involvement or you may have another unique problem that NIV rules are unable to satisfy. node input validator or NIV is fully customizable or expendable, you can add your own custom rules to it.
Installation
npm i node-input-validatorUsage
Simple Example
const { Validator } = require('node-input-validator');const v = new Validator({ name: '' },
{ name: 'required|minLength:5' },
);v.check().then(function (matched) {
console.log(matched);
console.log(v.errors);
});
Within express application
const { Validator } = require('node-input-validator');app.post('login', function (req, res) {const v = new Validator(req.body, {
email: 'required|email',
password: 'required'
}); v.check().then((matched) => {
if (!matched) {
res.status(422).send(v.errors);
}
});
});
With async-await
const { Validator } = require('node-input-validator');router.post('login', async (ctx) => {const v = new Validator(ctx.request.body, {
email: 'required|email',
password: 'required'
}); const matched = await v.check(); if (!matched) {
ctx.status = 422;
ctx.body = v.errors;
return;
}
});
Having a broken, weak, or incomplete authentication mechanism is ranked as the second most common vulnerability. It’s probably due to the fact that many developers think about authentication as “we have it, so we’re secure.” In reality, weak or inconsistent authentication is easy to bypass. One solution is to use existing authentication solutions like Okta or OAuth.
Okta allows you to control access to your application using both the OAuth 2.0 and OpenID Connect specifications. You can use Okta as your authorization server to retain all of your user information, and grant users tokens to control their authorization and authentication. Okta also supports using social logins. free Okta developer account. Install the Okta CLI and run the okta register to sign up for a new account. If you already have an account, run okta login. Then, run okta apps create. Select the default app name, or change it as you see fit. Choose Web and press Enter. Select Other. Then, change the Redirect URI to http://localhost:3000/callback and use http://localhost:3000 for the Logout Redirect URI. The Okta CLI will create an OIDC Web App in your Okta Org. It will add the redirect URIs you specified and grant access to the Everyone group. You will see output like the following when it’s finished:
Okta application configuration has been written to/path/to/app/.okta.envRun cat .okta.env (or type .okta.env on Windows) to see the issuer and credentials for your app. ``node export OKTA_OAUTH2_ISSUER=”https://dev-133337.okta.com/oauth2/default" export OKTA_OAUTH2_CLIENT_ID=”0oab8eb55Kb9jdMIr5d6" export OKTA_OAUTH2_CLIENT_SECRET=”NEVER-SHOW-SECRETS”
Install Schematics CLI:```shell
npm install -g @angular-devkit/schematics-cli
Install and run OktaDev Schematics with your Okta values for $issuer, $clientId, and $clientSecret:
npm i -D @oktadev/schematicsschematics @oktadev/schematics:add-auth --issuer=$issuer --clientId=$clientId --clientSecret=$clientSecret
Start your app and authenticate with Okta
npm startError handling is one of those parts of software development that don’t quite get the amount of attention it really deserves. However, building robust applications requires dealing with errors properly. You can get by in NodeJS without properly handling errors but due to the asynchronous nature of NodeJS, improper handling or errors can cause you pain soon enough especially when debugging applications.
async function someFunction() {try {
await someOtherFunction()
} catch (err) {
console.error(err.message)
}
}
You can just go ahead with easily sending all the information for the specific object to the front end and filter what will display there. Doing that is very simple as hackers always try finding the hidden data sent from the backend. The solution that you will have to apply in this case is to only consider sending the information needed. In case you require the first and last names, make sure about just retrieved from the database.
Logging and monitoring are important, but you might think they have nothing to do with security, but they are not. Of course, the goal is to make the system secure in the first place, but in practice, it requires an ongoing process. This requires logging and monitoring. Some hackers might be interested in making your application unusable. This can be found without logging it. However, some hackers like to go undiscovered for long periods of time. In such cases, monitoring logs and metrics can help you understand the problem. The default logs alone don’t give you enough information to understand what looks strange from your application, a third-party API, or a hacker.
$ npm init -y$ npm i express dotenv spm-agent-nodejs
This is everything you need in order to have an APM tool running and monitoring your application. Now, create two files, an app.js and a .env. Add this piece of code to the app.js.
require('dotenv').config()require('spm-agent-nodejs')
const express = require('express')
const app = express()app.get('/api', (req, res, next) => {
res.status(200).send('Api Works.')
})
app.get('/api/fast', (req, res, next) => {
res.status(200).send('Fast response!')
})
app.get('/api/slow', (req, res, next) => {
setTimeout(() => {
res.status(200).send('Slow response...')
}, 1000)
})
app.get('/api/error', (req, res, next) => {
try {
throw new Error('Something broke...')
} catch (error) {
res.status(500).send(error)
}
})
app.listen(3000, () =>
console.log('Server is running on port 3000'))
linter plugins like eslint-plugin-security. A security linter will notify you every time you use unsafe code practices (for example using eval or non-literal regex expressions).
Installation
$ npm install --save-dev eslint eslint-plugin-nodeUsage
{"extends": [
"eslint:recommended",
"plugin:node/recommended"
],
"parserOptions": {
// Only ESLint 6.2.0 and later support ES2020.
"ecmaVersion": 2020
},
"rules": {
"node/exports-style": ["error", "module.exports"],
"node/file-extension-in-import": ["error", "always"],
"node/prefer-global/buffer": ["error", "always"],
"node/prefer-global/console": ["error", "always"],
"node/prefer-global/process": ["error", "always"],
"node/prefer-global/url-search-params": ["error", "always"],
"node/prefer-global/url": ["error", "always"],
"node/prefer-promises/dns": "error",
"node/prefer-promises/fs": "error"
}
}
A response header is an HTTP header that can be used in an HTTP response and that doesn’t relate to the content of the message. Response headers, like Age, Location, or Server are used to give a more detailed context of the response. Not all headers appearing in response are categorized as response headers by the specification. For example, the Content-Type header is a representation header indicating the original type of data in the body of the response message (prior to the encoding in the Content-Encoding representation header being applied). However, “conversationally” all headers are usually referred to as response headers in a response message.
Helmet. js is a useful Node. js module that helps you secure HTTP headers returned by your Express apps. … The headers provide important metadata about the HTTP request or response so the client (browser) and server can send additional information in a transaction.
const express = require("express");const helmet = require("helmet");const app = express();app.use(helmet());// ...