Preventing XSS in Node.js / server side javascript

Viewed 67042

Any idea how one would go about preventing XSS attacks on a node.js app? Any libs out there that handle removing javascript in hrefs, onclick attributes,etc. from POSTed data?

I don't want to have to write a regex for all that :)

Any suggestions?

9 Answers

All usual techniques apply to node.js output as well, which means:

  • Blacklists will not work.
  • You're not supposed to filter input in order to protect HTML output. It will not work or will work by needlessly malforming the data.
  • You're supposed to HTML-escape text in HTML output.

I'm not sure if node.js comes with some built-in for this, but something like that should do the job:

function htmlEscape(text) {
   return text.replace(/&/g, '&').
     replace(/</g, '&lt;').  // it's not neccessary to escape >
     replace(/"/g, '&quot;').
     replace(/'/g, '&#039;');
}

Try out the npm module strip-js. It performs the following actions:

  • Sanitizes HTML
  • Removes script tags
  • Removes attributes such as "onclick", "onerror", etc. which contain JavaScript code
  • Removes "href" attributes which contain JavaScript code

https://www.npmjs.com/package/strip-js

Update 2021-04-16: xss is a module used to filter input from users to prevent XSS attacks.

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.

Visit https://www.npmjs.com/package/xss
Project Homepage: http://jsxss.com

You should try library npm "insane". https://github.com/bevacqua/insane

I try in production, it works well. Size is very small (around ~3kb gzipped).

  • Sanitize html
  • Remove all attributes or tags who evaluate js
  • You can allow attributes or tags that you don't want sanitize

The documentation is very easy to read and understand. https://github.com/bevacqua/insane

Related