Do you guys know of a solid libra开发者_运维问答ry/function in Javascript to clean user input.
Mainly for preventing XSS attacks and the sort.
It would be a plus if the said library had the option of allowing certain tags etc.
EDIT: I'm using node.js on the backend. That's why I need a javascript library for that sort of thing.
People are recommending a part of Google Caja here: Preventing XSS in Node.js / server side javascript
But I was just hoping to get more options.
I use node-validator by chriso.
Example
var check = require('validator').check,
sanitize = require('validator').sanitize
// Validate
check('test@email.com').len(6, 64).isEmail(); //Methods are chainable
check('abc').isInt(); //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt(); //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);
// Sanitize / Filter
var int = sanitize('0123').toInt(); //123
var bool = sanitize('true').toBoolean(); //true
var str = sanitize(' \s\t\r hello \n').trim(); //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a'); //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode(); //'<a>'
This is the equivalent of the PHP strip_tags
function in Javascript. phpjs.org comes in handy for this kind of situations.
http://phpjs.org/functions/strip_tags:535
For this purpose I use DOMPurify
, it is good enough and fast library. The examples below from official documentation.
DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abc<iframe/\/src=jAva	script:alert(3)>def'); // becomes <p>abcdef</p>
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><li><a href="//google.com">click</a></li></ul>
You can find more by following this URL.
精彩评论