Skip to main content

Supported JavaScript cleansing functions

FunctionDocumentationFlaw class
DOMPurify.sanitizeDOMPurify on github.com, DOMPurify on owasp.orgCWE-80
encodeURIencodeURI on developer.mozilla.orgCWE-80, 93, 113, and 117
encodeURIComponentencodeURI on developer.mozilla.orgCWE-80, 93, 113, and 117
JSON.stringifyJSON.stringify on developer.mozilla.orgCWE-117
vcEncodeHtmlSee belowCWE-80

Preventing cross-site scripting with text nodes

Veracode Static Analysis automatically detects the proper use of text nodes, as described in MDN Web Docs:

Using text nodes automatically resolves cross-site scripting flaws (CWE-80). In addition to strict data validation, it is the best approach for cross-site scripting prevention in a browser context.

The following code example uses built-in browser web APIs to demonstrate proper usage of text nodes to protect your code from cross-site scripting attacks:

const response = await fetch("//reversegeocoding/lat/lon");
const json = await response.json();
const address = json.address;

// validation logic for address omitted, will be different depending on a region
if (isValidAddress(address) === true) {
const addressElement = document.getElementById("address-display");
// this snippet will be safe even in the the case that validation fails to protect from malicious data potentially embedded in the address
addressElement.textContent = address;
} else {
// log an error and setup alerting on the backend - a service may have been compromised!
}

A similar approach is available in libraries or frameworks like jQuery.

The vcEncodeHtml helper function

You can use a function similar to the following to pass data through a text node to force the browser to HTML encode.

const dangerousUserData = decodeURIComponent(window.location.hash.substring(1));
const safelyEncodedData = vcEncodeHtml(dangerousUserData);
const myHtml = `<p>${safelyEncodedData}</p>`;
document.write(myHtml);

/**
* Encode String to HTML encoded String.
*
* Use TextNode to let browser do encoding.
* Copied from: https://docs.veracode.com
* @param {string} value String to encode
* @returns {string} Encoded string
*/
function vcEncodeHtml(value) {
var text = document.createTextNode(value);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}

This function does not already exist, so you must copy it or implement a similar function. Veracode Static Analysis detects the technique regardless of what the function is named.