Public: anyone can read this; the crew can change it.

The shell's 27 KB of JavaScript is a cached file, not re-sent with every page #1033

Closed opened this
Closed without merging

mason/forge:mason/114-the-shell-s-27-kb-of-javascript-is-a-cac → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +142 −20
src/http/server.ts +7 −3
@@ -61,6 +61,8 @@ import { sha256 } from "../kernel/hash.ts";
6161 import {
6262 assetResponse,
6363 highlightAsset,
64 shellAsset,
65 shellResponse,
6466 stylesheetAsset,
6567 stylesheetRedirect,
6668 stylesheetResponse,
@@ -514,10 +516,12 @@ export function buildRouter(): Router<Handler> {
514516 router.add("GET", "/sitemap.xml", sitemapXml);
515517 router.add("GET", "/manifest.webmanifest", webManifest);
516518 router.add("GET", "/icons/:spec.png", iconPng);
517 // The highlighter bundle, content-addressed. A stale hash is a 404 rather
518 // than a redirect: the page that asked for it names the hash it was built
519 // with, so a miss means an old tab, and an old tab should reload.
519 // The shell's script and the highlighter bundle, content-addressed. A
520 // stale hash is a 404 rather than a redirect: the page that asked for it
521 // names the hash it was built with, so a miss means an old tab, and an old
522 // tab degrades to plain HTML until it reloads.
520523 router.add("GET", "/assets/:name.js", async (ctx) => {
524 if (ctx.params.name === shellAsset().name) return shellResponse();
521525 const asset = await highlightAsset();
522526 if (asset === null || ctx.params.name !== asset.name) return notFound();
523527 return assetResponse(asset);
src/web/asset.ts +53 −6
@@ -1,11 +1,14 @@
11 /**
2 * The one script this forge ships as a file.
2 * The files this forge ships content-addressed: the highlighter bundle, the
3 * shell's script, and the stylesheet.
34 *
4 * Everything else on the web is server-rendered HTML plus a nonce'd inline
5 * script, and that is the right shape for a page: nothing to fetch, nothing to
6 * cache-bust, nothing to get out of sync with the server. The editor is the
7 * exception — it needs the *tokenizer itself* in the browser, and inlining two
8 * thousand lines of it into every editor page would be absurd.
5 * A page's own script is server-rendered beside its HTML in a nonce'd inline
6 * block, and that is the right shape for it: nothing to fetch, nothing to
7 * cache-bust, nothing to get out of sync with the server. Two scripts are the
8 * exception. The shell's is identical on every page, so re-sending it with
9 * each one is waste. And the editor needs the *tokenizer itself* in the
10 * browser — inlining two thousand lines of it into every editor page would be
11 * absurd.
912 *
1013 * So at first use we bundle `web/highlight-client.ts` with `Bun.build` (no
1114 * build step, no toolchain, no dependency: the runtime already has a bundler),
@@ -18,6 +21,7 @@
1821
1922 import { sha256 } from "../kernel/hash.ts";
2023 import { createLog } from "../kernel/log.ts";
24 import { shellJs } from "./client.ts";
2125 import { css } from "./style.ts";
2226
2327 const log = createLog("web");
@@ -71,6 +75,49 @@ export function assetResponse(asset: BuiltAsset): Response {
7175 });
7276 }
7377
78 /**
79 * The shell's script (`shellJs`), content-addressed the same way. It began
80 * inline, but it is the same bytes on every page — a quarter of a signed-in
81 * page and most of a signed-out one — so it is a file the browser keeps.
82 *
83 * It is linked as a *classic* script, not a module: a classic `<script src>`
84 * runs in document order, so a page's own inline script placed after it
85 * still runs after the shell, exactly as it did when the two were one block.
86 * The tag carries the page's nonce, so the CSP does not relax, and an
87 * `integrity` hash, so the bytes run are the bytes hashed. Hashed once per
88 * process.
89 */
90 export interface ShellAsset {
91 /** The URL path it is served from, content-hashed. */
92 path: string;
93 /** The `:name` the route matches, i.e. the path's basename without `.js`. */
94 name: string;
95 /** Subresource integrity for the `<script>` tag. */
96 integrity: string;
97 }
98
99 let shellAssetMemo: ShellAsset | null = null;
100
101 export function shellAsset(): ShellAsset {
102 if (shellAssetMemo === null) {
103 const name = `shell-${sha256(shellJs).slice(0, 16)}`;
104 const digest = new Bun.CryptoHasher("sha256")
105 .update(shellJs)
106 .digest("base64");
107 shellAssetMemo = {
108 path: `/assets/${name}.js`,
109 name,
110 integrity: `sha256-${digest}`,
111 };
112 }
113 return shellAssetMemo;
114 }
115
116 /** The response for a hit on the shell script: immutable, because it is. */
117 export function shellResponse(): Response {
118 return assetResponse({ ...shellAsset(), code: shellJs });
119 }
120
74121 /** The stylesheet, content-addressed the same way. Hashed once per process. */
75122 export interface CssAsset {
76123 /** The URL path it is served from, content-hashed. */
src/web/layout.ts +13 −6
@@ -23,9 +23,8 @@ import {
2323 THEMES,
2424 type ThemeName,
2525 } from "../design/themes.ts";
26 import { stylesheetAsset } from "./asset.ts";
26 import { shellAsset, stylesheetAsset } from "./asset.ts";
2727 import { linkHeader, pageLinks } from "./standards.ts";
28 import { shellJs } from "./client.ts";
2928 import {
3029 clearFlashCookie,
3130 flashCookie,
@@ -491,9 +490,7 @@ export function page(options: PageOptions, status = 200): Response {
491490 const theme = ctx.theme ?? options.theme;
492491 const flash = readFlash(ctx.request);
493492 const links = pageLinks(ctx);
494 const scriptJs = options.scriptJs
495 ? `${shellJs}\n${options.scriptJs}`
496 : shellJs;
493 const shellScript = shellAsset();
497494
498495 // The body's markup, built before the document so the icons it used can be
499496 // counted: every `icon()` left a `<use>` behind, and the sprite defining
@@ -603,7 +600,17 @@ export function page(options: PageOptions, status = 200): Response {
603600 </head>
604601 <body>
605602 ${shell}${iconSprite(shell.text)}
606 ${raw(`<script nonce="${nonce}">${scriptJs}</script>`)}
603 ${
604 // The shell is a cached file, linked as a classic script so it runs
605 // in document order: the page's own inline script below still runs
606 // after everything the shell set up. Both carry the nonce.
607 raw(
608 `<script nonce="${nonce}" src="${shellScript.path}" integrity="${shellScript.integrity}"></script>`,
609 )
610 }
611 ${options.scriptJs
612 ? raw(`<script nonce="${nonce}">${options.scriptJs}</script>`)
613 : null}
607614 </body>
608615 </html>`;
609616
test/capacity.test.ts +8
@@ -96,7 +96,13 @@ describe("capacity: only a forge admin reads or changes it", () => {
9696 };
9797 };
9898
99 // The forge's own check runs this suite with FORGE_CHECK_SHARDS set (it
100 // is the shard runner's), and that would be the shards' boot default here:
101 // a reset would return to it, not to nothing.
102 const inheritedShards = process.env["FORGE_CHECK_SHARDS"];
103
99104 beforeAll(async () => {
105 delete process.env["FORGE_CHECK_SHARDS"];
100106 dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-"));
101107 app = createApp({ dataDir, port: 0 });
102108 servers = await serve(app);
@@ -127,6 +133,8 @@ describe("capacity: only a forge admin reads or changes it", () => {
127133 });
128134
129135 afterAll(async () => {
136 if (inheritedShards !== undefined)
137 process.env["FORGE_CHECK_SHARDS"] = inheritedShards;
130138 servers.stop();
131139 app.close();
132140 await rm(dataDir, { recursive: true, force: true });
test/web-browse.test.ts +2 −1
@@ -505,7 +505,8 @@ describe("browsing an origin repository on the web", () => {
505505 );
506506 expect(running).toContain("new EventSource(url)");
507507 expect(running).toMatch(/<script nonce="[^"]+">/);
508 expect(running).not.toMatch(/<script[^>]*src=/);
508 // The only file it links is the shell's, cached on every page.
509 expect(running).not.toMatch(/<script[^>]*src="(?!\/assets\/shell-)/);
509510
510511 const done = await settled(jobPath.split("/").pop()!);
511512 expect(done?.stage).toBe("done");
test/web.test.ts +59 −4
@@ -14,7 +14,8 @@ import {
1414 type IconName,
1515 } from "../src/web/icons.ts";
1616 import { renderMarkdown } from "../src/web/markdown.ts";
17 import { highlightAsset } from "../src/web/asset.ts";
17 import { highlightAsset, shellAsset } from "../src/web/asset.ts";
18 import { liveRegionsJs, shellJs } from "../src/web/client.ts";
1819 import { securityFloor } from "../src/http/respond.ts";
1920 import { THEME_NAMES } from "../src/design/themes.ts";
2021 import { sha256 } from "../src/kernel/hash.ts";
@@ -285,6 +286,57 @@ describe("a page ships each drawing once", () => {
285286 expect(home).not.toContain('id="i-webhook"');
286287 });
287288
289 test("the shell's script is a cached file the page links, not inline text", async () => {
290 const res = await fetch(base, { headers: { cookie } });
291 const text = await res.text();
292 const shell = shellAsset();
293 // The studio front door carries a page script of its own: both halves.
294 expect(text).toContain(liveRegionsJs);
295 // The shell's source is gone from the HTML: every page is that much lighter.
296 expect(shellJs.length).toBeGreaterThan(25_000);
297 expect(text).not.toContain(shellJs.slice(0, 400));
298 expect(text).not.toContain("function rankPalette(");
299
300 // Linked as a classic script (no type="module", no defer, no async), so
301 // it runs in document order: before the page's own inline script.
302 const tags = [...text.matchAll(/<script\b([^>]*)>/g)].map((m) => m[1]!);
303 const nonce = /'nonce-([^']+)'/.exec(
304 res.headers.get("content-security-policy") ?? "",
305 )![1];
306 const linked = tags.findIndex((t) => t.includes(`src="${shell.path}"`));
307 expect(linked).toBeGreaterThanOrEqual(0);
308 expect(tags[linked]).toContain(`nonce="${nonce}"`);
309 expect(tags[linked]).toContain(`integrity="${shell.integrity}"`);
310 expect(tags[linked]).not.toMatch(/\b(type="module"|defer|async)\b/);
311 const inline = tags.findIndex((t, i) => i > linked && !t.includes("src="));
312 expect(inline).toBeGreaterThan(linked);
313 expect(tags[inline]).toBe(` nonce="${nonce}"`);
314
315 // The policy does not loosen for it: the nonce admits the file.
316 const policy = res.headers.get("content-security-policy")!;
317 expect(policy).not.toContain("unsafe-inline");
318 expect(policy).toMatch(/script-src 'nonce-[^']+';/);
319 });
320
321 test("the shell's file is content-addressed, immutable, and what the integrity names", async () => {
322 const shell = shellAsset();
323 expect(shell.path).toBe(`/assets/shell-${sha256(shellJs).slice(0, 16)}.js`);
324 const res = await fetch(`${base}${shell.path}`);
325 expect(res.status).toBe(200);
326 expect(res.headers.get("content-type")).toContain("text/javascript");
327 expect(res.headers.get("cache-control")).toBe(
328 "public, max-age=31536000, immutable",
329 );
330 const body = await res.text();
331 expect(body).toBe(shellJs);
332 const digest = new Bun.CryptoHasher("sha256").update(body).digest("base64");
333 expect(shell.integrity).toBe(`sha256-${digest}`);
334 // An old tab's hash is a miss, and degrades to plain HTML.
335 expect(
336 (await fetch(`${base}/assets/shell-0000000000000000.js`)).status,
337 ).toBe(404);
338 });
339
288340 test("the thread fragment inlines its own drawings", async () => {
289341 await fetch(`${base}/ada/engine/issues/1/comments`, {
290342 method: "POST",
@@ -383,9 +435,12 @@ describe("web pages end to end", () => {
383435 expect(text).toContain(
384436 '<script type="application/json" id="palette-index">',
385437 );
386 // The script carries the scorer and consumes Escape itself.
387 expect(text).toContain("function fuzzyScore(");
388 expect(text).toContain("function openModal(");
438 // The shell script the page links carries the scorer and consumes Escape itself.
439 const src = /<script[^>]*src="(\/assets\/shell-[0-9a-f]+\.js)"/.exec(text);
440 expect(src).not.toBeNull();
441 const shell = await (await fetch(`${base}${src![1]}`)).text();
442 expect(shell).toContain("function fuzzyScore(");
443 expect(shell).toContain("function openModal(");
389444 });
390445
391446 test("stylesheet is content-addressed and immutable, at the path the page names", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs