TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › XSS Defences: Encoding, Sanitisation, CSP and Trusted Types

XSS Defences: Encoding, Sanitisation, CSP and Trusted Types

The two previous lessons showed XSS arriving through the server and through the DOM. The defences come in layers, and each layer catches what the one before misses. Encoding makes data display as text in the context where it lands. Sanitisation keeps the harmless part of HTML that users are allowed to submit (bold text, links) and removes the rest. CSP stops injected script from running even when the first two fail. Trusted Types make the dangerous sinks themselves refuse plain strings, so a forgotten innerHTML becomes a visible error instead of a vulnerability. This lesson builds a small allow-list sanitizer to see how sanitisers think, then turns on Trusted Types in a sandboxed frame.

Definitions

  • Encoding (escaping): context-specific transformation so data can't change structure. HTML text and attributes: &<>"'; URLs: percent-encoding plus scheme checks; JavaScript strings: \uXXXX; CSS: \XX. Template engines with auto-escaping do HTML for you.
  • Sanitisation: parsing untrusted HTML and keeping only allow-listed elements and attributes (and safe URL schemes). Must use the browser's own parser, because sanitisers that use regular expressions disagree with browsers about what the markup means.
  • DOMPurify: the widely used client-side sanitizer (also runs on the server with jsdom). The HTML Sanitizer API (setHTML, Sanitizer) is the standardised built-in equivalent: Firefox shipped setHTML() in version 148 (February 2026) and web.dev lists Chrome 146; check current support, Safari's in particular, before relying on it.
  • Trusted Types: with the CSP directive require-trusted-types-for 'script', HTML, script and script-URL sinks accept only typed objects (TrustedHTML, TrustedScript, TrustedScriptURL) produced by named policies; plain strings throw a TypeError. trusted-types <names> limits which policies may exist.

Which defence for which feature

Feature Defence
show a user's name, comment, search term encoding (or textContent); nothing else needed
let users write formatted text Markdown rendered to HTML, then sanitised; or a sanitizer on submitted HTML
user-supplied links scheme allow-list (http, https, mailto), rel="noopener noreferrer"
user-uploaded HTML/SVG files serve from a separate origin with Content-Disposition: attachment and nosniff; never inline
everything CSP with nonces, Trusted Types, HttpOnly cookies

An allow-list sanitizer, to see how they work

Real projects should use DOMPurify or the Sanitizer API, not this code. But a minimal allow-list sanitizer shows the principles: parse with the browser's parser into an inert document (a <template>, where nothing loads or runs), walk the tree, keep only known elements and attributes, check URLs, and serialise the result.

html · try it yourself
<!doctype html>
<style>body{font:14px system-ui;margin:8px} .out{border:1px solid #999;padding:6px;margin:4px 0} pre{background:#8881;padding:6px;white-space:pre-wrap}</style>
<div id="results"></div>
<pre id="log"></pre>
<script>
  const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
  window.probe = (n) => log('PAYLOAD RAN: ' + n);
  const ALLOWED = { B: [], I: [], EM: [], STRONG: [], P: [], UL: [], LI: [], A: ['href', 'title'], CODE: [] };

  function sanitize(dirty) {
    const t = document.createElement('template');
    t.innerHTML = dirty;                                 // parsed, but inert: no loads, no handlers
    const walk = (node) => {
      for (const el of [...node.children]) {
        if (!(el.tagName in ALLOWED)) {                  // unknown element: replace it by its plain text
          const keepText = !['SCRIPT', 'STYLE', 'TEMPLATE'].includes(el.tagName);
          el.replaceWith(keepText ? document.createTextNode(el.textContent) : '');
          continue;
        }
        for (const attr of [...el.attributes]) {
          const keep = ALLOWED[el.tagName].includes(attr.name) &&
            (attr.name !== 'href' || /^(https?:|mailto:)/.test(new URL(attr.value, 'https://shop.lab.test/').protocol));
          if (!keep) el.removeAttribute(attr.name);
        }
        if (el.tagName === 'A') el.setAttribute('rel', 'noopener noreferrer');
        walk(el);
      }
    };
    walk(t.content);
    return t.innerHTML;
  }

  const inputs = [
    'Great <b>tea</b>, see <a href="https://blog.lab.test/t">my review</a>',
    '<img src=x onerror="probe(1)">picture',
    '<a href="javascript:probe(2)">click</a>',
    '<p onclick="probe(3)">hi <script>probe(4)<\/script></p>',
    '<svg><g onload="probe(5)"></g></svg>svg',
    '<b><i>nested</i></b><iframe srcdoc="<script>probe(6)<\/script>"></iframe>',
  ];
  for (const dirty of inputs) {
    const clean = sanitize(dirty);
    const div = document.createElement('div');
    div.className = 'out';
    div.innerHTML = clean;                               // safe only because clean is sanitised
    document.getElementById('results').append(div);
    log(clean);
  }
  setTimeout(() => log('done; any "PAYLOAD RAN" line above would be a sanitizer bug'), 300);
</script>

The formatted review keeps its bold text and link (with rel added). The image, the javascript: link target, the onclick, the <script>, the SVG and the <iframe srcdoc> are gone, and no payload ran. The first draft of this sanitizer had a bug worth knowing: it unwrapped unknown elements by moving their children up without checking them, so <svg><g onload=…> left a <g> with its handler in the output. Replacing an unknown element by its plain text closes that hole. Writing a sanitizer is easy; writing it completely is not: real sanitizers also handle namespace confusion between HTML, SVG and MathML, mutation XSS (markup that changes meaning when serialised and re-parsed), DOM clobbering through id/name attributes, and CSS. That is why you use a maintained library and keep it up to date.

Trusted Types: making the sink refuse strings

With Trusted Types enforced, el.innerHTML = string throws. The only way to write HTML is through a policy, which is one small, reviewable place in the code base; every other innerHTML in the application, including in third-party libraries, either goes through it or fails loudly.

html · try it yourself
<!doctype html>
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types comments">
<style>body{font:14px system-ui;margin:8px} pre{background:#8881;padding:6px}</style>
<div id="box"></div>
<pre id="log"></pre>
<script>
  const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
  const untrusted = 'Hi <img src=x onerror="document.title=\'pwned\'">';
  if (!window.trustedTypes) {
    log('This browser has no Trusted Types support; the policy is ignored here.');
  } else {
    try {
      document.getElementById('box').innerHTML = untrusted;          // a forgotten unsafe sink
      log('plain string accepted (unexpected)');
    } catch (e) {
      log('plain string refused: ' + e.name);
    }
    const policy = trustedTypes.createPolicy('comments', {
      createHTML: (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`),   // encode (or call DOMPurify here)
    });
    document.getElementById('box').innerHTML = policy.createHTML(untrusted);
    log('through the policy: ' + document.getElementById('box').textContent);
    try {
      trustedTypes.createPolicy('other', { createHTML: (s) => s });
    } catch (e) {
      log('second policy "other" refused: ' + e.name);
    }
  }
</script>

In Chromium-based browsers (and others that ship Trusted Types) you should see the plain string refused with a TypeError, the comment shown as text through the comments policy, and an attempt to create an unlisted, permissive policy refused too. The policy here encodes; a policy for rich text would call DOMPurify with RETURN_TRUSTED_TYPE: true.

How XSS defences are verified (detection)

  • Encoding: review templates for raw-output markers and string-built HTML; test every output context with a marker ('"<b>m</b>).
  • Sanitizer: check the library version against its advisories (DOMPurify has had bypasses fixed over the years); check it runs after any transformation (Markdown → HTML → sanitise, never the reverse) and that its output isn't modified afterwards.
  • CSP and Trusted Types: deploy Content-Security-Policy-Report-Only: require-trusted-types-for 'script' first; the violation reports list every sink that still receives strings. Enforce when the reports are quiet.
  • Regression tests: a list of known payloads through every rendering path, asserting that the output contains no executable markup (a headless browser can check that no handler ran, as the demos here do).

Pitfalls

  • Sanitising, then changing the HTML (string replacement, re-parsing in another context) can reintroduce markup.
  • Server-side sanitisers with a different parser from the browser's: their idea of the tree may not be the browser's.
  • A policy that returns its input unchanged (createHTML: s => s) defeats Trusted Types; restrict policy names with trusted-types and review the policies.

Practice

1. A forum renders Markdown to HTML on the server, sanitises it, then runs a "link-ifier" that turns bare URLs into <a> tags with string replacement. What is wrong?

The link-ifier runs after the sanitizer and builds HTML from strings, so a crafted URL (with quotes or javascript:) can inject markup. Link-ify before sanitising, or build links with DOM APIs and check the scheme.

2. Your Trusted Types report-only policy reports violations from a third-party analytics library calling document.write. Options?

Update or replace the library, load it in a sandboxed iframe, or create a narrowly scoped policy for it after reviewing what it writes. Don't enforce until it is handled, or the library will break.

Test yourself

When is sanitisation (rather than encoding) the right defence?

  1. Always
  2. When users are allowed to submit some HTML, such as formatted text
  3. For numbers
  4. For URLs only

Why did the example sanitizer parse into a <template>?

  1. Templates are faster
  2. Content in a template is inert: nothing loads and no handlers run while it is inspected
  3. Templates remove scripts automatically
  4. It is required by CSP

What does require-trusted-types-for 'script' change?

  1. Blocks all scripts
  2. HTML and script sinks such as innerHTML refuse plain strings and accept only values from Trusted Types policies
  3. Requires HTTPS
  4. Enables eval

Why use DOMPurify instead of your own sanitizer in production?

  1. It is smaller
  2. Complete sanitising must handle mutation XSS, SVG/MathML namespaces, DOM clobbering and more; a maintained library tracks the bypasses
  3. Browsers require it
  4. It encrypts HTML