0

It seems like this is a solved problem in older frameworks (Django, Rails), but I can't for the life of me find a solution in Express.

A super common pattern in one-page webapps is to use template data to create html and then echo the same data as JSON to the client so that it can maintain state.

each comment as comments
  div= comment

script.
  var comments = !{JSON.stringify(comments)}

Obviously this isn't safe because a user could easily create a comment that closes the script tag and performs all kinds of nastiness. What's the proper way to deal with this then?

I've seen people claim you can get by with just

JSON.stringify(comments).replace(/<\//g, '<\/')

but that seems naive especially when working with large, forgetful teams.

Similarly, I wrote a function that html escapes recursively before stringifying, but replacing " with &quot; in every string seems like overkill and bad for data binding.

EDIT

For reference, here's Django's solution https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

Kyle
  • 1,434
  • 1
  • 11
  • 14

1 Answers1

0

If I understand you correctly, you're asking how one might sanitize user input to prevent content injection attacks, XSS, etc.

There are at least three existing Express middleware packages you can take a look at for this sort of thing. express-validator has some sanitization features. It in turn uses node-validator. The current version of node-validator does not do XSS sanitization, so see express-sanitizer below.

The much-beloved helmet middleware has some XSS protection stuff that might meet some or all of your needs. If you are writing an Express app and at all concerned about security, you should definitely checkout helmet if you don't already know about it.

There is an Express middleware modulecalled express-sanitizer. It appears to be recent and only have one contributor, so check the code to see if it meets your needs and seems mature. But it is trying to do XSS sanitization now that node-validator does not do that anymore. (See express-validator above.)

Trott
  • 66,479
  • 23
  • 173
  • 212
  • Hey thanks! In our case, we'd like to accept any arbitrary string as input so I'd rather escape the output than sanitize the input. A post could consist of a code example and very well contain a well-intentioned instance of "". Django's solution, which I'll link above, is https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs . Seems like express-sanitizer could accomplish this, but I'll have to read up on Caja. – Kyle May 05 '15 at 22:11
  • Sounds like you might want to check out this answer to another question: http://stackoverflow.com/a/7124052/436641 – Trott May 06 '15 at 00:11
  • Looks like that answer gives a replacement for "escape" rather than "escapejs". I might just look at the code and replicate it in JS if I can. – Kyle May 06 '15 at 21:33