JAVASCRIPT
Sanitize HTML Input to Prevent XSS Attacks
Effectively prevent Cross-Site Scripting (XSS) vulnerabilities in your web applications by sanitizing untrusted HTML input using the robust DOMPurify library.
// Install: npm install dompurify jsdom
// Note: DOMPurify requires a DOM environment. For Node.js, JSDOM is used to simulate a browser environment.
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
// Create a JSDOM window object for DOMPurify to operate in
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
// Untrusted user input (e.g., from a rich text editor or comments)
const untrustedHTML = `
<img src="x" onerror="alert('XSS Attack!')">
<p>Hello, <script>alert('Another XSS!')</script> user!</p>
<a href="javascript:alert('Even more XSS!')">Click Me</a>
<iframe src="malicious.com"></iframe>
<p style="color:red;">This is fine.</p>
<div onmouseover="alert('Mouse over XSS!')">Hover here</div>
`;
console.log('Original HTML:
', untrustedHTML);
// Sanitize the HTML using DOMPurify
const cleanHTML = DOMPurify.sanitize(untrustedHTML, {
USE_PROFILES: { html: true }, // Ensure HTML profile is used
// FORBID_ATTR: ['style'], // Optional: disallow specific attributes like inline styles
// FORBID_TAGS: ['iframe', 'script'], // Optional: disallow specific tags
});
console.log('
--- Sanity Check ---
');
console.log('Clean HTML:
', cleanHTML);
// Example with custom options to allow certain attributes while forbidding others
const customOptionsHTML = `<p><a href="http://example.com" target="_blank">Safe Link</a><span onfocus="alert('Bad focus!')">Focus here</span></p>`;
const cleanWithOptions = DOMPurify.sanitize(customOptionsHTML, {
ADD_ATTR: ['target'], // Allow the 'target' attribute for 'a' tags
FORBID_TAGS: ['span'], // Disallow 'span' tags altogether
FORBID_ATTR: ['onfocus'] // Forbid the 'onfocus' attribute globally
});
console.log('
Clean HTML with custom options:
', cleanWithOptions);
How it works: This snippet illustrates how to effectively sanitize untrusted HTML input to prevent Cross-Site Scripting (XSS) vulnerabilities using the DOMPurify library. XSS attacks occur when an attacker injects malicious client-side scripts into web pages viewed by other users. DOMPurify works by parsing the HTML, removing any potentially dangerous elements, attributes, or protocols (like `javascript:` URLs), and returning a safe, clean HTML string. This is far more robust than regex-based sanitization, which is prone to bypasses, and can be configured with various options to control what is allowed or forbidden.