Working with XSS Protection

1. Understanding XSS Attack Vectors

TypeDetail
StoredMalicious script saved to DB, served to others
ReflectedFrom URL/form, immediately echoed
DOM-basedClient-side sink (innerHTML, eval)
Mutation (mXSS)Sanitized HTML mutated by browser into XSS

2. Implementing Input Validation

PracticeDetail
AllowlistSpecific patterns (email regex, UUID)
Length capReject oversized input early
Type checkUse schemas (Zod, Joi, Pydantic)
Not enough aloneOutput encoding still required

3. Using Output Encoding

ContextEncoding
HTML body& < > " ' → entities
HTML attributeAll non-alphanumeric → &#x..;
JS string\xHH escaping
URLpercent-encoding
CSS\HH escaping

Prevents document.cookie read — XSS cannot exfiltrate session.

5. Using Content Security Policy

Example: Strict CSP

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-rAnd0m';
  style-src 'self' 'nonce-rAnd0m';
  img-src 'self' data: https:;
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'none';
  require-trusted-types-for 'script';

6. Implementing X-XSS-Protection Header

Deprecated: X-XSS-Protection. Modern browsers ignore. Use strict CSP instead.

7. Handling DOM-Based XSS

SinkSafer Alternative
innerHTMLtextContent / Trusted Types
eval / FunctionAvoid; use JSON.parse
document.writeAvoid entirely
setTimeout(string)setTimeout(fn)

8. Implementing Sanitization Libraries

LibraryUse
DOMPurifyBrowser/Node HTML sanitization (de-facto standard)
sanitize-htmlNode, configurable allowlist
OWASP Java HTML SanitizerJava
bleachPython

9. Using Trusted Types

Example: Enforce Trusted Types

// CSP: require-trusted-types-for 'script'
const policy = trustedTypes.createPolicy("default", {
  createHTML: s => DOMPurify.sanitize(s)
});
el.innerHTML = policy.createHTML(userInput);   // raw string would throw
CHROMIUM — Firefox/Safari still partial.

10. Implementing Context-Aware Encoding

FrameworkDetail
ReactJSX auto-encodes; only dangerouslySetInnerHTML is risky
Vue{{ }} safe; v-html risky
AngularAuto-sanitization with DomSanitizer
TemplatesUse auto-escaping engines (Twig, Jinja, Handlebars)