'Is there a way to use recursion to loop through form data and sanitize each input using DOMpurify?
For each of the forms in the portal, it need to ensure that the user input is “sanitized” to prevent Cross-Site Scripting (XSS) attacks. These attacks happen when user input includes malicious code (such as JS scripts) that may eventually be rendered, and therefore executed, on some interface of the portal which can have an effect on other users.
As you're looping over the data, you will come across nested objects and arrays that your logic must be able to detect and treat accordingly. When the loop gets to an object or array, you may likely have to use recursion to process it properly.
import DOMPurify from 'dompurify';
/**
* Sanitizes all fields in `data` against XSS attacks
* @param {*} data
* @returns `cleanData`
*
*/
const rawData = {
identity: {
name: {
first: 'John',
middle: '<script type="text/javascript">var test="https://www.sknvibes.com/example.php?cookie_data=" + escape(document.cookie);</script>',
last: 'Doe'
}
},
location: {
address: {
street: {
number: 311,
name: 'Franklin <script>alert(document.cookie)</script> Drive'
}
},
},
first: 'John',
middle: '<script type="text/javascript">var test="https://www.sknvibes.com/example.php?cookie_data=" + escape(document.cookie);</script>',
last: 'Doe',
jobTitle: "Software Dev<body onload=alert('something')>;eloper",
notificationPreferences: ['email', 'SMS', 'phone', '<img onerror="alert(\'Hacked!\');" src="invalid-image" />']
}
const sanitizeInput = (data) => {
const cleanData = {}
console.log("Before cleaning: ", data)
console.log("Before cleaning: ", rawData)
// loop over data and sanitize each field
// for (const property in data) {
// cleanData[property] = DOMPurify.sanitize(data[property], {USE_PROFILES: {html: false, svg: false}})
// // this logic needs to be improved to allow for deep iterations as well as treating complex objects appropriately
// sanitizeInput(rawData[rawData.identity])
// console.log("test:", rawData.identity)
// }
// for (const property in rawData.identity) {
// rawData[property] = DOMPurify.sanitize(rawData[property], {USE_PROFILES: {html: false, svg: false}})
// }
if (rawData) {
rawData[rawData] = DOMPurify.sanitize(rawData.identity, {USE_PROFILES: {html: false, svg: false}})
console.log("just a test: ",rawData.identity)
console.log("After cleaning1: ", rawData)
return
}
sanitizeInput(rawData[rawData.identity])
//console.log("After cleaning: ", cleanData)
return cleanData
}
export default sanitizeInput
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
