Share 7 security-related JS libraries to make your application more secure

be02b3e4b1260121645efd7dbe14efd9.jpeg

In the world of JavaScript development, security is paramount in protecting applications from potential threats and vulnerabilities. Fortunately, the open source community has contributed a variety of powerful security libraries that can strengthen the security of JavaScript projects. In this article, we'll explore 7 essential JavaScript security libraries, all of which can be found on GitHub.

1. DOMPurify

8ef5a74bf113d5e573d94c9fb7880353.jpeg

This is one of the most starred repositories on GitHub with over 11k stars. This is a powerful library that provides safe and reliable HTML filtering. It helps prevent cross-site scripting attacks (XSS attacks) by filtering untrusted HTML and protecting applications from malicious user input.

Using DOMPurify is very simple and can be achieved with the following steps:

1. Install DOMPurify library

The DOMPurify library can be installed through npm, the command is as follows:

npm install dompurify

2. Import DOMPurify library

In the file that needs to use DOMPurify, import the DOMPurify library, the code is as follows:

import DOMPurify from 'dompurify';

3. Use DOMPurify to filter HTML

It is very simple to use the DOMPurify library to filter HTML. You can directly call the DOMPurify.sanitize() method and pass in the HTML string to be filtered as a parameter. The code example is as follows:

const dirtyHtml = '<script>alert("XSS Attack!");</script>';
const cleanHtml = DOMPurify.sanitize(dirtyHtml);
console.log(cleanHtml); // 输出:<span>alert("XSS Attack!");</span>

The above code will filter out the XSS attack code in `dirtyHtml`, and only keep safe HTML tags and content.

In addition, DOMPurify also provides some advanced usage, such as configuration options, custom strategies, etc. For details, please refer to the official documentation of DOMPurify.

https://github.com/cure53/DOMPurify

2. Helmet

c04099c226daecabd2f5380034a6647a.jpeg

helmet is a library for securing Express.js applications that helps you increase application security by setting HTTP headers. It prevents some common web security vulnerabilities such as cross-site scripting (XSS), clickjacking, content sniffing, and more. The following is the usage and code example of the helmet library:

1. First, you need to install the helmet library in your Express.js project, you can use the following command:

npm install helmet

2. In your Express.js application, import helmet and apply it to your application:

const express = require('express');
const helmet = require('helmet');

const app = express();

// 使用 helmet 中间件来增加安全性的 HTTP 头部
app.use(helmet());

// ...其他中间件和路由的设置...

// 启动服务器
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

By using helmet in your application, it automatically sets a series of HTTP headers, thereby enhancing the security of your application. Here are some sample settings:

Prevent Cross-Site Scripting (XSS):

The helmet sets the X-XSS-Protection header to help prevent the browser from executing maliciously injected scripts.

Disable sniffing of MIME types:

The helmet will set the X-Content-Type-Options header to prevent browsers from sniffing MIME types.

Clickjacking is prohibited:

The helmet will set the X-Frame-Options header to prevent the page from being nested in an iframe, thereby reducing the risk of clickjacking.

Set a secure transport policy:

The helmet will set the Strict-Transport-Security header to enforce the use of HTTPS to protect the transmission of sensitive data.

These are just some of the security enhancements that helmet can automatically set up for you. By using a helmet, you can easily increase the security of your Express.js application without manually writing a lot of security-related code.

https://github.com/helmetjs/helmet

3. Bcrypt

c12843ba207dfeda66d342e00d1aba86.jpeg

This is a library for secure password hashing in Node.js applications. It uses the bcrypt algorithm, which is designed to protect user passwords from unauthorized access. It has over 7k stars on GitHub.

The following is the usage of the bcrypt library and related code samples:

1. First, you need to install the bcrypt library in your Node.js project, you can use the following command:

npm install bcrypt

2. In your Node.js application, import bcrypt and use it for password hashing:

const bcrypt = require('bcrypt');
const saltRounds = 10; // 这是生成 salt 的轮数,可以根据需求进行调整

// 要哈希的原始密码
const plainPassword = 'mySecurePassword';

// 生成 salt,并使用 salt 对密码进行哈希
bcrypt.genSalt(saltRounds, (err, salt) => {
  if (err) throw err;
  bcrypt.hash(plainPassword, salt, (err, hash) => {
    if (err) throw err;

    // 此处的 hash 就是哈希后的密码,可以保存到数据库中
    console.log('Hashed Password:', hash);

    // 可以在这里进行密码校验
    bcrypt.compare(plainPassword, hash, (err, result) => {
      if (err) throw err;

      if (result) {
        console.log('Password is correct.');
      } else {
        console.log('Password is incorrect.');
      }
    });
  });
});

In this example, first we use the bcrypt.genSalt() function to generate a salt, and then use the bcrypt.hash() function to hash the original password and the salt to generate the final hashed password. You can save this hashed password to your database.

When a user logs in, you can use the bcrypt.compare() function to compare the password entered by the user with the hashed password in the database for password verification.

https://github.com/kelektiv/node.bcrypt.js

4、jsrsSsign

20bfd65ccfe4b984a4cacc08c4fb4517.jpeg

This library implements various cryptographic standards and algorithms such as RSA, HMAC, and X.509 certificates. It is useful when dealing with digital signatures and certificate-related tasks, especially for web applications. Gained over 3k stars on GitHub.

In today's digital age, data security is paramount. To ensure the confidentiality, integrity, and reliability of user data, developers need to take various measures to address security challenges. In this context, jsrsasign (RSA-Sign JavaScript Library) came into being as a powerful TypeScript/JavaScript library that supports RSA/RSAPSS/ECDSA/DSA signature/verification, ASN.1, PKCS#1/5/8 A series of cryptographic functions such as private key/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES JSON Web Signature/Token/Key, etc., fully help developers protect applications from various potential security threats.

You can install via Node NPM or Bower, or load libraries from several CDN sites. Here is a simple starter example showing how to load an encrypted PKCS#5 private key and sign:

// 导入 jsrsasign
var jsrsasign = require('jsrsasign');
var jsrsasignUtil = require('jsrsasign-util');

// 读取加密的私钥文件
var pem = jsrsasignUtil.readFile('z1.prv.p5e.pem');
var prvKey = jsrsasign.KEYUTIL.getKey(pem, 'passwd');

// 使用私钥对字符串 'aaa' 进行签名
var sig = new jsrsasign.Signature({ alg: 'SHA1withRSA' });
sig.init(prvKey);
sig.updateString('aaa');
var sigVal = sig.sign();

console.log('Signature:', sigVal);

jsrsasign provides powerful and flexible cryptography functions to help developers implement data security and authentication in applications. Its versatility, ease of use, and long-term maintenance make it a powerful tool for protecting sensitive information and preventing security threats. By knowing and mastering this library, developers can gain confidence in tackling various security challenges.

https://github.com/kjur/jsrsasign

5. QS

d70d0ed14b3ca46e39235226687a3d91.jpeg

This library will help you parse and serialize query strings in JavaScript. It helps prevent HTTP parameter pollution (HPP) attacks by properly handling query parameters and avoiding common parsing vulnerabilities. Has gained more than 7.5k stars on GitHub. The following is the usage of the qs library and related code samples:

First, install the qs library in your project, you can use the following command:

npm install qs

In your JavaScript code, you can import qs and start using it to parse and serialize query strings:

const qs = require('qs');

// 解析查询字符串
const queryString = 'name=John&age=30&city=New%20York';
const parsed = qs.parse(queryString);

console.log('Parsed Query:', parsed);

// 将对象序列化为查询字符串
const obj = {
  name: 'Alice',
  age: 25,
  city: 'Los Angeles'
};

const serialized = qs.stringify(obj);

console.log('Serialized Query:', serialized);

In this example, we first use qs.parse() to parse the query string, converting it into an object. We then serialize an object into a query string using qs.stringify().

qs also provides some other options and functions, such as handling of nested objects, handling of arrays, date formatting, etc. You can consult the documentation of the qs library for more details and usage examples:

https://github.com/ljharb/qs

6. Express rate limit

ed0b273301e065c1b397639f738d04ec.jpeg

This is an important middleware in an Express.js application. It helps mitigate denial of service (DoS) and brute force attacks by setting request rate limits on API endpoints. Has over 2.5k stars on GitHub. The following is
the usage and related code samples of node-rate-limiter-flexible library:

  1. First, install the node-rate-limiter-flexible library in your project, you can use the following command:

npm i --save rate-limiter-flexible
  1. In your Node.js application, import node-rate-limiter-flexible and use it to set a request rate limit:

const { RateLimiterMemory } = require('rate-limiter-flexible');

// 创建一个请求速率限制器
const rateLimiter = new RateLimiterMemory({
  points: 5, // 每秒允许的请求次数
  duration: 1 // 以秒为单位的时间窗口
});

// 在 Express.js 应用程序中使用请求速率限制器中间件
app.use((req, res, next) => {
  rateLimiter.consume(req.ip) // 使用客户端 IP 地址进行限制
    .then(() => {
      next();
    })
    .catch((err) => {
      res.status(429).send('Too Many Requests');
    });
});

// ...其他中间件和路由的设置...

// 启动服务器
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

In this example we create a request rate limiter using RateLimiterMemory. By setting the points and duration parameters, we can define the number of requests allowed per second and the time window. Then, we use middleware in the Express.js application to apply a request rate limiter, using the client's IP address for throttling. If the client exceeds the limit, it will receive a 429 Too Many Requests response.

node-rate-limiter-flexible also provides other limit policies, storage adapters and configuration options that you can adjust according to your needs. Detailed documentation can be found on the GitHub page of the library: https://github.com/animir/node-rate-limiter-flexible

https://github.com/animir/node-rate-limiter-flexible

7. jsSHA

d06794aae4eb53034bd9d8141efbc3e0.jpeg

This is a powerful TypeScript/JavaScript library for hashing data using various cryptography algorithms. It allows you to generate secure hashes for sensitive data, ensuring data integrity and authenticity. Got over 2k stars on GitHub. The following is the usage of the jsSHA library and related code samples:

  1. First, install the jsSHA library in your project, you can use the following command:

npm install jssha
  1. In your JavaScript code, you can import jsSHA and use it for data hashing:

javascriptCopy codeconst jsSHA = require('jssha');

// 创建一个 SHA-256 哈希对象
const shaObj = new jsSHA('SHA-256', 'TEXT');

// 要哈希的数据
const data = 'Hello, world!';

// 更新哈希对象的输入
shaObj.update(data);

// 获取最终的哈希值(十六进制表示)
const hash = shaObj.getHash('HEX');

console.log('Hash:', hash);

In this example, we first create a SHA-256 hash object, then use the update() method to update the input data, and finally use the getHash() method to get the final hash value.

jsSHA supports multiple encryption algorithms, you can specify the desired algorithm when creating a hash object, such as 'SHA-1', 'SHA-256', 'SHA-512', etc.

Note that jsSHA also provides many other options and features, such as HMAC calculations, handling binary data, etc. You can consult the documentation of the jsSHA library for more details and usage examples: https://caligatio.github.io/jsSHA/

Overall, jsSHA is a handy library that can be used to generate secure hashes of data in the browser and in Node.js to ensure data integrity and authentication.

https://github.com/Caligatio/jsSHA

Finish

In today's digital age, security has become increasingly important in application development. To ensure the confidentiality, integrity, and reliability of user data, developers need to take various measures to address security challenges. In this article, we've introduced seven security-related JavaScript libraries that provide developers with powerful tools to protect applications from a variety of potential security threats.

During your development journey, these libraries will act as a powerful shield, protecting your application from malicious behavior. At the same time, as technology continues to advance, we also encourage you to remain vigilant and keep abreast of the latest security standards and best practices to ensure your applications remain secure. If you have other great JavaScript library recommendations, please share them with us in the comments.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of the article is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132288318