System Atlas
the atlas

Cross-site scripting (XSS)

Trick a trusted site into serving your JavaScript, and it runs with the victim's session.

the gist

XSS injects attacker-controlled script into a page so it executes in the victim's browser with the site's origin and cookies. It comes in three flavors — stored, reflected, and DOM-based — but the outcome is the same: the script can read sessions, forge requests, and impersonate the user. Defenses stack: encode output, ship a Content-Security-Policy, mark cookies HttpOnly, and validate input.

ANALOGY // It's like graffiti written in the museum's own official font on the official wall — visitors trust it because of where it appears, not because of who actually wrote it.
living diagram01 / 06
craftAttackerwrites scriptInject payload<script>…</script>App / DBstores or reflectsVictim browserloads trusted pageScript runsin site's originAttacker serverreceives sessionDefensesencode · CSP · HttpOnly
01

Craft the payload

The attacker writes a snippet of JavaScript designed to run in someone else's browser — for example a script that reads document.cookie and sends it to an attacker-controlled URL. The goal is to get this string treated as code rather than as text by a trusted site.

02

Find an injection vector

The attacker looks for input the site reflects back into a page without neutralizing it. Stored XSS saves the payload on the server (a comment or profile field); reflected XSS puts it in a URL parameter the page echoes; DOM-based XSS abuses client-side JS that writes untrusted input into the DOM.

03

Serve it to the victim

The victim loads a page from the site they trust, and the tainted content is delivered as part of that page. Because it arrives from the legitimate origin, the browser has no reason to treat the embedded script as anything other than the site's own code.

04

Script executes in-origin

The browser parses the injected <script> and runs it with the full privileges of the trusted site: same origin, same cookies, same access to the DOM and any tokens the page can reach. The same-origin policy that normally isolates sites offers no protection, because the code is running as the site.

05

Steal the session

The script reads the victim's session cookie or auth token and exfiltrates it to the attacker's server, or silently fires authenticated requests — changing a password, posting content, moving money — all indistinguishable from the real user. One view of a poisoned page is enough.

06

Layered defenses

You stop XSS by never letting input become code: escape/encode all output for its context, ship a Content-Security-Policy to block inline and foreign scripts, mark session cookies HttpOnly so script can't read them, and validate input at the edge. No single control is enough; they overlap on purpose.

the full picture
01

What XSS actually is

Cross-site scripting is an injection attack where an attacker gets their own JavaScript to run inside a page served by a site the victim trusts. The name is a little misleading — the interesting word is *scripting*, not *cross-site*. The essence is a confusion of code and data: the site meant to display some text (a username, a comment, a search term), but because that text wasn't neutralized, the browser interpreted part of it as executable script.

Why is that so dangerous? Because of the browser's trust model. A page's JavaScript runs with the authority of its origin — it can read that origin's cookies, its localStorage, its DOM, and it can make requests as the logged-in user. The same-origin policy is supposed to stop evil.com from touching bank.com's data. But XSS smuggles the attacker's code *into* bank.com's own pages, so it runs as bank.com with all of bank.com's privileges. The isolation boundary isn't broken; it's bypassed, because the malicious code is now on the trusted side of it.

02

The three types

XSS is usually classified by how the payload reaches the victim's browser.

  • Stored (persistent) XSS — the attacker submits the payload and the server *saves* it: a forum comment, a product review, a profile bio, a support ticket. Every user who later views that content is served the script. This is the most dangerous variant because it's self-propagating and hits many victims without any further attacker action; a single poisoned comment can compromise everyone who reads the thread.
  • Reflected XSS — the payload isn't stored; it's included in a request and immediately *reflected* back in the response. A classic case is a search page that echoes You searched for: <term> — put script in the term and it runs. Because nothing is persisted, the attacker must deliver the payload per-victim, typically via a crafted link in a phishing email or a malicious ad.
  • DOM-based XSS — the vulnerability lives entirely in the client-side JavaScript and the server may never see the payload at all. Vulnerable code reads untrusted input (a URL fragment, location.hash, a query parameter) and writes it into the page with something like element.innerHTML = input. The server returns a perfectly clean page; the browser's own script does the injecting.

All three end in the same place — attacker script executing in the victim's browser — but they demand different defenses and are found in different places, which is why the distinction matters.

03

What the injected script can do

Once the attacker's code is running in-origin, it inherits everything the page can do, and the consequences escalate fast.

The headline attack is session theft. If the site keeps its session ID or auth token somewhere script can reach — a non-HttpOnly cookie, localStorage — the payload reads it and sends it to an attacker-controlled server with a one-line fetch. The attacker then replays that session and *is* the victim, no password required.

But it doesn't stop at stealing credentials. The script can act as the user, from the user's browser, firing authenticated requests that are indistinguishable from legitimate ones: change the account email, add a new payment method, post spam, transfer funds, or silently create an attacker-controlled admin. It can rewrite the visible page to phish for passwords, log keystrokes, or pull in a larger exploit framework. Because everything happens inside a trusted session on a trusted origin, server-side logs often show nothing but ordinary user activity. That combination — full in-page power plus near-invisibility — is why XSS consistently ranks among the most serious web vulnerabilities.

04

Defenses, layer by layer

There is no single switch that fixes XSS; robust protection is a stack of controls, each catching what the others miss.

  • Output encoding / escaping is the primary defense and it targets the root cause. Whenever untrusted data is placed into a page, encode it for that exact context so it is rendered as inert text, not parsed as markup or code — < becomes &lt;, and so on. Encoding is context-sensitive: HTML body, HTML attributes, JavaScript, and URLs each need different escaping, which is why using a framework's auto-escaping templates (and avoiding raw innerHTML) is far safer than hand-rolling it.
  • Content-Security-Policy (CSP) is a defense-in-depth backstop. A CSP header tells the browser which script sources to trust and can forbid inline scripts entirely, so that even if a payload slips through, the browser refuses to execute it. It turns a would-be compromise into a blocked, reported event.
  • HttpOnly cookies shrink the blast radius. Marking session cookies HttpOnly hides them from document.cookie, so injected script can't read and exfiltrate them directly — an attacker may still make requests as the user, but can't walk away with the raw session token.
  • Input validation filters obviously bad input at the edge (reject or constrain what a field may contain), which reduces the attack surface but must never be relied on alone.
05

Putting it together in practice

The mental model that prevents XSS is simple to state and easy to forget under deadline pressure: treat every piece of data that originated outside your code as untrusted, and never let it cross the line from data into code. Attackers are creative about where "outside" input hides — it's not just form fields but URLs, headers, cookies, filenames, imported data, and content from other users — so the safe posture is to encode on the way *out*, at the moment data is written into a response, for the context it's being written into.

In a real application you combine the layers rather than betting on one. You lean on a modern framework's automatic, context-aware escaping and avoid the dangerous escape hatches (innerHTML, dangerouslySetInnerHTML, eval) unless you sanitize with a vetted library first. You ship a strict CSP so a missed spot fails safe. You set HttpOnly and Secure on session cookies so a breach doesn't immediately hand over the session. And you validate input where it enters. Any one of these can be bypassed; together they mean an attacker has to defeat several independent controls at once, which is exactly the depth XSS defense requires.

what to remember
01

XSS makes the victim's browser run attacker script under the trusted site's origin.

02

Stored XSS persists the payload on the server (a comment, profile) and hits everyone who views it.

03

Reflected XSS bounces the payload straight back in the response, delivered via a crafted link.

04

DOM-based XSS never touches the server — vulnerable client-side JS writes untrusted input into the page.

05

The script can read document.cookie, tokens, and the DOM, then exfiltrate them or act as the user.

06

Defenses layer: output encoding, Content-Security-Policy, HttpOnly cookies, and input validation.

check yourself

Quick quiz

Q1

What distinguishes DOM-based XSS from stored and reflected XSS?

Q2

Why does marking a session cookie HttpOnly help against XSS?

follow the thread