How to validate if a JavaScript library is secure?

To avoid client-side security issues, you need to learn about the security requirements for client-side code and the common mistakes. OWASP has good resources. Make sure you read about DOM-based XSS, as that is one of the most common security mistakes.

As far as security best practices, I have several suggestions:

  • To avoid XSS, abide by the rules found in Adam Barth on Three simple rules for building XSS-free web applications.

  • Avoid setInnerHtml() and .innerHtml =. Instead, use setInnerText() or DOM-based operations (to make sure you don't introduce script tags, i.e., to avoid DOM-based XSS). Avoid document.write().

  • Avoid eval(). Its use tends to be correlated to security flaws. Similarly, avoid other APIs that turn a string into code and execute it, like setTimeout() with a string argument, setInterval() with a string argument, or new Function().

  • Turn on Javascript "strict mode". It helps avoid some subtle areas of Javascript that have been responsible for security problems before.

  • Make sure your code is compatible with a strict Content Security Policy (here's a tutorial), such as script-src 'self'; object-src 'self'.

See also Security Concerns on clientside(Javascript), which is on a related topic.

I don't know of any static analysis tools to scan Javascript and look for security problems.

If you follow Doug Crockford's recommendations about how to use Javascript (e.g., as per his book, Javascript: The Good Parts), you could use JSLint. It's a pretty aggressive lint tool. If your code is JSLint-clean, that's a positive mark. But JSLint is not focused primarily on security. And, if you take legacy code and run JSLint on it, you're probably going to get inundated with a pile of warnings.


Standard practice is for your client to engage a security test, but I am seeing more developers hiring security testers to provide some assurance to the client.

But there is no way to say 'this code is guaranteed secure' - there is only 'this code seems appropriately secure' or 'fit for purpose'


I think what you want is fundamentally impossible - saying that a program does or doesn't do some (unspecified) thing malicious is equivalent to the halting problem. Especially consider that javascript is part of a complex ecosystem of interacting software. Exploits are not necessarily as simple as writing a function called steal_cookies_and_send_to_bad_guys.

So since it's impossible, the best you can do is have the code inspected by someone who ought to be able to spot some "known species" of malware, and perhaps form an opinion that it is otherwise above board and well written.