← Study Notes Security


Security

XSS

Cross-Site Scripting injects attacker-controlled JavaScript into pages other users view — stored, reflected or DOM-based — letting it steal sessions, log keystrokes or rewrite the page. The fix is contextual output encoding, treating all input as untrusted, and a strict Content-Security-Policy as defence in depth. React auto-escapes, but dangerouslySetInnerHTML reopens the hole.


Purpose

Cross-Site Scripting (XSS) is the injection of attacker-controlled JavaScript into pages other users view. Once running in the victim's browser it inherits their session — it can read data, forge actions, log keystrokes or rewrite the page. It comes in three flavours: stored (saved in your data), reflected (echoed from the request) and DOM-based (introduced client-side).

When to Use It

Understanding it matters anywhere user content is rendered: comments, profiles, search results, markdown, email templates. Any string that travels from user input to HTML output is a potential vector.

Trade-offs

Frameworks help but do not absolve: React escapes text by default, yet dangerouslySetInnerHTML, attribute injection (href="javascript:…") and third-party widgets reopen the hole. Sanitising HTML correctly is hard enough that you should use a battle-tested library, never a homemade regex.

Implementation

Encode output for its context (HTML body, attribute, URL); treat all input as untrusted; sanitise rich HTML with a maintained library (DOMPurify). Add a strict Content-Security-Policy as defence in depth so injected scripts cannot load or execute, and mark session cookies HttpOnly so scripts cannot read them.