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

Workbench / Volume 2 Companion: The Web Frontend

V2·12

The Web Platform

Companion to Volume 2, chapter 12: how addresses, the document trees and the browser's security model connect; new angles (a URL as a postal address read by three different clerks, an origin as a flat with its own lock, the event loop as a single cook with a ticket rail); what the chapter simplifies, from one URL that a browser and Python resolve to two different hosts to Telugu text turning into "మస" without a charset, a sandboxed frame that sends `Origin: null`, and timers that stop being zero after five nestings; the theory behind it (the web's origin model as capabilities, parser differentials, why compatibility freezes bugs); the WHATWG URL parser and encoding sniffer as written in the reference implementations jsdom uses; four debugging drills; interview questions with how to approach each.

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

Understanding it better

Concept map

Chapter 12 has three strands. Addresses and trust: URLs identify everything, origins decide what trusts what, and browsing contexts hold the documents that navigation creates and replaces. Loading and the trees: bytes arrive, are decoded into characters, and are parsed into the DOM, styled through the CSSOM, rendered, and exposed as the accessibility tree. The runtime and security: one event loop runs the page's scripts, storage is partitioned by origin, and the same-origin policy, CORS, cookies and CSP decide what a page may read and run.

addresses and trust loading and the trees runtime and security URLs parsed by the WHATWG rules origins scheme + host + port sites registrable domain browsing contexts tabs · frames · windows documents one per navigation navigation, history back · forward · bfcache resource loading fetch · priority · order decoding bytes → characters DOM the document as objects CSSOM rules → computed styles accessibility tree what assistive tech sees rendering style · layout · paint event loop tasks · microtasks · frames storage cookies · local · IndexedDB same-origin policy read only your own CORS the server opts in cookies, CSRF sent by site, not origin CSP, isolation limit what runs yields grouped into inside shows replaced by bytes parsed into styled by then alongside scripts use keyed by origin relaxed by with credentials plus goes deeper: ch17 DOM APIs · ch18 browser internals · ch19 networking · ch28 security · Volume 1 ch 9: HTTP and TLS exercises: P1–P11 measure script order, the same-origin policy, storage, frames, attributes and the event loop
Concept map of chapter 12, the web platform: addresses and trust (URLs, origins, sites, browsing contexts, documents, navigation and history), loading and the trees (resource loading and script order, the DOM, the CSSOM, the accessibility tree, rendering) and the runtime and security (the JavaScript event loop, storage, the same-origin policy, CORS, cookies and CSP), with links such as the origin deciding what storage and requests a page may use, and the DOM and CSSOM combining into what is rendered.

The links worth remembering:

  • Everything security-related starts from the URL. The origin (scheme, host, port) is computed from the URL by a precise parser; storage, the same-origin policy and CORS all key off that origin. If two components parse the same URL differently, they disagree about which origin is involved (Gaps 1).
  • Bytes become characters before they become a tree. Decoding is an easily forgotten stage between "loading" and "the DOM", and it's where Indian-language text breaks (Gaps 2).
  • The server decides some things and the browser decides others. The server chooses headers (charset, CORS, CSP, cookies); the browser enforces them. Most of the platform's bugs are the two sides having different assumptions.

Explain it differently

1. A URL is a postal address read by three different clerks. "Flat 4, Sai Residency\Ameerpet@Begumpet" is ambiguous: one clerk treats the backslash as a typo for a slash, another treats @ as "care of", a third rejects it. Delivery depends on which clerk reads it. Browsers, Python and Java are three clerks with three rulebooks, and Gaps 1 shows them delivering the same string to different hosts. The WHATWG URL standard exists to make every browser use the same rulebook; the rest of the world hasn't fully joined.

2. An origin is a flat with its own lock. https://tiffinbox.in and https://admin.tiffinbox.in are neighbouring flats in the same building (the same site), but each has its own lock: one can't open the other's cupboards (storage) or read its post (responses). Cookies, though, are more like the building's shared notice board: anything addressed to the building can be seen by every flat. That difference between origin and site explains much of cookie security.

3. The event loop is a single cook with a ticket rail. One cook (the main thread) takes one ticket (task) at a time: a click, a timer, a network response. Between tickets, the cook clears the small urgent notes (microtasks, like promise callbacks), and from time to time stops to plate what's ready (rendering, about 60 times a second). A ticket that takes 200 ms means nothing else is cooked, plated or answered for 200 ms: the page freezes. That's why long tasks are the enemy of responsiveness (Chapter Exercises P11).

4. A document is a play performed on a stage; navigation replaces the play. The browsing context is the stage: it stays. Each navigation brings in a new play (a document) with its own cast (DOM), costumes (styles) and script (JavaScript state), and the old one is cleared away, unless the theatre keeps it backstage for a quick return (the back/forward cache). Single-page apps keep one play running and change the scenery themselves, which is why they must manage history explicitly.

5. CORS is the server writing a permission slip. By default, a page can send a request to another origin (like posting a letter), but it can't read the reply. CORS lets the other origin write a permission slip in its response headers ("pages from tiffinbox.in may read this"). The browser checks the slip; the server never stops the request from arriving. That's why CORS protects users' data from being read, but not servers from receiving requests (CSRF is a separate problem).

6. Charset is the language a letter is written in. The same bytes E0 B0 AE are "మ" in UTF-8 and "à°®" in Windows-1252. A letter without "written in Telugu" on the envelope is read in the reader's default language. The Content-Type: text/html; charset=utf-8 header, or <meta charset> early in the page, is that note on the envelope (Gaps 2).

7. The accessibility tree is the page as heard on the radio. A sighted user sees layout and colour; a screen-reader user hears names, roles and states ("button, Place order"; "list, 5 items"). The browser builds that "radio script" from the DOM and ARIA attributes. A <div> styled as a button looks right on screen and is silent on the radio. Testing with the accessibility tree (Chapter Exercises P9) is listening to the broadcast.

8. Timers are "no sooner than", not "exactly". setTimeout(f, 0) means "run f in a later task, no sooner than 0 ms". The browser may delay it for many reasons: other tasks in the queue, a background tab, battery saving, or the nesting rule that turns repeated zero timers into 4 ms ones (Gaps 4). Code that needs to run "as soon as possible" uses microtasks or MessageChannel; code that needs to run "every frame" uses requestAnimationFrame.

Gaps and misconceptions

What the chapter oversimplifies

1. "The URL standard defines how URLs are parsed": only browsers (and Node) follow it. The chapter teaches the WHATWG URL algorithm. Servers and tools in other languages use different parsers, and they disagree on unusual input. The same three strings, parsed by Node's WHATWG URL, Python's urllib.parse.urlsplit and Java's java.net.URI (real output):

Terminal
WHATWG   "https://tiffinbox.in\\@evil.example/menu" -> host tiffinbox.in path /@evil.example/menu href https://tiffinbox.in/@evil.example/menu
WHATWG   "https://tiffinbox.in\\evil.example/menu" -> host tiffinbox.in path /evil.example/menu href https://tiffinbox.in/evil.example/menu
WHATWG   "https://0x7f.1/" -> host 127.0.0.1 path / href https://127.0.0.1/
Python   'https://tiffinbox.in\\@evil.example/menu' -> host evil.example path /menu
Python   'https://tiffinbox.in\\evil.example/menu' -> host tiffinbox.in\evil.example path /menu
Python   'https://0x7f.1/' -> host 0x7f.1 path /
Java URI "https://tiffinbox.in\@evil.example/menu" -> Illegal character in authority at index 20: https://tiffinbox.in\@evil.example/menu
Java URI "https://0x7f.1/" -> host null path /

For the first string, the browser goes to tiffinbox.in, and Python believes the host is evil.example. For the third, the browser reads 0x7f.1 as the IPv4 address 127.0.0.1 (hex and shortened forms are legal), Python sees a hostname, and Java finds no host at all. This is a parser differential, and it's the basis of real attacks: a server validates a redirect URL with one parser ("the host is tiffinbox.in, allowed") and the browser follows it with another (to evil.example), or a server-side fetcher's allow-list check passes while the request goes to 127.0.0.1 (server-side request forgery). Rule: validate a URL with the same parser that will use it, and compare the parsed host, not the string (drill D1).

2. "The parser decodes the bytes": with what encoding, if nobody says? The chapter describes parsing into the DOM. Before that, bytes must become characters, and if the response doesn't say how, the browser guesses. Serving the same UTF-8 bytes of Telugu text three ways in Chromium (real output):

Terminal
/nocharset    document.characterSet=windows-1252 text='మసాలా దోస ₹89.50'
/metacharset  document.characterSet=UTF-8        text='మసాలా దోస ₹89.50'
/withcharset  document.characterSet=UTF-8        text='మసాలా దోస ₹89.50'

With neither a charset in Content-Type nor a <meta charset>, Chromium (with an English locale) fell back to Windows-1252, and "మసాలా దోస ₹89.50" became "మసాలా దోస ₹89.50", the classic mojibake. The fallback depends on the user's locale, so the same page can look right for the developer and broken for customers. Send charset=utf-8 in the header (authoritative) and put <meta charset="utf-8"> in the first 1,024 bytes (Code walkthrough; drill D2).

3. "Requests carry the page's origin": sometimes the origin is "null". The chapter explains the Origin header in CORS. Some contexts have an opaque origin: sandboxed iframes (without allow-same-origin), data: URLs, file: pages, and some redirects. A request from a sandboxed iframe, observed at the server (real output):

Terminal
sandboxed iframe fetch: read: {"dishes":1}
  server saw Origin='null' Sec-Fetch-Site='cross-site' Sec-Fetch-Mode='cors'
  server saw Origin=None Sec-Fetch-Site='same-origin' Sec-Fetch-Mode='cors'

The frame sent Origin: null, and because the server answered with Access-Control-Allow-Origin: null, the sandboxed frame read the response. Allow-listing null (often added "to make local testing work") lets any sandboxed iframe or data: page on any website read your API's responses, because they all share the same "null" origin. Never allow null. The second line shows the more useful signal: the Sec-Fetch-Site header (Fetch Metadata, Chapter Exercises leaves-out) says cross-site or same-origin reliably, and servers can reject cross-site requests to sensitive endpoints with it (drill D3).

4. "setTimeout(fn, 0) runs as soon as possible": until timers nest five deep. The chapter's event loop treats timers as tasks. The HTML standard adds a clamp: once timers are nested more than five levels deep (a timer callback setting another timer), the minimum delay becomes 4 ms. Measured in Chromium, gaps between ten chained setTimeout(tick, 0) calls (real output):

Terminal
setTimeout(0) chain, gaps in ms: ['0.10', '0.00', '0.00', '0.00', '0.00', '0.00', '4.20', '4.30', '4.10', '4.20']

The first six are effectively immediate; from the sixth nesting on, each takes about 4 ms. A loop that "yields to the browser" with setTimeout(0) to process 10,000 items in chunks spends 40 seconds just waiting on the clamp. Background tabs add much larger throttling. For yielding, use scheduler.postTask or scheduler.yield() where available, or MessageChannel (drill D4).

Common misconceptions

Misconception What's actually true Where it's shown
"If my server's URL parser says the host is X, the browser goes to X." Different parsers resolve some strings to different hosts. Gaps 1; drill D1
"UTF-8 is the default for web pages." Without a declared charset, browsers fall back to a locale-dependent legacy encoding. Gaps 2; drill D2
"Allowing Origin: null is harmless; it's for local files." Every sandboxed frame and data: page has origin null. Gaps 3; drill D3
"Zero-delay timers are free." Nested ones are clamped to 4 ms, and background tabs are throttled harder. Gaps 4; drill D4
"CORS stops requests from other sites." It stops other sites from reading responses; the request still arrives and acts. Explain it differently 5
"Same site means same origin." Sites group origins by registrable domain; cookies follow sites, storage follows origins. Explain it differently 2

Theoretical gaps: the ideas behind the chapter

1. The origin model is a capability system. In capability-based security, what you can do depends on which unforgeable references you hold. The web approximates this: a page's origin is its identity, and it gets the "capabilities" of that origin (its storage, its cookies' privileges, its permissions), while other origins' capabilities are withheld unless explicitly shared (CORS, postMessage). It's an imperfect capability system: ambient authority (cookies attached automatically to requests) is exactly what CSRF exploits, and SameSite cookies are a retrofit to reduce that ambient authority.

2. Parser differentials are a class of vulnerability, not a bug. Whenever two components parse the same input (a URL, an HTTP request, a JSON document, an email address) and act on their own interpretation, any input they interpret differently is a potential attack: URL validation bypasses (Gaps 1), HTTP request smuggling (the Companion to chapter 09), JSON with duplicate keys handled differently by two services. The structural fixes are to parse once and pass the parsed value onward, to use one shared parser, or to reject anything that isn't in a strict, unambiguous subset.

3. Compatibility freezes behaviour, including bugs. The web's first rule is "don't break the web": billions of pages rely on existing behaviour. So quirks survive as specification: the HTML parser's error recovery, the URL parser accepting backslashes and hex IP addresses, Windows-1252 as a fallback, document.write. The WHATWG standards largely describe what browsers do rather than prescribing ideal behaviour, and much of their value is that the quirks are now at least identical everywhere. When designing your own formats and APIs, this is the strongest argument for strictness from day one (the Companion to chapter 09, theoretical gap 3).

4. The web is a distributed system with an untrusted client. Everything in the browser can be read and changed by the user (and by malware or extensions). So the server must treat every request as untrusted, re-validating prices, permissions and state, however good the frontend's checks are. The frontend's validation is for the user's convenience; the server's validation is for correctness and security. TiffinBox's server prices orders itself (stage 11) and never trusts a price sent by a client for exactly this reason.

5. Progressive enhancement is graceful degradation in reverse. Start with HTML that works without scripts (forms, links, server rendering), then add JavaScript to improve it. The alternative, building on JavaScript first and trying to degrade, rarely degrades well. The deeper principle is least power: use the least powerful technology that does the job (HTML before CSS before JavaScript), because less powerful languages are easier to analyse, cache, secure and make accessible. The TiffinBox build's stage 13 follows it.

6. Rendering is a pipeline with a frame budget. At 60 frames per second, each frame has about 16.7 ms for script, style, layout, paint and compositing together. A task longer than that drops frames; one longer than 50 ms is a "long task" that makes input feel sluggish (the basis of the INP metric, chapter 27). Thinking of the main thread as a budget per frame, rather than "as fast as possible", is what turns performance from guesswork into engineering (chapter 18 and 27).

Applying it

Code walkthrough

Browsers implement the URL and encoding standards in C++; jsdom (the DOM used by many JavaScript test runners) uses JavaScript implementations that follow the specifications step by step, which makes them easy to read. Excerpts from whatwg-url 17.3.0 and html-encoding-sniffer 7.0.0, installed from npm.

whatwg-url: where the backslash becomes a slash

In lib/url-state-machine.js, the parser is a state machine with one function per state from the specification. In the authority state, after the scheme's //, it collects characters until something ends the authority:

JavaScript
  } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") ||
             (isSpecial(this.url) && c === p("\\"))) {
    if (this.atSignSeen && this.buffer === "") {
      this.validationErrors?.push("host-missing");
      return failure;
    }
    this.pointer -= countSymbols(this.buffer) + 1;
    this.buffer = "";
    this.state = "host";
  } else {
    this.buffer += cStr;
  }

Read it against Gaps 1:

  • For special schemes (http, https, ws, wss, ftp, file), a backslash ends the authority exactly as / does. So in https://tiffinbox.in\@evil.example/menu, the authority stops at the backslash, before the @ is ever seen as a userinfo separator: the host is tiffinbox.in, and \@evil.example/menu becomes the path (with the backslash turned into /).
  • Python's urlsplit doesn't treat \ as special. It finds the @, takes everything before it as userinfo (tiffinbox.in\) and everything after as the host: evil.example. Two specifications, two hosts.
  • The validationErrors?.push(...) lines are the specification's "validation errors": the parser notes that the input is malformed and carries on anyway, for compatibility (theoretical gap 3). A strict system can use those errors to reject such URLs instead of guessing.

html-encoding-sniffer: deciding what the bytes mean

From lib/html-encoding-sniffer.js, the HTML branch:

JavaScript
    // https://html.spec.whatwg.org/multipage/parsing.html#encoding-sniffing-algorithm
    if (maxPrescanBytes === undefined) {
      maxPrescanBytes = 1024;
    }
    ...
    if (defaultEncoding === undefined) {
      defaultEncoding = "windows-1252";
    }

    encoding = labelToName(getBOMEncoding(uint8Array));

    if (encoding === null && transportLayerEncodingLabel !== undefined) {
      encoding = labelToName(transportLayerEncodingLabel);
    }

    if (encoding === null) {
      encoding = prescanHTMLEncoding(uint8Array, maxPrescanBytes);
    }

    if (encoding === null) {
      encoding = defaultEncoding;
    }

The order is the specification's order of authority:

  1. a byte order mark at the start of the file wins over everything;
  2. then the HTTP header's charset (the "transport layer");
  3. then a prescan of the first 1,024 bytes for <meta charset> or <meta http-equiv="Content-Type">;
  4. otherwise a default: Windows-1252 here, locale-dependent in browsers.

Run on Telugu bytes (real output):

Terminal
no header, no meta: windows-1252
header charset=utf-8: UTF-8
meta after 1,100 bytes of comment: windows-1252

The last line is instructive. With <meta charset> placed after 1,100 bytes of comment, the prescan misses it and this sniffer says Windows-1252. Chromium, given the same page, ended up with UTF-8:

Terminal
/latemeta     document.characterSet=UTF-8 text='మసాలా దోస'

because the full HTML parser has a second chance: when it later meets a <meta charset> that disagrees with the guess, the specification's "change the encoding" step can make the browser re-decode or reload the page. Tools that only run the prescan (link checkers, crawlers, some test environments) don't, so the same page decodes differently in a test and in a browser. The safe rule is the one in Gaps 2: declare the charset in the header and in the first bytes.

Read it yourself

  1. Why does the specification treat \ as / in https: URLs at all?
  2. Why is the prescan limited to 1,024 bytes instead of searching the whole document?

Debugging drills

D1. An open redirect that "checks the host"

After login, TiffinBox redirects to a next URL, checked by a Python service:

Python
if urlsplit(next_url).hostname not in ("tiffinbox.in", "evil-proof.tiffinbox.in"):
    abort(400)
return redirect(next_url)

A security researcher reports that https://evil.example\@tiffinbox.in/ redirects users to evil.example. Both parsers on that string (real output):

Terminal
WHATWG host evil.example href https://evil.example/@tiffinbox.in/
Python host tiffinbox.in

Explain, and fix it.

D2. Customers in Kerala see gibberish on the order page

The order confirmation page shows dish names in Malayalam and Telugu. It looks fine to the developers; some customers report "à´ª…" characters. The page is served by a small service that sets Content-Type: text/html and builds the HTML with a template that starts with a 2 KB comment block of licence text before <head>. A reproduction:

Terminal
/nocharset    document.characterSet=windows-1252 text='మసాలా దోస ₹89.50'

Explain why only some users are affected, and fix it properly.

D3. "We only allow our own origins", and null

TiffinBox's API returns order history with CORS headers built from an allow-list: ["https://tiffinbox.in", "http://localhost:5173", "null"]. Someone added "null" so a developer could open a test page from file://. A reproduction:

Terminal
sandboxed iframe fetch: read: {"dishes":1}
  server saw Origin='null' Sec-Fetch-Site='cross-site' Sec-Fetch-Mode='cors'

Explain the risk, considering that the API also sends Access-Control-Allow-Credentials: true, and fix it.

D4. The kitchen display takes 40 seconds to load 10,000 tickets

To keep the page responsive while rendering many tickets, a developer processes them in chunks of one, yielding with setTimeout(next, 0) between each. Rendering 10,000 tickets now takes about 40 seconds. A measurement of the yielding itself:

Terminal
setTimeout(0) chain, gaps in ms: ['0.10', '0.00', '0.00', '0.00', '0.00', '0.00', '4.20', '4.30', '4.10', '4.20']

Explain the 40 seconds, and fix it without freezing the page.

Career-oriented

Interview prep

Mid level

Q1. What happens, in order, between a user typing tiffinbox.in/menu and seeing the menu? Focus on what the browser does, not the network.

How to get there. The networking half is Volume 1, chapter 9; here, walk through the browser's steps: URL parsing and the origin, navigation and a new document, response handling (status, headers, charset), parsing into the DOM with scripts and styles, rendering, and the accessibility tree. Name a decision at each step.

Q2. Explain the difference between an origin and a site, and give one security mechanism that uses each.

How to get there. Define both precisely (scheme, host and port; scheme and registrable domain from the Public Suffix List), give an example where they differ, then map mechanisms to each and say why.

Senior level

Q3. A product manager wants TiffinBox embedded in partner websites as an iframe so customers can order without leaving them. What do you need to decide and configure?

How to get there. Cover the browser's rules for framing (who may embed whom), cookies in third-party contexts (increasingly blocked), communication (postMessage with origin checks), security headers, and the alternatives (a redirect flow, a popup, an SDK). Be explicit about what breaks in which browsers.

Q4. How would you make the TiffinBox web app resilient to its own mistakes in URL handling across its stack (Java backend, Node frontend server, Python data tools)?

How to get there. Name the risk (parser differentials), then a structural answer: a single canonical representation, one parser per boundary, strict validation, tests with hostile URLs shared by all components.

Staff level

Q5. Your organisation has 20 web properties with inconsistent security headers, cookie settings and CORS configurations. How do you bring them to a common baseline without breaking them?

How to get there. Chapter Exercises S3 defines a header baseline; this question is the rollout. Measure first, roll out in report-only mode, fix what breaks, enforce through shared infrastructure, and keep it from drifting.

Q6. Leadership asks whether TiffinBox should build its customer app as a website, a progressive web app, or native apps. How do you frame the decision?

How to get there. Tie the platform's capabilities (this chapter: what the browser can and can't do) to product needs (reach, discovery, offline, notifications, payments, performance), team skills and cost, and propose a staged plan with evidence.