79572461

Date: 2025-04-14 06:23:05
Score: 0.5
Natty:
Report link

Try working with this -- it handles all data types and uses recursion to go arbitrarily deep into complex JS object structures. I got tired of looking for something which wasn't either a bloated library or too simple to deploy easily. Wanted to guard against folks poking holes in my SQL (I do use parameterization, but...), logging, server code, whatever. You can easily change the regexes, etc. to fit your needs. Just wrote it this afternoon, so would appreciate feedback if there are things I overlooked.

function sanitizeVar(jsVar, options = {}) {

    const type = typeofComplete(jsVar)

    if (type == 'object') 
        Object.keys(jsVar).forEach(key => { jsVar[key] = sanitizeElement(jsVar[key])})

    else if (type == 'array')
        for (let idx = 0; idx < jsVar.length; idx++) { jsVar[idx] = sanitizeElement(jsVar[idx]) }

    else // string, boolean, number, bigint, null, undefined, function, symbol
        jsVar = sanitizeElement(jsVar) 

    return jsVar // return mutated value -- end of main function

    /*
        helper functions -- keep in this scope
    */
    function typeofComplete(jsVar) { // what the native JS typeof should do...

        return jsVar == null ? 'null' : Array.isArray(jsVar) ? 'array' : typeof jsVar
    }

    function sanitizeElement(val) {

        const type = typeofComplete(val)

        if (type == 'string') return sanitizeString(val)

        // return back up to sanitizeVar(); will likely recurse back here...
        else if (['object', 'array'].includes(type)) return sanitizeVar(val) 

        else if (['boolean', 'number', 'bigint', 'null', 'undefined'].includes(type)) 
            return val // these are safe as they are

        else if (['function', 'symbol'].includes(type)) return null // never in a client request
    }

    function sanitizeString(str) { // sanitizing crux; add regex and options as needed

        // DIAG to make sure it's working:  str = str.replace(/\d/g, 'X')

        return str.replace(/[^\x00-\x7F]/g, '')                 // remove non-ASCII chars
            .replace(/[\\|`"';<>]/g, '')                        // remove \ | ` " ' ; < >
            .substring(0, options.max_str_length || undefined)  // undefined => no limit
    }
}

I know the question is super-old, but I ran across it before I gave up looking for a more robust light-weight solution. Another idea is to pass regex(es) in as part of options object arg.

Reasons:
  • Blacklisted phrase (1.5): would appreciate
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: monist