Workbench / The TiffinBox Build
S12 · V2·12
One Origin for App and API
Volume 2 begins. TiffinBox gets its first web page, served by stage 9's server from the same origin as the API, so the browser's same-origin policy works for TiffinBox instead of against it and no CORS is needed. Every response now carries a security baseline (a strict Content Security Policy, no framing, no MIME sniffing, UTF-8 declared), static files are served through a whitelist that stops path tricks and symlinks, and state-changing requests from any other origin are refused using the browser's Fetch Metadata. A check in real Chromium finds that a page on another port counts as the "same site", which a first version of the rule allowed.
Stage 12: one origin for app and API
The brief
What you'll build.
- Static file serving in the server:
serve DIR PORT RULES WEBserves the frontend from aweb/directory on the same origin as the API, through a strict path whitelist (no.., no hidden files, no unknown types, no symlinks leaving the root). - A security header baseline on every response, API and pages alike:
Content-Security-Policy(same-origin only, no inline script, no framing),X-Content-Type-Options: nosniff,Referrer-Policy,Cross-Origin-Opener-Policy,Cross-Origin-Resource-Policy, andcharset=utf-8on every text response. - A Fetch Metadata rule: any non-GET request whose
Sec-Fetch-Siteisn'tsame-origin(ornone) is refused with 403 before it reaches a handler. - The first page,
web/index.htmlandweb/app.css, with Telugu and Malayalam text. WebTest(3 tests, 13 server tests in total) andweb-tests/stage12.py, a Playwright script that checks the rules in real Chromium.- The Volume 2 plan (below) and ADR-0014.
Why a real company needs this. The decision "where is the frontend served from?" sets the security model for years. Serve it from a different origin than the API, and every call needs CORS, cookies need SameSite=None, and every misconfiguration is a hole (the Companion's drill D3). Serve it from the same origin, and the browser's default rules already protect you. The header baseline and the Fetch Metadata rule are cheap, and they turn whole classes of attacks (cross-site scripting through injected scripts, clickjacking, cross-site request forgery) into errors in the browser's console.
Why now. Chapter 12 is the browser's model: URLs, origins and sites, documents, the same-origin policy, CORS, cookies and CSP. Before writing any frontend code, decide how that code relates to the server.
What you'll have at the end.
- the frontend served from the API's origin, with a baseline on every response;
- 3 new server tests and a real-browser check script;
- ADR-0014: one origin for app and API, and the baseline;
- the stage plan for Volume 2.
The plan for Volume 2
Each stage follows its chapter. By the end of Volume 2, TiffinBox has a customer web app and a kitchen display, both talking to the Volume 1 server.
| Stage | Chapter | TiffinBox gains | The question it answers |
|---|---|---|---|
| 12 | 12 The web platform | The frontend served from the API's origin; a security header baseline; Fetch Metadata | Which browser rules work for us, and which against us? |
| 13 | 13 HTML | A menu and order page that works with no JavaScript at all, semantic and valid | What does the platform give us before we write any script? |
| 14 | 14 CSS | Design tokens, a responsive layout, dark mode, contrast checked | Can the design survive 390 px, 1,200 px and a user's settings? |
| 15 | 15 JavaScript | Search-as-you-type over the HTML page, with debouncing and cancelled stale requests | How does code stay correct when responses arrive out of order? |
| 16 | 16 TypeScript | The API contract as types, matching the server's sealed lifecycle | Can the compiler catch a contract change? |
| 17 | 17 DOM and browser APIs | The kitchen display: live tickets, keyboard control, updates without polling storms | How do we update a live page efficiently? |
| 18 | 18 Browser internals | The kitchen display profiled: layout thrashing found and removed | Where does a frame's time go? |
| 19 | 19 Frontend networking | Retries with idempotency keys from the browser, timeouts, HTTP caching with ETags | What happens when the network fails mid-order? |
| 20 | 20 Accessibility | Keyboard-only and screen-reader flows, live regions for order status, automated audits | Can everyone order a meal? |
| 21 | 21 UI architecture | Components, data flow and boundaries for the customer app, decided and written down | Where does each piece of state live? |
| 22 | 22 React | The kitchen display in React, on stage 21's core | What does a framework add, and cost, against the plain view? |
| 23 | 23 Angular | The kitchen display rebuilt in Angular | When does a full framework pay for itself? |
| 24 | 24 Full-stack frameworks | Server-side rendering for the public menu pages | Which pages should render on the server? |
| 25 | 25 State management | One store for every view, the filter in the URL, the theme as a remembered preference | Does every piece of state have one home, the right one? |
| 26 | 26 Frontend testing | Unit, component, end-to-end and contract tests against the real server | Which tests catch which bugs, at what cost? |
| 27 | 27 Frontend performance | Budgets for LCP, INP and bundle size, enforced in CI | What does fast mean, in numbers? |
| 28 | 28 Frontend security | A strict CSP with nonces or hashes, Trusted Types, hostile dish names | Can a malicious menu entry run code? |
| 29 | 29 PWAs, workers, WebAssembly | An offline menu, background sync of orders, a worker for search | Can a customer order on a train through a tunnel? |
| 30 | 30 Build tooling | A workspace with shared types, reproducible builds, bundle analysis | What exactly ships, and can we rebuild it? |
| 31 | 31 Frontend deployment | Hashed assets, cache headers, atomic releases and rollback | How do we ship without breaking open tabs? |
| 32 | 32 Frontend observability | Real-user metrics and errors beaconed to the server, with source maps | What are customers actually experiencing? |
| 33 | 33 Frontend projects | Release 0.2: the web app and kitchen display, end to end, with evidence | Can we defend every frontend decision? |
Theory to own
- Origin, site, and why the difference matters here. Is
http://127.0.0.1:18301the same origin ashttp://127.0.0.1:18300? The same site? (Chapter: "Origins"; "Sites and schemeful sites"; Companion, Interview prep Q2.) - What the same-origin policy gives for free. If the frontend and API share an origin, what can a page on another origin do to the API, and what can't it do? (Chapter: "The browser security model".)
- The header baseline. For each of
default-src 'self',script-src 'self',frame-ancestors 'none'andnosniff, name the attack it blocks. (Chapter: "The browser security model"; Chapter Exercises P10.) - Fetch Metadata. What do
Sec-Fetch-Sitevaluessame-origin,same-site,cross-siteandnonemean, and why can't a page forge them? (Chapter Exercises leaves out "Fetch Metadata and defence in depth on the server".) - Path traversal. Which requests could escape a static file root, and why check the real path after normalising? (Volume 1, stage 6: untrusted input.)
Build it
Step 1: decide the origin, and write it down
Before any code, decide: the frontend's files are served by the TiffinBox server itself, from the same scheme, host and port as the API. Write ADR-0014 with the alternatives:
- same origin (chosen): no CORS, cookies can be
SameSite=Strictlater, the same-origin policy protects the API by default; - a separate static host or CDN origin (
app.tiffinbox.incallingapi.tiffinbox.in): independent deploys and caching, but CORS on every call, a second origin to secure, and cookies shared across a site rather than an origin; - a CDN in front of one origin: the same origin to the browser, with caching at the edge (the likely future, stage 31).
Checkpoint. The ADR names the security consequences of each option, not just deployment convenience.
Step 2: serve static files safely
Add a constructor parameter webRoot (resolved to its real path) and a staticFile(path) route for any GET that isn't an API route:
/means/index.html;- the path must match
(/[A-Za-z0-9_-][A-Za-z0-9._-]*)+and contain no..: no empty segments, no leading dots, no backslashes or percent signs; - after resolving under the root, the file must exist, be a regular file, and its real path must still start with the root;
- the extension must be in a small table of types (
html,css,js,json,svg,png,webmanifest,txt); anything else is 404; - responses carry
Cache-Control: no-cachefor now (stage 31 adds hashed, long-cached assets).
Static responses carry raw bytes, so Response gains an optional byte[] body, and only text types get charset=utf-8.
Checkpoint. /, /app.css are served; /../outside.txt, /%2e%2e/outside.txt, /.env, /notes.md, /link.txt (a symlink out of the root), //etc/passwd, /app.css/ and /a\..\outside.txt are all refused.
Step 3: a security baseline on every response
Write every response through one method that adds the baseline headers, so no route can forget them:
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Checkpoint. /, /app.css and /health all carry the headers, and HTML is text/html; charset=utf-8.
Step 4: refuse state-changing requests from other origins
At the top of route, read Sec-Fetch-Site. Allow GETs from anywhere. For every other method, allow only same-origin and none, and requests without the header (non-browser clients); answer everything else with 403. Start with the obvious rule (refuse only cross-site), and test it in step 5.
Checkpoint. A raw POST /orders with Sec-Fetch-Site: cross-site gets 403; a cross-site GET of /menu/search gets 200 with no CORS headers.
Step 5: check it in a real browser
Write web-tests/stage12.py: start the server with the web root, start a second small server on another port that serves three hostile pages (one that fetches the menu, one that auto-submits a form POST to /orders, one that frames TiffinBox), then use Playwright with Chromium to:
- load TiffinBox and check
document.characterSet, the heading, and a same-originfetch('/version'); - inject an inline script and check it doesn't run (and capture the CSP console message);
- visit each hostile page and record what happened.
Checkpoint. Every hostile page fails in the way you predicted, and the same-origin page works.
Senior and architect lens
1. Choose the architecture that makes the platform's defaults work for you. Same origin means the browser's built-in rules protect the API with no configuration. Many teams split origins for deployment convenience and then spend years maintaining CORS allow-lists and fixing credentialed-CORS mistakes. The deployment benefits are available without splitting (a CDN in front of one origin).
2. ADR-0014: one origin, and a baseline on every response. Write it with these points:
- Decision: the frontend is served by the TiffinBox server from the API's origin; every response carries the security baseline; non-GET requests from browsers must be
same-origin. - Alternatives: separate origins with CORS; a static host on a subdomain. Rejected for CORS cost and risk.
- Consequences: no CORS configuration exists; all CSS and JavaScript live in files (no inline code); third-party scripts, fonts and analytics need an explicit CSP change, reviewed.
- Revisit when: a CDN is introduced (stage 31: same origin through the CDN), or a partner needs to call the API from its own pages (then a separate, CORS-enabled public API, not a loosened app API).
3. Make security rules impossible to forget. The headers are added in the single method that writes responses, and the Fetch Metadata check runs before routing. New endpoints are protected without anyone remembering to protect them. Security that depends on each developer doing the right thing on each endpoint eventually fails.
4. Test security in the real environment. The same-site surprise only appeared in a real browser. The same is true of CSP (browsers differ in edge cases), cookies (third-party cookie policies differ by browser), and framing. Keep a small browser-based security check in CI; it's cheap, and it tests what attackers will actually use.
5. A strict CSP is easiest on day one. Adding script-src 'self' to an existing application means finding and moving every inline script and event handler attribute, often hundreds. Starting with it means every page is written to fit. Stage 28 tightens it further.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| a real menu page | index.html is a placeholder; menu search returns JSON |
stage 13 (HTML pages rendered by the server) |
| scripts on the page | none yet; script-src 'self' will require files, not inline code |
stage 15 |
| caching static files | everything is no-cache |
stage 31 (hashed assets, long cache lifetimes) |
| login and cookies | no sessions yet | Volume 3 (Spring Security), keeping same-origin |
| third-party analytics or fonts | blocked by the CSP | a reviewed CSP change; stage 32 sends metrics to our own origin instead |
Evidence
serve DIR PORT RULES WEBservesweb/from the API's origin; the server build printstests: 13 passed.web-tests/stage12.pyoutput, before and after thesame-sitefix, is in the README.curl -sI http://127.0.0.1:PORT/andcurl -sI .../healthshow the baseline headers on both (paste them).- Each hostile path from step 2 is listed in the README with the server's answer.
- ADR-0014 is committed, along with the Volume 2 plan.
Carry forward
- One origin for app and API (ADR-0014) holds for all of Volume 2 and Volume 3; no CORS configuration exists anywhere.
- The baseline headers apply to every response, and the CSP's
script-src 'self'shapes how every later stage writes JavaScript. - Fetch Metadata protects every state-changing endpoint added later, including stage 17's kitchen actions and Volume 3's login.
web-tests/is where real-browser checks live; every Volume 2 stage adds to it.