Pregunta

I'm using Node.js and Underscore.js. I can't determine whether to escape JSON data on server side or client side. For underscore doesn't auto escape interpolated values with syntax <%= someValue %> but with <%- someValue %>, which is in the contrast to EJS and may causes confusion. There was a issue on GitHub and also a commit of auto-escape version. But a comment beneath the issue said:

I'm of the general philosophy that escaping should be done closer to your data than in the templating language

So, any suggestion that when to do HTML escape to AJAX data is better? Here's the server side helper function I have been using:

var htmlEscape = function(html){
    return String(html)
    .replace(/&(?!\w+;)/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
};
var xss = function(obj) {
    if (obj instanceof Array) {
        for (var i = 0; i < obj.length; i++) {
            obj[i] = xss(obj[i]);
        }
    } else {
        for(var key in obj) {
            // key != '_id' for mongoose doc
            if(obj[key] instanceof Object && !(obj[key] instanceof String) 
                && !(obj[key] instanceof Function) && key != '_id') {
                obj[key] = xss(obj[key]);
            } else if (obj[key] instanceof String || typeof(obj[key]) == "string") {
                obj[key] = htmlEscape(obj[key]);
            } else {
                obj[key] = obj[key];
            }
        }
    }
    return obj;
};

Then call it whenever return a JSON:

res.json(xss(someData));
¿Fue útil?

Solución

It is always better to perform sanitization/escape operations on the server since anyone can mess with your client side code and send the data any way they want.

There is a great node.js module, node-validator, which has an xss() function as well as a bunch other functions to validate/sanitize your data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top