Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·28

Frontend Security

Companion to Volume 2, chapter 28: how injection defences, cross-origin protections and identity connect; new angles (CSP as a guest list, Trusted Types as a locked kitchen door, SameSite as a stamp that only counts in your own restaurant); what the chapter simplifies, measured: Trusted Types set to 'none' refusing a test tool's script tag and DOMPurify's own policy until the policy is named; CSP reporting where adding report-to made Chromium stop sending report-uri reports, and the Reporting API delivered nothing in 90 seconds; and nonces, hidden from getAttribute and CSS but readable as a property by any script; the theory behind it; how DOMPurify decides what to remove, including DOM clobbering and namespace confusion; four debugging drills; interview questions with how to approach each.

6 sections · ~13 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 28 has three strands. Injection: the browser threat model, XSS and framework escaping, DOM XSS, CSP and Trusted Types, prototype pollution and open redirects. Cross-origin attacks and the supply chain: CSRF, clickjacking, CORS, cross-origin isolation, dependencies. Identity: sessions and cookies, OAuth and OpenID Connect with PKCE, tokens in browsers, refresh tokens and passkeys.

injection cross-origin and supply chain identity threat model who, what, where XSS, escaping framework defaults DOM XSS sources and sinks CSP, Trusted Types lock the sinks prototype pollution open redirects CSRF SameSite, Fetch Metadata clickjacking frame-ancestors CORS who may read cross-origin isolation COOP, COEP supply chain dependencies, SRI sessions, cookies HttpOnly, prefixes OAuth, OIDC, PKCE delegated login tokens in browsers BFF or not refresh tokens rotation passkeys phishing-resistant starts with or caught by and and and and and or issues renewed by or goes deeper: ch12 web platform · ch22 React · ch23 Angular · ch24 SSR · Volume 3 auth and backend security exercises: P1–P9 CSP bypass, base and SRI, DOM XSS, CSRF, redirects, isolation, PKCE, supply chain, passkeys
Concept map of chapter 28, frontend security: injection (the browser threat model, XSS and framework escaping, DOM XSS, CSP and Trusted Types, prototype pollution and open redirects), cross-origin attacks and the supply chain (CSRF, clickjacking, CORS, cross-origin isolation, dependencies) and identity (sessions and cookies, OAuth and OIDC with PKCE, tokens in browsers, refresh tokens and passkeys), with links such as CSP and Trusted Types catching the injections escaping missed and cookies' SameSite carrying most of CSRF defence.

The links worth remembering:

  • Defence in depth means each layer assumes the one before failed. Escaping (chapters 22–23) stops most injection; CSP stops injected script from running; Trusted Types stops strings reaching sinks at all; reports tell you a layer was tested. Stage 28 adds the last two.
  • Origins are the browser's unit of trust. CSRF, CORS, framing and cookie scope are all questions of which origin may do what to which. "Same site" is weaker than "same origin" (stage 12's lesson about other ports).
  • Identity in the browser is a set of trade-offs, not a best practice. Cookies, tokens, BFFs and passkeys each move risk somewhere else; the chapter's exercises pick for TiffinBox, Volume 3 builds it.

Explain it differently

1. CSP is a guest list. The doorman lets in only people on the list (scripts from 'self', styles with tonight's nonce); a gatecrasher who got in through the window (an injected inline script) is still stopped at the dining-room door.

2. Trusted Types is a locked kitchen door. Nobody walks into the kitchen carrying raw ingredients from the street (strings into innerHTML); everything goes through a named supplier (a policy) who inspects it. With trusted-types 'none', there are no suppliers at all: nothing gets in that way (Gaps 1).

3. A nonce is tonight's password. It changes every evening (every response), so last night's password is useless. But anyone already inside can hear it (Gaps 3).

4. SameSite is a stamp that only counts in your own restaurant. A loyalty card stamped Lax is shown when the guest walks in from the street, but not when another restaurant sends a waiter over to order in the guest's name.

5. CORS is a receptionist deciding who may read the mail, not who may send it. A cross-origin request may still arrive and do its work; CORS decides whether the sending page may read the answer. That's why CSRF needs its own defence.

6. Prototype pollution is changing the master recipe card. Every dish made from it after that inherits the change, even in kitchens that never saw the edit.

7. A dependency is a supplier with keys to the kitchen. A compromised supplier doesn't need to break in: they already deliver into the walk-in fridge. Lockfiles, provenance and minimal dependencies limit who holds keys.

8. A passkey is a key that only fits your own door. A phishing site is a different door; the key won't turn, so there's nothing for the user to be tricked into handing over.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Chromium, DOMPurify 3.2.7, jsdom 27.0.0 and the build's stage 28 (exp/28), unless stated.

1. trusted-types 'none' is the strictest setting, and it also refuses your tools. The chapter shows Trusted Types blocking a string written to innerHTML, and recommends DOMPurify for HTML you must insert. Stage 28 sets require-trusted-types-for 'script'; trusted-types 'none' (the build needs no policies). Two consequences found along the way. The test suite's usual way of injecting axe, Playwright's add_script_tag, was refused:

Terminal
playwright._impl._errors.Error: Page.add_script_tag: TypeError: Failed to set the 'src' property on 'HTMLScriptElement': This document requires 'TrustedScriptURL' assignment.

(The suite now serves axe as a <script src> added to the HTML as it arrives: parser-inserted, same-origin, allowed, and run under the real policy. Before stage 28 it bypassed the CSP.) And a sanitiser needs a policy too. DOMPurify on a page with 'none', then with its policy named:

Terminal
trusted-types 'none': ["string from sanitize(): Failed to set the 'innerHTML' property on 'Element': This document requires 'Tru", "RETURN_TRUSTED_TYPE: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' "] | console: ['Creating a TrustedTypePolicy named \'dompurify\' violates the following Content Security policy directive: "trusted-types ', "This document requires 'TrustedHTML' assignment. The action has been blocked."]
trusted-types dompurify: ["string from sanitize(): Failed to set the 'innerHTML' property on 'Element': This document requires 'Tru", 'RETURN_TRUSTED_TYPE: assigned <img src="x"><b>Dosa</b>'] | console: ["This document requires 'TrustedHTML' assignment. The action has been blocked."]

A sanitised string is still a string, so assigning it is refused either way; only RETURN_TRUSTED_TYPE with the dompurify policy allowed in the CSP works. Third-party widgets, analytics and older libraries that write HTML from strings break the same way, so turning Trusted Types on is an inventory of every sink first (the build's boundary check bans them in its own code), report-only mode to find the rest, and named policies for each legitimate one.

2. CSP reports: one directive can silence the other. The chapter recommends report-to with the Reporting API, keeping report-uri for older browsers. Stage 28 sent both, then deliberately violated Trusted Types and waited:

Terminal
csp-report 2026-11-16T11:48:40.109194287Z {"csp-report":{"document-uri":"http://127.0.0.1:18326/menu","referrer":"","violated-directive":"require-trusted-types-for","effective-directive":"require-trusted-types-for", … ,"blocked-uri":"trusted-types-sink","line-number":1,"column-number":56,"status-code":200,"script-sample":"Element innerHTML|<b>x</b>"}}

That report arrived only with report-uri alone. With report-to csp in the policy as well (and the Reporting-Endpoints header), Chromium ignored report-uri, as the specification says it should, and the Reporting API delivered nothing to the server within 90 seconds of waiting. The Reporting API batches and delays reports by design, and its delivery depends on the browser's own scheduling; in a test, or right before a page closes, reports may never be sent. So the build sends report-uri only for now, and stage 32 tests report-to against the real RUM endpoint. Note also what the report contains: a script-sample with the first characters of what was blocked, which may include user data; reports are personal data to be stored and retained accordingly.

3. A nonce protects against injected markup, not injected script. The chapter describes nonce-based CSP as the strongest option for inline scripts and styles. The Angular page's nonce, as seen from the page:

Terminal
{'getAttribute("nonce")': '', '.nonce length': 24, 'CSS selector matches its first letter': False, 'style elements with the nonce': 1}

Browsers hide the nonce attribute from the DOM after parsing: getAttribute returns an empty string and CSS attribute selectors can't match it, which defeats the old trick of stealing nonces with injected CSS. But the nonce property is readable by any script, which is how Angular finds it (and how the build's main.ts passes it to Angular). If an attacker's script runs, it can read the nonce and use it. The nonce stops injected HTML from running script; it doesn't contain script that already runs. Two more rules follow: the nonce must be new for every response (stage 28's test checks two loads differ), and a page with a nonce must never be cached and served to someone else (the build's pages are no-store).

Common misconceptions

Misconception What's actually true Where it's shown
"Sanitise, then assign to innerHTML." Under Trusted Types, a sanitised string is refused; only a trusted value from a named policy works. Gaps 1
"Send both report-to and report-uri for coverage." With report-to present, Chromium ignored report-uri. Gaps 2; drill D2
"A nonce is a secret on the page." Any running script can read it as a property. Gaps 3
"Fetch Metadata is enough against CSRF." Older browsers don't send it; the build now checks Origin too. Drill D3
"CORS stops cross-site requests." It controls who reads responses; the request still happens. Explain it differently 5
"DOMPurify removes everything risky." It keeps what's inert by its rules (a data: SVG image); context matters. Code walkthrough

Theoretical gaps: the ideas behind the chapter

1. Taint tracking. XSS is untrusted data flowing to a dangerous sink. Static and dynamic taint analysis track sources (URL, storage, messages) to sinks (innerHTML, eval, src); Trusted Types is taint tracking enforced by the browser's type system: only values of a special type may reach a sink.

2. Capability-based security. A Trusted Types policy is a capability: code holding the policy can create trusted values; code without it can't. 'none' means no capability exists. Capabilities, not checks at every use, are the robust way to restrict powerful operations.

3. The confused deputy. CSRF is the classic confused deputy: the browser holds the user's authority (cookies) and uses it on behalf of another site's request. Defences remove ambient authority (SameSite), or require proof the request came from the right origin (Fetch Metadata, Origin, tokens).

4. Same-origin policy as an isolation boundary. Origins are the browser's processes: each has its own storage and can't read another's responses. Cross-origin isolation (COOP, COEP) strengthens the boundary against side channels like Spectre, as process isolation does in operating systems.

5. Supply-chain trust is transitive. Installing one package trusts its dependencies and its authors' accounts. Reproducible builds, provenance (Sigstore, npm provenance), lockfiles and minimal dependency trees reduce how far that trust extends.

6. Authentication is a protocol, and protocols are attacked at their edges. OAuth's redirects, state and PKCE exist because each step can be intercepted or replayed; passkeys bind the credential to the origin, removing phishing as an attack on the protocol's human step.

Applying it

Code walkthrough

Gaps 1 used DOMPurify, the sanitiser most applications use for HTML they must insert. Excerpts from DOMPurify 3.2.7, dist/purify.es.mjs, installed from npm.

The Trusted Types policy it creates

JavaScript
const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
  // …
  const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML(html) {
        return html;
      },
      createScriptURL(scriptUrl) {
        return scriptUrl;
      }
    });
  } catch (_) {
    console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
    return null;
  }

The policy's functions return their input unchanged: the policy isn't the sanitiser, it's the capability to mark DOMPurify's own output as trusted. That's why the CSP must allow the name dompurify (Gaps 1), and why a second copy of DOMPurify on the page fails (duplicate policy names throw; the data-tt-policy-suffix attribute exists for that).

Elements

JavaScript
  const _sanitizeElements = function _sanitizeElements(currentNode) {
    // …
    /* Check if element is clobbered or can clobber */
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    // …
    /* Detect mXSS attempts abusing namespace confusion */
    if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    // …
    /* Remove element if anything forbids its presence */
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      // … keep the children of a removed element, unless it's in FORBID_CONTENTS …
      _forceRemove(currentNode);
      return true;
    }
    /* Check whether element has a valid namespace */
    if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }

DOMPurify parses the input into a real DOM tree (the browser's own parser, so it sees what the browser would), then walks it. A form whose properties have been replaced by child elements (_isClobbered: a form with an input named attributes makes form.attributes the input, not the attribute list) is removed, because DOMPurify itself would be fooled by it. Elements whose text looks like markup are removed (mutation XSS: markup that is harmless once parsed can become dangerous when serialised and parsed again in a different namespace). Disallowed elements are removed but their children kept by default. Elements in the wrong namespace (an HTML element inside SVG where it can't be) are removed.

Attributes

JavaScript
  const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
    /* Make sure attribute cannot clobber */
    if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
      return false;
    }
    // … data-* and aria-* allowed; anything not in ALLOWED_ATTR refused …
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
      return false;
    } else ;
    return true;
  };

An id or name is refused if its value is already a property of document or of a form (name="cookie" would make document.cookie an element: DOM clobbering). Attribute values are checked against an allowed-URI pattern after removing whitespace (which defeats java\tscript:), and data: URLs are allowed only in src or href of tags where they're inert (images, not scripts).

Read it yourself

Before running it, predict what DOMPurify.sanitize returns for: an image with onerror; a link to javascript:alert(1); an SVG containing a script; <svg><style><img src=x onerror=alert(1)></style></svg>; a form named cookie with an input named value; and an image whose src is a data: SVG with onload.

Debugging drills

D1. Trusted Types on, and the accessibility tests break

After adding require-trusted-types-for 'script'; trusted-types 'none', every axe test fails before running, with Failed to set the 'src' property on 'HTMLScriptElement': This document requires 'TrustedScriptURL' assignment.

D2. The CSP report endpoint receives nothing

The CSP has report-uri /csp-reports; report-to csp and a Reporting-Endpoints header. A deliberate violation in staging is blocked, but no report ever arrives.

D3. A cross-site form post works in one browser and not another

A security tester shows that a form on another site can change a visitor's theme preference, but only from an old Safari. Chromium and Firefox get 403.

D4. Angular's styles work, then stop after a cache is added

The Angular view's component styles apply correctly. After someone adds a CDN rule to cache kitchen pages for a minute, the styles randomly stop applying for some users, with Applying inline style violates the following Content Security Policy directive in the console.

Career-oriented

Interview prep

Mid level

Q1. What does a Content Security Policy protect against, and what doesn't it?

How to get there. Think about which attacker actions it blocks once injection has happened, and which it can't see.

Q2. How would you roll out Trusted Types on an existing application?

How to get there. Find the sinks before enforcing.

Senior level

Q3. Design CSP reporting for a large application.

How to get there. Consider volume, noise, privacy and what you'll do with a report.

Q4. Your app has no login today. What cross-site risks still matter?

How to get there. List what a cross-site page can make a visitor's browser do here.

Staff level

Q5. Set the security baseline for every web application in your organisation, and how it's enforced.

How to get there. Pick defaults that are safe without effort, and checks that catch drift.

Q6. A third-party chat widget requires 'unsafe-inline' and injects HTML from strings. Sales wants it next week. What do you do?

How to get there. Weigh the risk it brings against ways to contain it.