I am working on some one page apps coded in JavaScript that currently use lodash. I would like to prevent Cross Site Scripting (XSS) using a standard library by:
1) Escaping all untrusted content
2) Encoding output depending on its destination CSS, HTML, HTMLAttribute JavaScript, JSON etc
I have seen a number of stack overflow answers but they don't provide a complete canonicalization / encoding solution in a standard library that I can write static test to make sure developers are using the library.
Is there an esapi or similar "light" library that I can use just for JavaScript?
I have seen the OWASP Esapi and the jQuery Encoder Plugin https://github.com/chrisisbeef/jquery-encoder and the SalesForce Encoder https://github.com/salesforce/secure-filters
At this moment I'm only interested canonicalizing input and encoding output. I'm also looking for something current, well maintained and ideally not dependent on other libraries.
Can anyone suggest the best approach to use?
Are any templating frameworks in use? Ideally you should use a framework like React which handles the encoding by default. Then all you would have to do, is to make sure dagerouslySetInnerHTML is not used (or used safely).
Adding untrusted CSS is considered unsafe unless whitelist validated. Adding untrusted data to tags, can be safely done by assigning the data to element.textContent or by using jQuery's $.text(). Adding untrusted data to HTML attributes that are not event handlers, can be done using element.setAttribute or $.attr(). For double contexts like inside script tags (javascript context inside html context) or javascript event handler attributes (javascript context inside html attribute context), you would have to make sure you encode for both.
For HTML content you can optionally use DOMPurify to remove any active content, but that's more valid if you need to allow untrusted HTML fragments.