Courses / Frontend System Design, with JavaScript Foundations / Chapter 14
Module 6 · Patterns, Architecture and Security · Chapter 14 of 21
Security in Frontend Systems
Builds on The DOM, Events and Observers and API Styles, Protocols and Data Formats. Next up: A Step-by-Step Method for Frontend Design Sessions.
Part 1 · Threats to a page and XSS
What cross-site scripting is
A web page runs in the user's browser, but the code on it is not all written by you. Anything that lets a stranger's text become code on your page is a classic frontend security hole.
Cross-site scripting (XSS) is an attack where the attacker gets their own JavaScript to run on your page, with your page's origin. The browser's usual protection, the same-origin policy, does not help, because the script is running as you. It can read everything on the page, read cookies and storage that scripts may read, send requests to your API with the user's cookies attached, and rewrite the page to show a fake form.
OWASP, the web security community, groups XSS by how the payload arrives.
| Kind | How the payload reaches the page | Example |
|---|---|---|
| Stored | the server saves it and sends it to every visitor | a comment containing markup |
| Reflected | it is in the request, and the server writes it into the reply | a search term echoed in the page |
| DOM-based | client-side script reads it and writes it into the page; the server never sees it | a script that copies location.search into the DOM |
A useful way to find DOM-based XSS is to think in sources and sinks. A source is where untrusted data enters your code: the URL (location.search, location.hash), document.referrer, a postMessage event, storage, or a server reply that contains user text. A sink is a place where data is interpreted as markup or code: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, and string forms of setTimeout. A bug is a path from a source to a sink with nothing in between.
A DOM XSS you can run
The lab has two pages on a local server. The first copies the q parameter of the URL into the page with innerHTML, as a search page might. The second loads comments from the server and writes each into a list the same way. The first page also sets a session cookie marked HttpOnly and an ordinary cookie that scripts can read.
Every script in this chapter starts by importing three helpers from one small file, h.mjs: launch starts the local Chrome, listen starts a server on a port, and html sends an HTML reply with optional headers. The port numbers in the listings are the ones this chapter's runs used.
import http from 'node:http' import { chromium } from 'playwright-core' export const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe' export const launch = () => chromium.launch({ executablePath: CHROME }) export const listen = (port, handler) => new Promise((resolve) => { const server = http.createServer(handler) server.listen(port, '127.0.0.1', () => resolve(server)) }) export const html = (res, body, headers = {}) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...headers }) res.end(body) } export const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
h.mjs: the helpers every script imports.
const comments = [] const page = `<!doctype html><title>Search</title> <h1>Shop search</h1> <div id="result"></div> <script> document.cookie = 'theme=dark' const q = new URLSearchParams(location.search).get('q') ?? '' document.querySelector('#result').innerHTML = 'You searched for: ' + q </script>` const wall = `<!doctype html><title>Comments</title> <ul id="list"></ul> <script> document.cookie = 'theme=dark' fetch('/api/comments').then((r) => r.json()).then((all) => { for (const c of all) list.innerHTML += '<li>' + c + '</li>' }) </script>`
xss1.mjs: the two vulnerable pages.
const server = await listen(55800, (req, res) => { const url = new URL(req.url, 'http://x') if (url.pathname === '/') { return html(res, page, { 'set-cookie': 'session=s-17; HttpOnly' }) } if (url.pathname === '/comments') return html(res, wall) if (url.pathname === '/api/comments' && req.method === 'POST') { let body = '' req.on('data', (c) => (body += c)) req.on('end', () => { comments.push(JSON.parse(body).text) res.end('ok') }) return } if (url.pathname === '/api/comments') { return res.end(JSON.stringify(comments)) } res.statusCode = 204 res.end() })
xss1.mjs: the server.
What the run teaches
The result for payload A surprises many people. Scripts inserted through innerHTML are not executed by the browser, so a filter that only looks for the word script feels safe. Payload B shows why it is not. An event handler attribute such as onerror runs when the event fires, and there are dozens of such attributes on dozens of elements. Blocklists of dangerous tags always miss one.
The session cookie stayed out of reach, but only that. A script in your page can still call your API with the cookie attached. The browser adds the cookie to the request whether the page's code or an attacker's code made it. So HttpOnly limits what is stolen, but it does not stop an attacker acting as the user while the page is open.
The next lessons build the defences in layers, since no single one is enough.
| Layer | What it does | Lesson |
|---|---|---|
| Encode or avoid the sink | data never becomes markup | the next lesson |
| Sanitise HTML you must allow | strips what is dangerous | the next lesson |
| Trusted Types | makes raw strings in sinks an error | the next lesson |
| Content Security Policy | blocks scripts that should not run | the lesson after that |
| Cookie flags and token storage | limits what a successful attack can take | the last two lessons |
Why did payload A, a script element, not run when written with innerHTML, and why is that not a defence?
Part 2 · Encoding, sanitising and Trusted Types
Encode for the place the data lands
The cleanest fix for a source-to-sink path is to make the data stop being markup. The rule the OWASP prevention cheat sheet gives is to encode on output, and to encode for the context the data lands in. Text between tags, an attribute value and a URL parameter each have different dangerous characters.
In HTML text the dangerous characters are < and &. In a quoted attribute, the quote character that closes the value matters most. In a URL, the characters that have meaning in a URL have to be percent-encoded. The script below does all three, first raw and then encoded.
const entities = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => entities[c]) const comment = '<img src=x onerror=steal()>' console.log('text context, raw :', `<p>${comment}</p>`) console.log('text context, escaped:', `<p>${escapeHtml(comment)}</p>`) const name = '" onfocus="steal()" x="' console.log('attribute, raw :', `<input value="${name}">`) const safe = escapeHtml(name) console.log('attribute, escaped :', `<input value="${safe}">`) const search = 'tea & ghee?'
escape.mjs: three contexts, raw and encoded.
text context, raw : <p><img src=x onerror=steal()></p> text context, escaped: <p><img src=x onerror=steal()></p> attribute, raw : <input value="" onfocus="steal()" x=""> attribute, escaped : <input value="" onfocus="steal()" x=""> URL parameter : /search?q=tea%20%26%20ghee%3F&page=2
Output (Node 24)
The raw comment becomes a real img element. The raw name closes the value attribute early and adds an onfocus handler of its own. The escaped versions are inert text. encodeURIComponent turned the space, the ampersand and the question mark into percent codes, so the search term cannot add a second parameter. The cheat sheet's advice is to encode parameter values and not whole URLs.
Hand-written escaping like this is for illustration. In real code, use the encoding your template library does by default, and treat any place where it is switched off as a code review item.
Safer sinks, and links that run code
Often the better answer is to choose a sink that cannot run code at all. textContent writes plain text, so markup in the data is shown as characters. Compare the same payload through the two sinks in a page loaded in Chrome. The script's server has a /blank route that returns an empty div with the id o, and the page's code runs through Playwright's evaluate. The second part of the script is about links.
const browser = await launch() const page = await browser.newPage() await page.goto(`${base}/blank`) const payload = '<img src=x onerror="window.hit=1">' console.log('-- textContent shows the payload as text') console.log(await page.evaluate((p) => { o.textContent = p return `${o.children.length} elements, text: ${o.textContent}` }, payload))
xss2.mjs: the same payload, written with `textContent`.
A link is a different kind of sink. An href may start with javascript:, and clicking such a link runs the code in the page. If the URL comes from user data, that is XSS without a single angle bracket. The fix is to check the scheme. The page below parses the URL, allows only http: and https: and replaces anything else with #.
console.log('-- a javascript: link, before and after a URL check') await page.evaluate(() => { window.safeHref = (u) => { const url = new URL(u, location.href) return ['http:', 'https:'].includes(url.protocol) ? url.href : '#' } const bad = 'javascript:void(window.hit = "link ran")' o.innerHTML = '<a id=a>raw</a> <a id=b>checked</a>' a.href = bad b.href = safeHref(bad) }) const ran = () => page.evaluate(() => window.hit ?? 'nothing ran') await page.click('#b') await page.waitForTimeout(200) console.log('checked href:', await ran()) await page.click('#a') await page.waitForTimeout(200) console.log('raw href :', await ran()) await browser.close() server.close()
xss2.mjs: a link set directly and a link set after a check.
-- textContent shows the payload as text 0 elements, text: <img src=x onerror="window.hit=1"> -- a javascript: link, before and after a URL check checked href: nothing ran raw href : link ran
Output (Chrome 157)
The text sink printed the payload and created no elements. The checked link did nothing when clicked, and the raw link ran the script. A check that tests whether the string starts with http is weaker than parsing, since attackers vary case and whitespace, which is why the code parses with URL and compares the protocol.
Sanitising HTML you have to allow
Sometimes the data really is HTML: a rich-text comment, an email body, a help article written by staff. Encoding would show the tags as text, so the page must keep some markup and remove the rest. That is sanitising, and it is hard to do correctly by hand. Use a maintained library. OWASP recommends DOMPurify, which parses the input and removes anything outside an allowed set.
The script loads DOMPurify into a page in Chrome and passes four dirty strings through DOMPurify.sanitize.
The server below serves DOMPurify's browser build at /purify.js and one page, /tt, with a response header. The header is the Trusted Types part, explained further down: it is here because the same page is used for both runs.
const purify = readFileSync('../node_modules/dompurify/dist/purify.js') const policy = "require-trusted-types-for 'script'; trusted-types app dompurify" const server = await listen(55801, (req, res) => { if (req.url === '/purify.js') { res.setHeader('content-type', 'text/javascript') return res.end(purify) } if (req.url === '/tt') { return html(res, `<title>t</title><div id=o></div> <script src="/purify.js"></script>`, { 'content-security-policy': policy }) } res.statusCode = 204 res.end() })
xss3.mjs: the server and its header.
const browser = await launch() const page = await browser.newPage() await page.goto('http://127.0.0.1:55801/tt') console.log('-- DOMPurify.sanitize, input then output') const samples = [ '<img src=x onerror="steal()">', '<b>bold</b><script>steal()</script>', '<a href="javascript:steal()">go</a>', '<p onclick="steal()">text</p>', ] for (const s of samples) { const clean = await page.evaluate((x) => DOMPurify.sanitize(x), s) console.log(s.padEnd(38), '->', clean) }
xss3.mjs: four dirty inputs through DOMPurify.
-- DOMPurify.sanitize, input then output <img src=x onerror="steal()"> -> <img src="x"> <b>bold</b><script>steal()</script> -> <b>bold</b> <a href="javascript:steal()">go</a> -> <a>go</a> <p onclick="steal()">text</p> -> <p>text</p>
Output (Chrome 157)
The onerror handler, the script element, the javascript: link and the onclick attribute are all gone, and the harmless markup stays. Two rules from the cheat sheet matter. Do not change the output after sanitising it, because a later edit can undo the cleaning. And keep the library up to date, since bypasses are found from time to time.
Trusted Types
All of the above rely on developers remembering. Trusted Types makes the browser enforce it. A page that sends the Content-Security-Policy header require-trusted-types-for 'script' may no longer pass a plain string to a dangerous sink such as innerHTML. The sink accepts only a special typed value that a named policy created. The trusted-types directive limits which policy names may exist. According to MDN, Trusted Types has been Baseline newly available since February 2026.
The policy in the script below is named app and sanitises with DOMPurify. The header also allows a policy named dompurify, because the library makes a policy of that name for itself. Left out of the header, it makes every sanitize call return an empty string: that was checked by running the script with only app in the trusted-types list. So the header has to list it.
console.log('-- Trusted Types enforced by the header') const result = await page.evaluate(() => { const log = [] try { o.innerHTML = '<b>raw</b>' } catch (e) { log.push(`${e.name}: ${e.message}`) } const app = trustedTypes.createPolicy('app', { createHTML: (s) => DOMPurify.sanitize(s), }) const dirty = '<b>clean</b><img src=x onerror=steal()>' o.innerHTML = app.createHTML(dirty) log.push('through the policy: ' + o.innerHTML) try { trustedTypes.createPolicy('other', { createHTML: (s) => s }) } catch (e) { log.push(`${e.name}: ${e.message}`) } return log }) for (const line of result) console.log(line)
xss3.mjs: a raw string, a policy, and a policy that is not allowed.
-- Trusted Types enforced by the header TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment. through the policy: <b>clean</b><img src="x"> TypeError: Failed to execute 'createPolicy' on 'TrustedTypePolicyFactory': Policy "other" disallowed.
Output (Chrome 157)
The raw assignment threw a TypeError before anything reached the page. The same string, passed through the app policy, came out cleaned. Creating a policy named other failed, because it was not listed. MDN's note is the important caveat: Trusted Types does not sanitise anything itself. A policy that returns its input unchanged satisfies the browser and protects nothing, so its value comes from keeping the number of policies small and making each one do real work.
Part 3 · Content Security Policy
A second line of defence
Encoding and sanitising must be right everywhere. A Content Security Policy (CSP) is a second layer that still holds when one of them fails: the server sends a header that tells the browser which scripts it is allowed to run.
A policy is a list of directives. script-src says where scripts may come from, object-src covers plugins, base-uri limits the page's <base> element, and report-uri names an address that the browser tells about violations. MDN marks report-uri as deprecated in favour of report-to, which needs a separate Reporting-Endpoints header; the lab uses report-uri because it is the simpler one to read in a local server. Older policies listed allowed host names. The web.dev guidance on strict CSP recommends a different approach: allow a script only if it carries a nonce, a random value the server puts in the header and in the script tag, or if its hash is listed.
A policy with only default-src 'self' blocks inline scripts and scripts from other hosts. Allowing a CDN host by name is weaker than it looks, because anything that host serves is then trusted, including scripts an attacker can get it to serve. The nonce and hash forms avoid that by trusting a specific script, not a place.
A nonce must be freshly generated for every response. An attacker who can inject markup into a page cannot guess it, so injected inline scripts are blocked while the page's own scripts, which carry the nonce, run.
The lab server reflects the q parameter into the page unencoded, which is the bug, and serves it under four policies. The page also contains its own nonced script, which creates another inline script at run time.
const reports = [] const base = 'http://127.0.0.1:55802' const injectedOf = (url) => new URL(url, base).searchParams.get('q') ?? '' // the page reflects ?q= into the HTML without encoding it: a bug const app = (nonce, q) => `<!doctype html><title>Shop</title> <p>Results for ${q}</p> <script nonce="${nonce}"> window.app = 'own script ran' const s = document.createElement('script') s.textContent = "window.child = 'created script ran'" document.head.append(s) </script>` const policies = { '/plain': () => null, '/strict': (n) => `script-src 'nonce-${n}' 'strict-dynamic'; ` + "object-src 'none'; base-uri 'none'; report-uri /csp-report", '/nonce-only': (n) => `script-src 'nonce-${n}'; report-uri /csp-report`, '/report-only': (n) => `script-src 'nonce-${n}' 'strict-dynamic'; ` + 'report-uri /csp-report', }
csp.mjs: the vulnerable page and the four policies.
The same attack under four policies
const server = await listen(55802, (req, res) => { const path = new URL(req.url, base).pathname if (path === '/csp-report') { let body = '' req.on('data', (c) => (body += c)) req.on('end', () => { reports.push(JSON.parse(body)['csp-report']) res.end() }) return } if (!policies[path]) { res.statusCode = 204; return res.end() } const nonce = randomBytes(12).toString('base64') const policy = policies[path](nonce) const header = path === '/report-only' ? 'content-security-policy-report-only' : 'content-security-policy' const headers = policy ? { [header]: policy } : {} html(res, app(nonce, injectedOf(req.url)), headers) })
csp.mjs: the server picks a policy and a fresh nonce.
const browser = await launch() const injected = "<script>window.xss = 'injected script ran'</script>" for (const path of Object.keys(policies)) { const page = await browser.newPage() const messages = [] page.on('console', (m) => messages.push(m.text())) await page.goto(`${base}${path}?q=${encodeURIComponent(injected)}`) await page.waitForTimeout(300) const seen = await page.evaluate(() => ({ own: window.app, child: window.child, xss: window.xss, })) console.log(`== ${path}`) console.log(' own script :', seen.own ?? 'blocked') console.log(' created script:', seen.child ?? 'blocked') console.log(' injected :', seen.xss ?? 'blocked') const first = messages[0]?.split(' Either')[0] if (first) console.log(' console :', first) } console.log('== reports the server received') for (const r of reports) { console.log(' ', r['effective-directive'], r['blocked-uri'], r.disposition) } await browser.close()
csp.mjs: Chrome visits each page with an injected script.
== /plain
own script : own script ran
created script: created script ran
injected : injected script ran
== /strict
own script : own script ran
created script: created script ran
injected : blocked
console : Executing inline script violates the following Content
Security Policy directive 'script-src 'nonce-e6SCZo0sHpTRWD3D'
'strict-dynamic''.
== /nonce-only
own script : own script ran
created script: blocked
injected : blocked
console : Executing inline script violates the following Content
Security Policy directive 'script-src 'nonce-u1Q0ln8bHSzsRoDD''.
== /report-only
own script : own script ran
created script: created script ran
injected : injected script ran
console : Executing inline script violates the following Content
Security Policy directive 'script-src 'nonce-ireEx/tMDgHhehNE'
'strict-dynamic''.
== reports the server received
script-src-elem inline enforce
script-src-elem inline enforce
script-src-elem inline enforce
script-src-elem inline reportOutput (Chrome 157; the nonce is random on each run)
Hashes, report-only and the meta trap
A nonce needs the server to build every response. A static page that is served from a file or a CDN cannot, so it can use a hash instead: the policy lists the SHA-256 of each inline script's exact text. The script below computes the hash, serves a page whose script matches, and serves a second page whose script was changed by one word.
import { createHash } from 'node:crypto' import { launch, listen, html } from './h.mjs' const reports = [] const code = "window.ran = 'inline script ran'" const hash = createHash('sha256').update(code).digest('base64') const tampered = "window.ran = 'tampered script ran'"
csp2.mjs: the script text, and its hash.
const server = await listen(55802, (req, res) => { if (req.url === '/csp-report') { req.resume() req.on('end', () => { reports.push('report received'); res.end() }) return } const policy = `script-src 'sha256-${hash}'` if (req.url === '/hash-ok') { return html(res, `<title>t</title><script>${code}</script>`, { 'content-security-policy': policy }) } if (req.url === '/hash-bad') { return html(res, `<title>t</title><script>${tampered}</script>`, { 'content-security-policy': policy }) } if (req.url === '/meta') { return html(res, `<title>t</title> <meta http-equiv="Content-Security-Policy-Report-Only" content="script-src 'none'; report-uri /csp-report"> <script>${code}</script>`) } res.statusCode = 204 res.end() })
csp2.mjs: the server: a matching page, a changed page, a meta policy.
const browser = await launch() for (const path of ['/hash-ok', '/hash-bad', '/meta']) { const page = await browser.newPage() const messages = [] page.on('console', (m) => messages.push(m.text())) await page.goto(`http://127.0.0.1:55802${path}`) await page.waitForTimeout(300) const ran = await page.evaluate(() => window.ran ?? 'blocked') console.log(path.padEnd(10), ran) for (const m of messages) { console.log(' console:', m.split(' Either')[0]) } } console.log('reports received:', reports.length) await browser.close() server.close()
csp2.mjs: Chrome loads each page.
/hash-ok inline script ran
/hash-bad blocked
console: Executing inline script violates the following Content
Security Policy directive 'script-src
'sha256-uVcPvu0Fo8qybqHUsbUgOfO6ryIrVG97jqgX3k/gw0o=''.
/meta inline script ran
console: The report-only Content Security Policy 'script-src 'none';
report-uri /csp-report' was delivered via a <meta> element, which is
disallowed. The policy has been ignored.
reports received: 0Output (Chrome 157)
The page whose text matched the hash ran. The changed one did not. A hash binds a policy to exact bytes, so any edit to the script means a new hash.
Part 4 · Origins, CORS and cookies
Origin and site
A browser decides what one page may do to another by comparing where they come from. Two words describe that, and they are often mixed up: origin and site.
An origin is the scheme, host and port of a URL. Two URLs are same-origin only if all three match. A site is the scheme plus the registrable domain, such as example.com, so a different subdomain or port is still the same site. The same-origin policy stops a page from reading responses from another origin, and cookies follow the looser idea of a site.
const base = 'https://shop.example.com' const others = [ 'https://shop.example.com/cart', 'http://shop.example.com', 'https://shop.example.com:8443', 'https://api.example.com', 'https://example.com', ] console.log('page origin:', new URL(base).origin) for (const u of others) { const origin = new URL(u).origin const same = origin === new URL(base).origin const verdict = same ? 'same' : 'cross' console.log(u.padEnd(30), origin.padEnd(29), verdict) }
origins.mjs: which URLs share an origin with the page.
page origin: https://shop.example.com https://shop.example.com/cart https://shop.example.com same http://shop.example.com http://shop.example.com cross https://shop.example.com:8443 https://shop.example.com:8443 cross https://api.example.com https://api.example.com cross https://example.com https://example.com cross
Output (Node 24)
Only the first URL matches, since a different scheme, a different port, a subdomain or the bare domain each give another origin. Yet four of the five are the same site, because they are HTTPS and share example.com. Only the plain HTTP URL is another site, because the scheme is part of a site. Origin decides whether a script may read a reply. Site decides whether SameSite cookies are sent. This lesson uses both.
CORS
The same-origin policy blocks a page from reading a reply from another origin. Cross-Origin Resource Sharing (CORS) is the way a server agrees to be read. The server adds Access-Control-Allow-Origin to its reply naming the origin it allows, and the browser then lets the page read it. For a simple request, which needs no question first, the request has already been sent by the time the browser decides, and that matters.
Some requests are sent without asking first. MDN calls them simple requests: GET, HEAD or POST, with only safelisted headers and a content type of form, multipart or plain text. Anything else, such as a PUT or a request with Content-Type: application/json, triggers a preflight. The browser sends an OPTIONS request first, asking whether the real one is allowed, and only then sends it. The server's preflight answer lists the allowed methods and headers, and Access-Control-Max-Age says how long the answer may be cached. MDN gives the default as 5 seconds, and browsers cap larger values.
The page is on localhost:55803 and the API is on localhost:55804, which is another origin. The server records every request it receives.
const PAGE = 'http://localhost:55803' const API = 'http://localhost:55804' const log = [] const page = await listen(55803, (req, res) => html(res, '<title>app</title>')) const api = await listen(55804, (req, res) => { const path = req.url log.push(`${req.method} ${path}`) const cors = {} if (path === '/open' || path === '/json' || path === '/creds') { cors['access-control-allow-origin'] = PAGE } if (path === '/star') cors['access-control-allow-origin'] = '*' if (path === '/star' || path === '/creds') { cors['access-control-allow-credentials'] = 'true' } if (req.method === 'OPTIONS') { cors['access-control-allow-methods'] = 'PUT' cors['access-control-allow-headers'] = 'content-type' cors['access-control-max-age'] = '600' res.writeHead(204, cors) return res.end() } res.writeHead(200, { 'content-type': 'text/plain', ...cors }) res.end('hello from the API') })
cors.mjs: the API sets different CORS headers on each path.
const browser = await launch() const tab = await browser.newPage() const messages = [] tab.on('console', (m) => messages.push(m.text())) await tab.goto(PAGE + '/') const attempt = (label, path, init) => tab.evaluate(async ([p, i]) => { try { const r = await fetch(p, i) return 'read the reply: ' + await r.text() } catch (e) { return `${e.name}: ${e.message}` } }, [API + path, init]).then((r) => { console.log(label.padEnd(28), r) for (const m of messages.splice(0)) { const why = m.split('blocked by CORS policy: ')[1] if (why) console.log(' why:', why) } })
cors.mjs: Chrome, and a helper that tries one call.
Cookies and SameSite
A cookie is a small value the server asks the browser to store and send back. Its attributes decide when it is sent. HttpOnly hides it from scripts, but per MDN it is still sent with requests that scripts make. Secure limits it to HTTPS, though MDN notes an exception for localhost, and Chrome also accepted it on the local addresses used in this lab. SameSite controls cross-site sending: Strict sends it only for requests from the same site, Lax also sends it on top-level navigations with a safe method, and None sends it everywhere and requires Secure. MDN says only that some browsers default to Lax when the attribute is missing, so set it explicitly.
Cookies are keyed by host and not by port. The lab shows both facts. A page on localhost:55803 calls three APIs with credentials: one on localhost:55804 (same site, another origin) with a Lax cookie, one on 127.0.0.1 with a Lax cookie, and one on 127.0.0.1 with a None cookie.
const APP = 'http://localhost:55803' const SAME = 'http://localhost:55804' // same site, other origin const OTHER = 'http://127.0.0.1:55805' // a different site const NONE = 'http://127.0.0.1:55806' // another origin of it const seen = {} const cookieApi = (name) => (req, res) => { if (req.url === '/login') { res.setHeader('set-cookie', { same: 'sid-same=1; HttpOnly; SameSite=Lax', lax: 'sid-lax=1; HttpOnly; SameSite=Lax', none: 'sid-none=1; HttpOnly; SameSite=None; Secure', }[name]) return html(res, 'logged in') } seen[name] = req.headers.cookie ?? '(no cookie)' res.writeHead(200, { 'access-control-allow-origin': APP, 'access-control-allow-credentials': 'true' }) res.end('ok') } const servers = [ await listen(55803, (req, res) => html(res, '<title>app</title>')), await listen(55804, cookieApi('same')), await listen(55805, cookieApi('lax')), await listen(55806, cookieApi('none')), ] const browser = await launch() const ctx = await browser.newContext() const tab = await ctx.newPage()
cookies.mjs: each API sets its own cookie when visited.
await tab.goto(`${SAME}/login`) // a normal visit stores the cookie await tab.goto(`${OTHER}/login`) await tab.goto(`${NONE}/login`) await tab.goto(`${APP}/`) const call = (url) => tab.evaluate( (u) => fetch(u, { credentials: 'include' }).then(() => 'done'), url) await call(`${SAME}/data`) await call(`${OTHER}/data`) await call(`${NONE}/data`) const sent = (kind, name) => seen[kind].includes(name + '=') ? 'sent' : 'not sent' console.log('page on', APP, 'calls with credentials: include') console.log('same-site, Lax :', sent('same', 'sid-same')) console.log('cross-site, Lax :', sent('lax', 'sid-lax')) console.log('cross-site, None :', sent('none', 'sid-none')) console.log('cookie header at :55805 :', seen.lax)
cookies.mjs: the page calls each API with credentials.
Cookie name prefixes
Name prefixes add checks that the browser enforces. A name starting with __Host- is accepted only with Secure, with Path=/ and with no Domain attribute, which pins the cookie to exactly one host. The server below offers four cookies.
const server = await listen(55803, (req, res) => { res.setHeader('set-cookie', [ '__Host-a=1; Secure; Path=/; HttpOnly; SameSite=Lax', '__Host-b=1; Path=/', '__Host-c=1; Secure; Path=/; Domain=localhost', 'plain=1; Path=/', ]) html(res, '<title>t</title>') }) const browser = await launch() const ctx = await browser.newContext() const page = await ctx.newPage() await page.goto('http://localhost:55803/') console.log('offered: __Host-a Secure, Path=/') console.log(' __Host-b no Secure') console.log(' __Host-c Domain=localhost') console.log(' plain no prefix') const stored = (await ctx.cookies()).map((c) => c.name) console.log('stored :', stored.join(', ')) await browser.close() server.close()
hostprefix.mjs: one valid `__Host-` cookie and three bad ones.
offered: __Host-a Secure, Path=/
__Host-b no Secure
__Host-c Domain=localhost
plain no prefix
stored : __Host-a, plainOutput (Chrome 157)
The browser stored the valid prefixed cookie and the plain one, and dropped the other two. MDN says the prefixes apply when the cookie is set by a secure page, and Chrome treated the local address as one here. MDN also says you cannot count on the assurance in browsers that do not support prefixes, because they accept the cookie anyway, so a prefix is an extra layer and not the only protection.
The API answered without CORS headers and the browser blocked the read. Did the request reach the server?
- Yes. The server's log shows the
GETarrived. - CORS stops the page reading the reply and does not protect the server from the request.
Which two cookie settings together decide whether a cookie is sent on a cross-site request from another site?
SameSitedecides, andNonealso needsSecure.- A
Laxcookie is not sent on a cross-site fetch.
Part 5 · CSRF and clickjacking
How a cross-site request forgery works
A request that changes something on a site can be sent from any page, and the browser adds the user's cookies to it. That is the whole attack.
In cross-site request forgery (CSRF) an attacker's page makes the user's browser send a state-changing request to a site where the user is signed in. The browser attaches the session cookie as it always does, so the site cannot tell the request was not meant. An auto-submitting form on the attacker's page is enough. The attacker never reads the reply, since a forged request only needs to be sent.
What stops it is the server telling an intended request from a forged one. The OWASP cheat sheet describes these defences, and tells you to check first whether your framework already protects state-changing requests.
- Synchroniser token: the server stores a random token in the user's session and puts it in each form. A request is accepted only when it carries the token. The attacker's page cannot read the form, because the same-origin policy forbids it.
- Signed double-submit cookie: for servers with no session store. The token is bound to the session by a signature. The naive form, where a cookie and a field merely match, is discouraged because an attacker who can set cookies can match them.
- Fetch Metadata: browsers add a
Sec-Fetch-Siteheader saying whether a request is same-origin, same-site or cross-site. OWASP callsSec-Fetch-Sitethe most useful of the Fetch Metadata headers and says a fallback to theOriginandRefererheaders is required for browsers that do not send them. - SameSite cookies: they stop the cookie travelling cross-site. OWASP treats them as defence in depth, not a replacement for the above.
The lab runs one attack under five setups. The shop is on localhost:55803 and the attacker's page is on 127.0.0.1:55804, another site. The server has a session cookie and a form that changes the account's email address.
One attack, five setups
const SHOP = 'http://localhost:55803' const EVIL = 'http://127.0.0.1:55804' let email = 'priya@example.com' const sessions = { abc: { token: 'tok-7f3a' } } // what the server decides for a POST: three endpoints, three rules const decide = (path, session, fields, site) => { if (!session) return '401: no session cookie arrived' if (path === '/email-meta' && site !== 'same-origin') { return `403: Sec-Fetch-Site is ${site}` } if (path === '/email-token' && fields.get('csrf') !== session.token) { return '403: token missing' } return 'changed' }
csrf.mjs: the server state and the three rules.
const shop = await listen(55803, (req, res) => { const url = new URL(req.url, SHOP) const cookie = req.headers.cookie ?? '' const session = cookie.includes('sid=abc') ? sessions.abc : null if (url.pathname === '/login') { const same = url.searchParams.get('mode') === 'lax' ? 'SameSite=Lax' : 'SameSite=None; Secure' res.setHeader('set-cookie', `sid=abc; HttpOnly; ${same}`) return html(res, 'ok') } if (url.pathname === '/settings') { return html(res, `<form method=post action="/email-token"> <input name=csrf value="${sessions.abc.token}"> <input name=email value="priya.new@example.com"> <button>Save</button></form>`) } if (req.method !== 'POST') { res.statusCode = 204; return res.end() } let body = '' req.on('data', (c) => (body += c)) req.on('end', () => { const fields = new URLSearchParams(body) const site = req.headers['sec-fetch-site'] const verdict = decide(url.pathname, session, fields, site) if (verdict === 'changed') email = fields.get('email') html(res, `<p id=r>${verdict}</p>`) }) })
csrf.mjs: login, the settings form and the POST handler.
const evil = await listen(55804, (req, res) => { const target = new URL(req.url, EVIL).searchParams.get('to') html(res, `<title>win a prize</title> <form id=f method=post action="${SHOP}${target}"> <input name=email value="attacker@example.com"></form> <script>f.submit()</script>`) }) const browser = await launch() const run = async (label, mode, target, legit) => { const ctx = await browser.newContext() const page = await ctx.newPage() await page.goto(`${SHOP}/login?mode=${mode}`) if (legit) { await page.goto(`${SHOP}/settings`) await page.click('button') } else { await page.goto(`${EVIL}/?to=${target}`) } const verdict = await page.locator('#r').textContent() console.log(label.padEnd(26), verdict.padEnd(34), '| email:', email) await ctx.close() } await run('1 cookie None, no check', 'none', '/email-open') email = 'priya@example.com' await run('2 cookie Lax, no check', 'lax', '/email-open') await run('3 None, Fetch Metadata', 'none', '/email-meta') await run('4 None, token, attacker', 'none', '/email-token') await run('5 None, token, real form', 'none', '/email-token', true) await browser.close()
csrf.mjs: the attacker's page, and Chrome running each setup.
Clickjacking
A second kind of trick does not forge a request. Clickjacking loads your page in an invisible frame on the attacker's page, so that the user thinks they are clicking the attacker's button and actually click yours. The request is real and comes from the real page, so no token helps. The only defence is to stop the page being framed by sites you did not choose.
The modern tool is the frame-ancestors directive of CSP, which lists which sites may embed the page. frame-ancestors 'none' allows nobody. The older X-Frame-Options header does the same job with fewer options. OWASP quotes the CSP specification: an enforced frame-ancestors makes the browser ignore X-Frame-Options, although old browser versions did not follow that rule. It also says ALLOW-FROM is obsolete and no longer works in modern browsers. Neither may be set in a <meta> element. The server serves a payment page four ways and the attacker's page frames each one.
const SHOP = 'http://localhost:55803' const EVIL = 'http://127.0.0.1:55804' const variants = { '/open': {}, '/csp': { 'content-security-policy': "frame-ancestors 'none'" }, '/xfo': { 'x-frame-options': 'DENY' }, } const shop = await listen(55803, (req, res) => { if (req.url === '/meta') { return html(res, `<title>pay</title> <meta http-equiv="Content-Security-Policy" content="frame-ancestors 'none'">Pay now`) } html(res, '<title>pay</title>Pay now', variants[req.url] ?? {}) }) const evil = await listen(55804, (req, res) => { const path = new URL(req.url, EVIL).searchParams.get('path') html(res, `<title>free tea</title> <iframe src="${SHOP}${path}" style="opacity:0.01"></iframe>`) })
frame.mjs: four variants of the page, and the attacker.
const browser = await launch() for (const path of ['/open', '/csp', '/xfo', '/meta']) { const page = await browser.newPage() const messages = [] page.on('console', (m) => messages.push(m.text())) await page.goto(`${EVIL}/?path=${path}`) await page.waitForTimeout(400) const child = page.frames().find((f) => f !== page.mainFrame()) const shown = (await child.title()) === 'pay' ? 'shown' : 'refused' console.log(path.padEnd(6), 'framed page is', shown) for (const m of messages.filter((x) => /frame|Refused/i.test(x))) { console.log(' console:', m.trim()) } } await browser.close() shop.close(); evil.close()
frame.mjs: Chrome loads the attacker page for each.
/open framed page is shown /csp framed page is refused console: Framing 'http://localhost:55803/' violates the following Content Security Policy directive: "frame-ancestors 'none'". The request has been blocked. /xfo framed page is refused console: Refused to display 'http://localhost:55803/' in a frame because it set 'X-Frame-Options' to 'deny'. /meta framed page is shown console: The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> element.
Output (Chrome 157)
Part 6 · Tokens, postMessage and third-party code
Where a sign-in token lives
Once a user is signed in, something has to prove it on each request. Where you keep that proof decides what an XSS bug can take.
There are two usual places. A cookie is sent by the browser automatically, and with HttpOnly a script cannot read it. A token kept in web storage, localStorage or sessionStorage, is read by your code and added to requests as a header, which means any script on the page can read it too. OWASP's HTML5 cheat sheet says it plainly: do not store session identifiers in local storage, since the data is always accessible by JavaScript, and that cookies can mitigate this risk with the httpOnly flag.
The lab signs a user in with an HttpOnly cookie, keeps a second token in localStorage, and then opens the page with an injected payload like the one from the first lesson. The payload tries to carry away what it can and also calls the API.
const base = 'http://127.0.0.1:55803' const server = await listen(55803, (req, res) => { const url = new URL(req.url, base) if (url.pathname === '/api/me') { const ok = (req.headers.cookie ?? '').includes('session=s-17') return res.end(ok ? 'user priya' : 'anonymous') } if (url.pathname !== '/') { res.statusCode = 204; return res.end() } html(res, `<title>app</title><div id=o></div> <script> localStorage.setItem('token', 'jwt-demo-abc') o.innerHTML = new URLSearchParams(location.search).get('q') </script>`, { 'set-cookie': 'session=s-17; HttpOnly; SameSite=Lax', }) })
tokens.mjs: the page, with both a cookie and a stored token.
// what an injected script tries to carry away const loot = `<img src=x onerror=" window.loot = { cookie: document.cookie, token: localStorage.getItem('token') } fetch('/api/me').then((r) => r.text()).then((t) => loot.me = t)">` const browser = await launch() const page = await browser.newPage() await page.goto(`${base}/`) // sign in: cookie is set await page.goto(`${base}/?q=${encodeURIComponent(loot)}`) await page.waitForTimeout(400) const got = await page.evaluate(() => window.loot) console.log('document.cookie :', JSON.stringify(got.cookie)) console.log('localStorage token :', got.token) console.log('fetch with the cookie:', got.me) await browser.close() server.close()
tokens.mjs: the payload and what it collects.
document.cookie : ""
localStorage token : jwt-demo-abc
fetch with the cookie: user priyaOutput (Chrome 157)
postMessage between windows
Pages in different origins cannot read each other, but they sometimes need to talk: a payment frame to its parent, a widget to the page that embeds it. window.postMessage is the supported way. It carries two risks, and OWASP names both. The receiver must check event.origin against the exact origin it expects, because anyone can send it a message. The sender must give the expected origin as the second argument instead of *, so that the message is not delivered to some other page if the frame has moved.
The lab has a receiver on localhost:55803 in two versions, one that acts on any message and one that checks the sender's origin. A trusted widget on localhost:55805 and an attacker's page on 127.0.0.1:55804 each frame the receiver and send the same message.
const RECEIVER = 'http://localhost:55803' const WIDGET = 'http://localhost:55805' // the trusted sender const ATTACKER = 'http://127.0.0.1:55804' // another site const receiver = await listen(55803, (req, res) => { const checked = req.url === '/checked' html(res, `<title>r</title><script> window.log = [] addEventListener('message', (e) => { if (${checked} && e.origin !== '${WIDGET}') { window.log.push('ignored a message from ' + e.origin) return } window.log.push('acted on ' + JSON.stringify(e.data) + ' from ' + e.origin) }) </script>`) }) const sender = (port) => listen(port, (req, res) => { const to = new URL(req.url, 'http://x').searchParams const src = `${RECEIVER}/${to.get('r')}` html(res, `<title>s</title><iframe id=f src="${src}"></iframe><script> f.onload = () => f.contentWindow.postMessage({ cmd: 'pay' }, '${to.get('target') ?? '*'}')</script>`) }) const widget = await sender(55805) const attacker = await sender(55804)
postmsg.mjs: two receivers, and a page that frames one and sends.
const browser = await launch() const cases = [ ['naive receiver, widget', WIDGET, 'naive'], ['naive receiver, attacker', ATTACKER, 'naive'], ['checked receiver, widget', WIDGET, 'checked'], ['checked receiver, attacker', ATTACKER, 'checked'], ] for (const [label, origin, r] of cases) { const page = await browser.newPage() await page.goto(`${origin}/?r=${r}`) await page.waitForTimeout(300) const frame = page.frames().find((f) => f !== page.mainFrame()) const log0 = (await frame.evaluate(() => log))[0] console.log(label.padEnd(28), log0) } const page = await browser.newPage() const seen = [] page.on('console', (m) => seen.push(m.text())) await page.goto(`${WIDGET}/?r=naive&target=http://localhost:9`) await page.waitForTimeout(300) const frame = page.frames().find((f) => f !== page.mainFrame()) const got = await frame.evaluate(() => log) console.log('wrong targetOrigin: receiver got', got.length, 'messages') console.log(seen.find((m) => m.includes('target origin'))) await browser.close()
postmsg.mjs: every sender and receiver combination.
Third-party scripts and Subresource Integrity
Many pages load a script from another host: analytics, a tag manager, a library from a CDN. That script runs with your origin's full rights, so an attacker who changes it on its host controls your page. Subresource Integrity (SRI) reduces that risk. You add an integrity attribute holding the hash of the file you reviewed, and the browser refuses to run a copy whose hash differs.
The script computes a SHA-384 hash and tries five script tags. Two are same-origin, one of them with a changed file. Three are served from another origin.
const good = "window.lib = 'library v1 ran'" const evil = "window.lib = 'TAMPERED library ran'" const sri = 'sha384-' + createHash('sha384').update(good).digest('base64') const SHOP = 'http://localhost:55803' const CDN = 'http://127.0.0.1:55804' const script = (res, body, cors) => { res.writeHead(200, { 'content-type': 'text/javascript', ...(cors ? { 'access-control-allow-origin': '*' } : {}) }) res.end(body) } const cdn = await listen(55804, (req, res) => { if (req.url === '/lib.js') return script(res, good, true) if (req.url === '/lib-nocors.js') return script(res, good, false) res.statusCode = 204 res.end() }) const tag = (src, cors = '') => `<script src="${src}" ${cors} integrity="${sri}">` const anon = 'crossorigin="anonymous"' const cases = { '1 same origin, right hash': tag('/lib.js'), '2 same origin, file changed': tag('/lib-evil.js'), '3 other origin, crossorigin': tag(`${CDN}/lib.js`, anon), '4 other origin, no attribute': tag(`${CDN}/lib.js`), '5 other origin, no CORS reply': tag(`${CDN}/lib-nocors.js`, anon), }
sri.mjs: the hash, the five tags and the servers.
const shop = await listen(55803, (req, res) => { if (req.url === '/lib.js') return script(res, good, false) if (req.url === '/lib-evil.js') return script(res, evil, false) const n = new URL(req.url, SHOP).searchParams.get('case') if (n) { const tagText = Object.values(cases)[n - 1] return html(res, `<title>t</title>${tagText}</script>`) } res.statusCode = 204 res.end() }) const browser = await launch() for (const [i, label] of Object.keys(cases).entries()) { const page = await browser.newPage() const messages = [] page.on('console', (m) => messages.push(m.text())) await page.goto(`${SHOP}/?case=${i + 1}`) await page.waitForTimeout(300) const ran = await page.evaluate(() => window.lib ?? 'blocked') console.log(label.padEnd(30), ran) if (i === 1 || i === 3) console.log(' console:', messages[0]) } await browser.close() shop.close(); cdn.close()
sri.mjs: the shop server, and Chrome loading each case.
1 same origin, right hash library v1 ran 2 same origin, file changed blocked console: Failed to find a valid digest in the 'integrity' attribute for resource 'http://localhost:55803/lib-evil.js' with computed SHA-384 integrity '3gj/2f5ELJg+hfUd6IQ8BMF7HdmdN127Li7D59s9zhplH85TES3CFXNxkWQ2awOr'. The resource has been blocked. 3 other origin, crossorigin library v1 ran 4 other origin, no attribute blocked console: Subresource Integrity: The resource 'http://127.0.0.1:55804/lib.js' has an integrity attribute, but the resource requires the request to be CORS enabled to check the integrity, and it is not. The resource has been blocked because the integrity cannot be enforced. 5 other origin, no CORS reply blocked
Output (Chrome 157)
All chapters · Previous: Frontend Design Patterns and Architectures