Workbench / Volume 2 Exercises: The Web Frontend
V2·28
Frontend Security
Exercises for Volume 2, chapter 28: the browser threat model; XSS and framework escape hatches; DOM XSS sources and sinks; Content Security Policy; Trusted Types; prototype pollution; open redirects; CSRF; clickjacking; CORS misconfiguration; cross-origin isolation; dependency and supply-chain attacks; sessions, OAuth 2.0, OpenID Connect, PKCE, token handling in browsers, JWTs, refresh tokens, and passkeys. 10 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. Every attack here runs against your own local test pages, never anyone else's site. The measured exercises use Chromium 153 through Playwright, two local origins on different ports, Node 22's crypto, React 19.3.1's server renderer and npm 10. Every quoted output is real. Four are worth knowing before you start:
- P1: a
script-src 'self'CSP was bypassed through a same-origin JSONP endpoint. - P2: an injected
<base>tag loaded an attacker's script despite a nonce-based CSP, untilbase-uri 'none'was added. - P5: a redirect check written as
startsWith('/') && !startsWith('//')let/\evil.examplethrough. - P7: a JWT verifier that trusted the token's
algheader accepted a forged admin token.
The chapter's lab showed innerHTML XSS stealing a token (and textContent or a nonce CSP stopping it), Trusted Types blocking raw strings, frame-ancestors blocking framing, prototype pollution making ({}).isAdmin true, and npm audit finding 31 advisories in two old dependencies. The exercises build on those.
Coverage map.
| Chapter component | Exercises |
|---|---|
| threat model | T1 |
| XSS; framework escaping and escape hatches | T2, P3 |
| DOM XSS: sources and sinks | T2, P3 |
| CSP | T3, P1, P2 |
| Trusted Types | T3, P3 |
| prototype pollution | T4 |
| open redirects | T4, P5 |
| CSRF | T5, P4 |
| clickjacking | T5 |
| CORS misconfiguration | T6 |
| cross-origin isolation headers | T6, P6 |
| dependency attacks and supply-chain security | T7, P8 |
| sessions; cookie prefixes | T8, P4 |
| OAuth 2.0, OpenID Connect, PKCE | T9, P7 |
| token handling in browsers, JWT, refresh tokens | T9, P7 |
| passkeys and modern login | T10, P9 |
Theory
T1. The browser threat model
- List the attackers TiffinBox's web app faces (a malicious website the user visits, a malicious user of TiffinBox itself, a compromised dependency or CDN, a network attacker on public Wi-Fi, a browser extension, a malicious kitchen owner entering content) and what each can and can't do.
- What does the same-origin policy protect, and what crosses origins by design (navigations, form posts, embedded images and scripts, cookies attached to cross-site requests)? Why do most frontend attacks abuse those design choices?
- Where does the frontend's responsibility end? Which security properties can only the server enforce (authorisation, validation, rate limiting), and which only the browser can enforce (CSP, frame-ancestors, cookie attributes, Trusted Types)?
T2. XSS, framework escaping and DOM XSS
- Explain stored, reflected and DOM-based XSS with TiffinBox examples (a kitchen description, a search query echoed in the page,
location.hashwritten into the DOM). What can an attacker do once their script runs in your origin? - P3: React 19.3.1 rendered
<a href={userUrl}>with ajavascript:URL ashref="javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')"(also for" JAVASCRIPT:…"), but rendered<iframe src="data:text/html,<script>…">unchanged anddangerouslySetInnerHTMLas raw HTML. What does framework escaping protect, and what are the escape hatches in React, Angular and Vue? - List DOM XSS sources (
location.*,document.referrer,postMessagedata,localStoragevalues written by other code, URL fragments) and sinks (innerHTML,outerHTML,insertAdjacentHTML,document.write,eval,setTimeout(string),new Function,src/hrefof script and iframe,srcdoc, jQuery's$(html)).
T3. CSP and Trusted Types
- The lab's nonce-based CSP (
script-src 'nonce-…'; object-src 'none'; base-uri 'none') blocked an injected inline handler. P1 found thatscript-src 'self'was bypassed by injecting<script src="/jsonp?callback=…">(output:['INJECTED via JSONP', 'app.js']), while'nonce-abc' 'strict-dynamic'blocked the same injection (['app.js']). Why are allow-list CSPs weak, and how do nonces andstrict-dynamicwork? - P2: an injected
<base href="https://attacker/">made the page's relative<script nonce=abc src="b/app.js">load the attacker's file, with no CSP and with a nonce CSP lackingbase-uri; withbase-uri 'none'it loaded the real file. Explain, and list the directives a strict CSP needs (script-src,object-src,base-uri,frame-ancestors,form-action,report-to). - The lab's Trusted Types experiment: a raw string to
innerHTMLthrew "This document requires 'TrustedHTML' assignment", an unlisted policy name was disallowed, and DOMPurify/setHTML()produced safe output. How does Trusted Types change the security review burden, and how do you roll out CSP and Trusted Types on an existing app (report-only, violation reports, fixing sinks)?
T4. Prototype pollution and open redirects
- The lab's deep merge with
{"__proto__": {"isAdmin": true}}made({}).isAdmintrue. Explain the mechanism and three defences (key filtering,Object.create(null)/Map, schema validation), and how pollution becomes XSS through "gadgets". - P5 tested redirect validators on 11 inputs.
startsWith('/')accepted//evil.example/loginand/\evil.example; adding&& !startsWith('//')still accepted/\evil.example, which the browser resolved tohttps://evil.example/. A check withnew URL(t, origin).origin === originrejected all attacker inputs and accepted' /orders'and'HTTPS://tiffinbox.in/ok'. Explain why string checks fail and why parsing with the browser's own URL parser is the right approach. - Why are open redirects a security problem (phishing with a trusted domain, OAuth
redirect_uritoken theft, CSP allow-list bypasses), and how should "return to where you were after login" be implemented?
T5. CSRF and clickjacking
- Explain CSRF with a TiffinBox example (a hidden form on
evil.exampleposting totiffinbox.in/account/phonewith the victim's cookies), and the defences: SameSite cookies (Lax by default), anti-CSRF tokens (synchroniser or double-submit), checkingOrigin/Sec-Fetch-Siteheaders, and requiring non-simple requests (custom headers, JSON) for state changes. Why is SameSite alone not always enough (same-site subdomains, GET with side effects, older browsers,Laxallowing top-level GET)? - Chapter 24's P5: Next.js rejected a server-action request with a cross-site
Originheader. Which framework protections exist (Next.js server actions' origin check, Angular's XSRF token support, Django/Rails tokens), and what's left to you? - The lab's framing experiment showed
frame-ancestors 'none'blocking the framed bank page. Explain clickjacking variants (UI redressing, cursorjacking, double-click jacking) and when you need to allow framing (embedding your own widgets, partner portals).
T6. CORS misconfiguration and cross-origin isolation
- Chapter 24's S2 and chapter 19's T7 touched CORS. List the dangerous misconfigurations: reflecting any
Originwith credentials,nullorigin allowed, suffix/prefix matching (endsWith('tiffinbox.in')matcheseviltiffinbox.in), allowing all subdomains when one serves user content, missingVary: Origin. What does each let an attacker do? - P6: with COOP
same-originand COEPrequire-corp, the page became cross-origin isolated (crossOriginIsolated: true) andSharedArrayBufferbecame available (functionvsundefined), but a cross-origin image without a CORP header failed to load (width 0) while one withCross-Origin-Resource-Policy: cross-originloaded. Explain COOP, COEP, CORP, and why isolation is required for SharedArrayBuffer and high-precision timers (Spectre). - What does COOP alone protect against (cross-window attacks via
window.opener, XS-Leaks), and why isCross-Origin-Opener-Policy: same-origin-allow-popupsused for pages that open OAuth or payment popups?
T7. Supply-chain security
- The lab's
npm auditfound 31 advisories in axios and lodash. Explain why audit results need triage (reachability, server-only advisories, dev dependencies), and why audit doesn't catch a freshly compromised package. - P8 changed one
integrityvalue inpackage-lock.json;npm cirefused withEINTEGRITY … integrity checksum failed when using sha512: wanted sha512-AAAA… but got sha512-41Cif…. What do lockfiles and integrity hashes protect against (a tampered tarball on a mirror, registry or proxy), and what don't they (a malicious new version you choose to install, install scripts)? - List supply-chain defences for a frontend team: lockfiles and
npm ci, pinning and delayed adoption (minimumReleaseAge/cooldowns in Renovate or pnpm), disabling install scripts by default (pnpm'sonlyBuiltDependencies), provenance attestations andnpm audit signatures, least-privilege CI tokens and trusted publishing, dependency review in PRs (Socket, Dependabot), SRI for third-party CDN scripts (P2's 4a/4b), and minimising dependencies.
T8. Sessions and cookies
- Compare server-side sessions (opaque session ID in an HttpOnly cookie, state on the server) with stateless tokens (JWT in a cookie or header) for TiffinBox's web app: revocation, size, logout, scaling, and XSS exposure.
- P4 set seven cookies over
http://localhost:__Host-sid(Secure, Path=/, no Domain) was stored;__Host-badwithDomain=localhostwas rejected;__Host-nosecure(no Secure) rejected;__Secure-xstored,__Secure-ywithout Secure rejected;http(HttpOnly) stored but absent fromdocument.cookie. Explain cookie prefixes and why__Host-is the best choice for session cookies. - Design session handling: cookie attributes, session fixation protection (rotate the ID at login), idle and absolute timeouts, logout everywhere, step-up authentication for sensitive actions (changing phone number, payout details), and device/session listing.
T9. OAuth 2.0, OpenID Connect, PKCE and tokens in browsers
- Explain OAuth 2.0 roles (resource owner, client, authorisation server, resource server) and the authorisation code flow, and what OpenID Connect adds (the ID token,
nonce, the UserInfo endpoint, standard claims). Use "Sign in with Google" for TiffinBox and "Allow the TiffinBox partner app to read your bank statements" as examples. - P7 computed the PKCE
code_challengefor RFC 7636's test verifier and gotE9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, matching the RFC. Explain PKCE (what it prevents: authorisation code interception), thestateparameter (CSRF in the OAuth flow), exact redirect URI matching, and why the implicit flow is deprecated (OAuth 2.1). - Where should a browser app keep tokens? Compare: access token in memory + refresh via HttpOnly cookie; tokens in
localStorage; the BFF pattern (backend-for-frontend holding tokens, browser gets a session cookie). P7 also showed that anyone can read a JWT's payload without the key, and that a verifier honouring the header'salg: noneaccepted a forgedrole: admintoken. What are the JWT rules?
T10. Refresh tokens and passkeys
- Explain refresh token rotation with reuse detection: each refresh returns a new refresh token and invalidates the old one; if an old one is used again, the server revokes the whole token family. What attack does this detect, and what are the edge cases (two tabs refreshing at once, network failures mid-refresh)?
- What are passkeys (WebAuthn/FIDO2 credentials: a key pair per site, private key on the device or synced via a platform keychain, unlocked with biometrics or PIN), and why do they resist phishing (the browser binds the credential to the origin), credential stuffing and server breaches? P9 shows the registration and authentication data flow.
- TiffinBox users log in mostly with phone OTP. Compare SMS OTP, WhatsApp OTP, email magic links and passkeys on security (SIM swap, phishing relays, interception), usability on budget phones, and cost. Propose a migration path.
Programming exercises
P1. Bypass and fix an allow-list CSP
On a local test page with Content-Security-Policy: script-src 'self', inject <script src="/jsonp?callback=…"> through a reflected parameter and check whether the attacker-controlled callback runs. Then switch to script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none' and repeat. Evaluate both policies with Google's CSP Evaluator.
P2. The <base> tag, SRI and other directives
On a page that loads <script nonce=abc src="b/app.js"> (a relative URL), inject <base href="https://attacker-origin/"> with no CSP, with a nonce CSP without base-uri, and with base-uri 'none'. Then load a third-party script with Subresource Integrity, once with the correct hash and once after "the CDN file changed". Record which scripts run.
P3. Find and fix DOM XSS sinks with Trusted Types
Take an app with three sinks (a search term from location.search into innerHTML, a kitchen description from the API into dangerouslySetInnerHTML, and a "share" link built from location.hash into href). Deploy Content-Security-Policy-Report-Only: require-trusted-types-for 'script'; trusted-types app dompurify and collect violations; then fix each sink (textContent, a sanitising policy, URL validation), and switch to enforcing mode. Confirm React's handling of javascript: URLs.
P4. CSRF and cookie prefixes
Build a local "account settings" endpoint that changes the phone number on POST, protected only by a session cookie. From a second local origin, auto-submit a form to it with SameSite=None, Lax and Strict cookies and record which succeed. Add an Origin/Sec-Fetch-Site check and a CSRF token. Then set __Host- and __Secure- cookies with correct and incorrect attributes and record what the browser keeps.
P5. Write a safe redirect validator
Test three validators (startsWith('/'), startsWith('/') && !startsWith('//'), and parsing with new URL(t, origin) and comparing origins) against: /orders/42, //evil.example/login, /\evil.example, https://evil.example, /%2F%2Fevil.example, javascript:alert(1), ' /orders', https://tiffinbox.in.evil.example/x, /orders?next=//evil.example, \\evil.example, HTTPS://tiffinbox.in/ok. Record what each accepts and where the browser resolves each input. Then write the final safeRedirect and unit-test it.
P6. Cross-origin isolation in practice
Serve a page with and without Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp, embedding two cross-origin images (one with Cross-Origin-Resource-Policy: cross-origin, one without). Record crossOriginIsolated, typeof SharedArrayBuffer, and which images load. Then try COEP: credentialless, and list what in TiffinBox's pages would break under isolation (third-party images, maps, payment iframes, analytics).
P7. PKCE and JWT verification
Implement PKCE: generate a verifier, compute the S256 challenge, and check it against RFC 7636's test vector. Build an HS256 JWT, decode its payload without the key, forge an alg: none token with role: admin, and compare a verifier that trusts the header's alg with one using a fixed allow-list. Then use a maintained library (jose) and check iss, aud and exp.
P8. Supply-chain hygiene in a frontend repo
Install a dependency, then change its integrity value in package-lock.json and run npm ci. Record the result. Then configure: Renovate with a minimum release age, install scripts disabled except for an allow-list, npm audit in CI with triage notes, dependency review on PRs, SRI or self-hosting for CDN scripts, and a CSP connect-src limiting where a compromised script could send data.
P9. Add passkeys to the login flow
Implement passkey registration and login with SimpleWebAuthn (or the raw WebAuthn API) for a local app: registration options with rp.id, user, challenge, authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' }; verification on the server; login with conditional UI (autocomplete="username webauthn"); and a test using Playwright's virtual authenticator (CDP WebAuthn.addVirtualAuthenticator). Show that a credential registered on localhost can't be used from another origin.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–28)
C1. A security baseline for TiffinBox's web apps
Define and implement the baseline for the customer app (Next.js) and partner portal (Angular): HTTP security headers (strict CSP with nonces or hashes, Trusted Types, frame-ancestors, HSTS with preload, Referrer-Policy, Permissions-Policy, COOP where compatible), cookie policy (__Host- sessions, SameSite), CSRF protection for every mutating endpoint, safe redirect and URL handling, sanitisation policies, CORS rules, dependency policy (P8), secrets handling in builds (no secrets in client bundles), and automated checks (header tests in CI, CSP violation monitoring, Semgrep/ESLint security rules). Produce a checklist teams can follow.
Combines: HTTP and cookies (ch 19), full-stack framework server actions and caching (ch 24), testing in CI (ch 26), Angular and React specifics (ch 22, 23) and this chapter.
C2. Implement login with OIDC, a BFF and step-up
Implement TiffinBox's login: phone OTP and "Sign in with Google" via OIDC (authorisation code + PKCE + state + nonce), handled by a BFF in the full-stack app, which stores tokens server-side and issues a __Host- session cookie; session rotation at login; refresh token rotation with reuse detection for the Google tokens (if needed for API access); step-up authentication (OTP or passkey) before changing the phone number or payout details; logout everywhere; and passkeys as an optional upgrade (P9). Write tests for the flows and for attacks (state mismatch, code reuse, redirect URI tampering, CSRF on step-up).
Combines: HTTP cookies and CORS (ch 19), full-stack framework route handlers and server actions (ch 24), state machines for auth flows (ch 25), testing with Playwright (ch 26) and this chapter's OAuth/OIDC and session sections.
C3. Threat-model and harden the partner portal's payout settings
Kitchen owners change their bank account for payouts in the partner portal. Threat-model this feature (STRIDE or attack trees): account takeover, CSRF, clickjacking, XSS in staff-entered notes, a malicious browser extension, insider abuse, a compromised dependency, social engineering. Implement mitigations (step-up with passkey or OTP, cooling-off period and notifications, CSP and Trusted Types, frame-ancestors, audit log, dual control for large payouts) and write tests and monitoring for each.
Combines: Volume 1's security and threat modelling foundations (ch 06 and the security sections of ch 10), Angular security features (ch 23), state machines (ch 25), testing (ch 26) and this chapter.
What the chapter leaves out
Security testing tools and practices
Beyond unit and integration tests: DAST scanners (OWASP ZAP, Burp Suite) against staging, SAST for JavaScript/TypeScript (Semgrep, CodeQL) with rules for XSS sinks and unsafe redirects, dependency scanning (npm audit, Socket, Snyk), secret scanning in repos and built bundles, CSP Evaluator and header checkers, bug bounty programmes and responsible disclosure (/.well-known/security.txt), and regular penetration tests. Security regression tests (P1–P5 style) keep fixed bugs fixed.
Privacy engineering in the frontend
Security and privacy overlap: minimise personal data in the browser (don't send full addresses or phone numbers to pages that don't need them), avoid personal data in URLs (logged everywhere), control third-party scripts and what they can read (session replay tools capturing form fields), honour consent before loading analytics, respect Global Privacy Control, and comply with India's Digital Personal Data Protection Act 2023 (consent, purpose limitation, data principal rights) and GDPR for EU users.
WebAssembly, extensions and other platform surfaces
WebAssembly runs inside the same sandbox and CSP rules ('wasm-unsafe-eval' is needed to compile WASM under a strict CSP: chapter 29); browser extensions have their own security model (manifest permissions, content scripts); postMessage between windows and iframes needs origin checks on both sides; service workers can persist malicious behaviour after an XSS (register only from your own code, scope narrowly, and use Clear-Site-Data on logout); and the Permissions API and Permissions-Policy control powerful features (camera, geolocation, payment).
Payment security in the browser
Payment pages are prime targets for web skimming (Magecart-style injected scripts stealing card numbers). PCI DSS 4.0 requires inventories and integrity checks for scripts on payment pages (requirements 6.4.3 and 11.6.1), which in practice means strict CSP, SRI, change detection, and using hosted payment fields or redirects (Razorpay/Stripe Elements in iframes) so card data never touches your DOM. UPI intents and app redirects in India move most payments out of the page, but checkout pages still need the same script controls.
Incident response for frontend security
When XSS or a compromised dependency is found: contain (deploy a CSP that blocks the vector, remove the dependency, roll back), assess impact (CSP reports, logs of affected sessions, what data the script could reach), revoke (rotate tokens and sessions: Clear-Site-Data, logout everywhere), notify users and regulators as required (CERT-In's 6-hour reporting rule for certain incidents in India), and fix root causes (Trusted Types, dependency policy). Practice with a tabletop exercise.
Senior exercises
S1. Set the frontend security standards
Write the frontend security standard for TiffinBox's teams: required headers and how they're set, rules for rendering untrusted content, URL handling, authentication and token storage, CSRF, dependency policy, third-party scripts, secrets in builds, security reviews (which changes need one), and the automated checks that enforce each rule.
S2. Review a pull request for security issues
A PR adds a "share your order" feature: it reads ?ref= from the URL and does document.getElementById('banner').innerHTML = 'Shared by ' + ref; builds <a href={order.kitchenWebsite}> from kitchen-entered data; stores the access token in localStorage for the share API; adds Access-Control-Allow-Origin: * with credentials on the share endpoint; redirects after login to req.query.next with startsWith('/'); and loads a social-sharing SDK from a CDN without SRI. Write the review.
S3. Decide on token storage and session architecture
The mobile app uses OAuth tokens against the API; the web app copied that approach, storing access and refresh tokens in localStorage. Security wants a change; engineering worries about effort and the mobile/web split. Write the decision: options (keep with mitigations, memory + refresh cookie, BFF with sessions), threat analysis, migration plan, and impact on CDN caching, SSR and the API.
S4. Respond to a compromised dependency
A widely used npm package in your build (a date-picker's transitive dependency) published a malicious patch version yesterday that steals environment variables during install and injects a skimming script into built bundles. Your CI ran npm install (not npm ci) on three branches since then, and one build was deployed to production. Write the incident response.
S5. Teach frontend security with five attacks you can run
Prepare a 30-minute hands-on session using this chapter's local experiments: the lab's search-page XSS, P1's JSONP CSP bypass, P2's <base> hijack, P5's /\evil.example redirect, and P7's alg: none JWT. For each: the attack, the one-line fix, and the general rule. End with five rules.