XSS in the Modern Era: Bypassing CSP and DOMPurify Configurations
When outdated sanitizers and misconfigured CSP script hashes leave gaps, even modern web applications can become vulnerable to Cross-Site Scripting (XSS). Frameworks such as React, Vue, and Angular provide useful securit
When outdated sanitizers and misconfigured CSP script hashes leave gaps, even modern web applications can become vulnerable to Cross-Site Scripting (XSS). Frameworks such as React, Vue, and Angular provide useful security protections, but they cannot automatically secure every interaction between user input, JavaScript, and the browser DOM.
Modern applications frequently process dynamic content, API responses, URL parameters, and user-generated HTML. If these inputs reach unsafe DOM methods, attackers may find opportunities to execute unwanted scripts.
This guide explores how DOM-based XSS develops, why Content Security Policy (CSP) and DOMPurify configurations sometimes fail, and how developers can strengthen application security using safer DOM APIs, Trusted Types, and practical testing methods.
1. Understanding Modern XSS and DOM-Based Vulnerabilities
Cross-Site Scripting occurs when an application allows untrusted input to execute as browser-side code.
There are three common categories:
- Reflected XSS: Malicious input is included in an immediate server response.
- Stored XSS: Untrusted content is saved and displayed to other users.
- DOM-based XSS: Client-side JavaScript processes untrusted data and inserts it into an unsafe DOM location.
Single-page applications (SPAs) require particular attention because they frequently update page content without reloading the entire document.
Consider this vulnerable JavaScript implementation:
const params = new URLSearchParams(
window.location.search
);
const message = params.get("message");
document.querySelector("#output").innerHTML =
message || "";
The problem is the use of innerHTML. It interprets the supplied value as HTML instead of displaying it as ordinary text.
A safer implementation is:
const params = new URLSearchParams(
window.location.search
);
const message = params.get("message") || "";
document.querySelector("#output").textContent =
message;
Using textContent prevents the browser from interpreting the supplied value as HTML.
The main lesson is that developers should identify every location where external data enters the DOM.
2. How CSP Misconfigurations Create Security Gaps
Content Security Policy is a browser security mechanism that controls which resources can execute or load on a website.
A properly configured CSP can reduce the impact of XSS vulnerabilities by restricting unauthorized JavaScript execution.
However, weak policies may create unnecessary opportunities for script injection.
Common configuration problems include:
- Allowing
unsafe-inlinein script directives. - Allowing
unsafe-evalwithout a clear requirement. - Using broad script source allowlists.
- Reusing predictable CSP nonces.
- Forgetting to update script hashes after modifying inline scripts.
- Trusting third-party script loaders without reviewing their behavior.
A stronger policy can use nonces and additional restrictions.
Example CSP header:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{RANDOM_NONCE}';
object-src 'none';
base-uri 'none';
frame-ancestors 'self';
require-trusted-types-for 'script';
trusted-types app-sanitizer;
The nonce must be generated securely for each response and must match the nonce attached to authorized script elements.
For static pages, hash-based CSP policies can be useful. However, hashes must match the exact inline script content. Any modification requires recalculating the corresponding hash.
Developers should also understand that strict-dynamic transfers trust from a nonce- or hash-authorized script to scripts dynamically loaded by that trusted script. This makes the behavior of trusted script loaders especially important.
CSP is an additional security layer, not a replacement for fixing unsafe application code.
3. DOMPurify Configurations and Advanced Payload Handling
DOMPurify is a widely used HTML sanitization library. It removes unsafe HTML elements and attributes before content is inserted into the DOM.
However, using a sanitizer does not automatically guarantee application security.
Potential problems include:
- Running outdated DOMPurify versions.
- Modifying sanitized HTML afterward.
- Using unsafe configuration options.
- Allowing unnecessary HTML elements or attributes.
- Processing content differently across application components.
- Trusting sanitized output without checking the destination context.
Advanced XSS research also examines encoding differences, parser behavior, mutation-based XSS (mXSS), and script gadgets.
A script gadget is an existing piece of trusted application code that can unintentionally turn attacker-controlled data into executable behavior.
For example, an application may sanitize HTML correctly but later pass a value into an unsafe JavaScript function. This can undermine the original security protection.
A basic DOMPurify implementation:
npm install dompurify
import DOMPurify from "dompurify";
const untrustedContent =
"<p>Welcome to the application</p>";
const sanitizedContent =
DOMPurify.sanitize(untrustedContent);
document.querySelector("#content").innerHTML =
sanitizedContent;
For applications that need to render HTML, sanitization should happen immediately before the content reaches the HTML sink.
Avoid changing the sanitized output afterward.
The security team should also review sanitizer versions and configuration whenever application dependencies change.
4. Trusted Types Enforcement and Secure Implementation
Trusted Types provide an additional browser-level mechanism for controlling data passed into dangerous DOM injection points.
Instead of allowing arbitrary strings to reach HTML sinks, applications can require values created through approved Trusted Types policies.
This is particularly useful for large SPAs with multiple developers and shared UI components.
Example implementation using DOMPurify:
import DOMPurify from "dompurify";
const sanitizerPolicy =
window.trustedTypes.createPolicy(
"app-sanitizer",
{
createHTML: (input) =>
DOMPurify.sanitize(input, {
RETURN_TRUSTED_TYPE: false
})
}
);
const untrustedContent =
"<p>Approved sample content</p>";
const safeHTML =
sanitizerPolicy.createHTML(untrustedContent);
document.querySelector("#content").innerHTML =
safeHTML;
The RETURN_TRUSTED_TYPE: false option ensures DOMPurify returns a string to the Trusted Types policy, which then creates the TrustedHTML value.
A matching CSP directive can enforce Trusted Types:
Content-Security-Policy:
require-trusted-types-for 'script';
trusted-types app-sanitizer;
This restricts direct assignment of ordinary strings to protected DOM injection sinks in supporting browsers.
An important distinction: Trusted Types do not sanitize content by themselves. The security of the implementation depends on the transformation function used by the approved policy.
5. CLI Testing, Remediation, and Security Checklist
A controlled local environment is useful for identifying DOM-based XSS risks without testing against production users or third-party websites.
Step 1: Create a local project.
mkdir modern-xss-lab
cd modern-xss-lab
npm init -y
npm install dompurify
Step 2: Inspect installed dependencies.
npm list dompurify
npm audit
npm audit --omit=dev
These commands help identify installed versions and reported dependency vulnerabilities. Review the audit output before applying upgrades.
Step 3: Check HTTP security headers.
curl -sSI https://hackmywebsite.io
Review the response for:
- Content-Security-Policy
- Strict-Transport-Security
- X-Content-Type-Options
- X-Frame-Options
- Referrer-Policy
Step 4: Review unsafe JavaScript patterns.
grep -RInE \
'innerHTML|outerHTML|document.write|eval\(' \
src/
This is a basic source-code search, not a complete security scanner. Each match requires manual review.
Step 5: Validate the remediation.
| Security test | Expected result |
|---|---|
| Plain text rendering | Input displayed as text |
| HTML sanitization | Disallowed elements removed |
| CSP validation | Unauthorized scripts blocked |
| Trusted Types | Untrusted strings rejected at protected sinks |
| Dependency audit | Known vulnerabilities reviewed |
| DOM review | Unsafe injection paths remediated |
For production applications, CSP should initially be monitored using Content-Security-Policy-Report-Only before switching to enforcement. This helps identify legitimate application resources that may be affected by the new policy.
The final security review should also include OWASP XSS Prevention guidance and a manual review of application-specific DOM manipulation.
Conclusion
Modern XSS prevention requires more than installing a security library or adding a CSP header. It requires understanding how data travels through an application and identifying where that data reaches browser execution contexts.
DOMPurify, strict CSP policies, safe DOM APIs, and Trusted Types work best as complementary defenses. Regular dependency updates and security testing help ensure that these protections remain effective as applications evolve.
For developers building modern web applications, identifying and fixing these weaknesses early can significantly reduce application security risks.
Explore application security testing with Hack My Website:
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.