Home > Net >  in node.js how to sanitize api requests that failed input validation for future security review
in node.js how to sanitize api requests that failed input validation for future security review

Time:11-14

I need to sanitize api requests that failed input validation for future security review. I have it in json format and I need to keep them in json format.

this is for example valid json but I can't log it to our system like that:

{
    "<script>alert('test!!!!');</script>": "<script>alert('xss12!!!!');</script>"
}

I need a lib or some way in node.js to sanitize it and keep it json and then log it, for example convert it to utf:

{
    "#utf3c#script#utf3c#alert('test#utf3c##utf3c##utf3c##utf3c#')#utf3c##utf3c##utf3c#script#utf3c#": "#utf3c#script#utf3c#alert('xss12#utf3c##utf3c##utf3c#')#utf3c##utf3c##utf3c#script#utf3c#"
}

I had the idea to convert it to string with JSON.stringify convert to codePointAt with this replacer with string replace and then convert back to json with JSON.parse but the string it generate can't be converted back to json easily, with complex nested json it breaks.

   function replacer(match, index, wholeString) {
        const result = "codePoint#"   wholeString.codePointAt(index);
        return result;
   }

   const dataToEncodeAsString = JSON.stringify(dataToEncode);
   const test = dataToEncodeAsString.replace(/[^a-zA-Z1-9:'" ]/g, replacer);
   console.log(test); 

CodePudding user response:

I found this package flat

and used it to flat the structure of the deeply nested JSON and then clean all chars from its keys and values and then used flat again with unflatten function to bring the JSON to its original structure.

hope it will help others that need this kind of solution!

  • Related