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
mason/forge:mason/114-the-shell-s-27-kb-of-javascript-is-a-cac → main 2 commits fork
6 files
changed +142
−20
src/http/server.ts +7 −3
| @@ -61,6 +61,8 @@ import { sha256 } from "../kernel/hash.ts"; | ||
| 61 | 61 | import { |
| 62 | 62 | assetResponse, |
| 63 | 63 | highlightAsset, |
| 64 | shellAsset, | |
| 65 | shellResponse, | |
| 64 | 66 | stylesheetAsset, |
| 65 | 67 | stylesheetRedirect, |
| 66 | 68 | stylesheetResponse, |
| @@ -514,10 +516,12 @@ export function buildRouter(): Router<Handler> { | ||
| 514 | 516 | router.add("GET", "/sitemap.xml", sitemapXml); |
| 515 | 517 | router.add("GET", "/manifest.webmanifest", webManifest); |
| 516 | 518 | 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. | |
| 520 | 523 | router.add("GET", "/assets/:name.js", async (ctx) => { |
| 524 | if (ctx.params.name === shellAsset().name) return shellResponse(); | |
| 521 | 525 | const asset = await highlightAsset(); |
| 522 | 526 | if (asset === null || ctx.params.name !== asset.name) return notFound(); |
| 523 | 527 | return assetResponse(asset); |
src/web/asset.ts +53 −6
| @@ -1,11 +1,14 @@ | ||
| 1 | 1 | /** |
| 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. | |
| 3 | 4 | * |
| 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. | |
| 9 | 12 | * |
| 10 | 13 | * So at first use we bundle `web/highlight-client.ts` with `Bun.build` (no |
| 11 | 14 | * build step, no toolchain, no dependency: the runtime already has a bundler), |
| @@ -18,6 +21,7 @@ | ||
| 18 | 21 | |
| 19 | 22 | import { sha256 } from "../kernel/hash.ts"; |
| 20 | 23 | import { createLog } from "../kernel/log.ts"; |
| 24 | import { shellJs } from "./client.ts"; | |
| 21 | 25 | import { css } from "./style.ts"; |
| 22 | 26 | |
| 23 | 27 | const log = createLog("web"); |
| @@ -71,6 +75,49 @@ export function assetResponse(asset: BuiltAsset): Response { | ||
| 71 | 75 | }); |
| 72 | 76 | } |
| 73 | 77 | |
| 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 | ||
| 74 | 121 | /** The stylesheet, content-addressed the same way. Hashed once per process. */ |
| 75 | 122 | export interface CssAsset { |
| 76 | 123 | /** The URL path it is served from, content-hashed. */ |
src/web/layout.ts +13 −6
| @@ -23,9 +23,8 @@ import { | ||
| 23 | 23 | THEMES, |
| 24 | 24 | type ThemeName, |
| 25 | 25 | } from "../design/themes.ts"; |
| 26 | import { stylesheetAsset } from "./asset.ts"; | |
| 26 | import { shellAsset, stylesheetAsset } from "./asset.ts"; | |
| 27 | 27 | import { linkHeader, pageLinks } from "./standards.ts"; |
| 28 | import { shellJs } from "./client.ts"; | |
| 29 | 28 | import { |
| 30 | 29 | clearFlashCookie, |
| 31 | 30 | flashCookie, |
| @@ -491,9 +490,7 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 491 | 490 | const theme = ctx.theme ?? options.theme; |
| 492 | 491 | const flash = readFlash(ctx.request); |
| 493 | 492 | const links = pageLinks(ctx); |
| 494 | const scriptJs = options.scriptJs | |
| 495 | ? `${shellJs}\n${options.scriptJs}` | |
| 496 | : shellJs; | |
| 493 | const shellScript = shellAsset(); | |
| 497 | 494 | |
| 498 | 495 | // The body's markup, built before the document so the icons it used can be |
| 499 | 496 | // counted: every `icon()` left a `<use>` behind, and the sprite defining |
| @@ -603,7 +600,17 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 603 | 600 | </head> |
| 604 | 601 | <body> |
| 605 | 602 | ${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} | |
| 607 | 614 | </body> |
| 608 | 615 | </html>`; |
| 609 | 616 |
test/capacity.test.ts +8
| @@ -96,7 +96,13 @@ describe("capacity: only a forge admin reads or changes it", () => { | ||
| 96 | 96 | }; |
| 97 | 97 | }; |
| 98 | 98 | |
| 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 | ||
| 99 | 104 | beforeAll(async () => { |
| 105 | delete process.env["FORGE_CHECK_SHARDS"]; | |
| 100 | 106 | dataDir = await mkdtemp(join(tmpdir(), "forge-capacity-")); |
| 101 | 107 | app = createApp({ dataDir, port: 0 }); |
| 102 | 108 | servers = await serve(app); |
| @@ -127,6 +133,8 @@ describe("capacity: only a forge admin reads or changes it", () => { | ||
| 127 | 133 | }); |
| 128 | 134 | |
| 129 | 135 | afterAll(async () => { |
| 136 | if (inheritedShards !== undefined) | |
| 137 | process.env["FORGE_CHECK_SHARDS"] = inheritedShards; | |
| 130 | 138 | servers.stop(); |
| 131 | 139 | app.close(); |
| 132 | 140 | 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", () => { | ||
| 505 | 505 | ); |
| 506 | 506 | expect(running).toContain("new EventSource(url)"); |
| 507 | 507 | 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-)/); | |
| 509 | 510 | |
| 510 | 511 | const done = await settled(jobPath.split("/").pop()!); |
| 511 | 512 | expect(done?.stage).toBe("done"); |
test/web.test.ts +59 −4
| @@ -14,7 +14,8 @@ import { | ||
| 14 | 14 | type IconName, |
| 15 | 15 | } from "../src/web/icons.ts"; |
| 16 | 16 | 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"; | |
| 18 | 19 | import { securityFloor } from "../src/http/respond.ts"; |
| 19 | 20 | import { THEME_NAMES } from "../src/design/themes.ts"; |
| 20 | 21 | import { sha256 } from "../src/kernel/hash.ts"; |
| @@ -285,6 +286,57 @@ describe("a page ships each drawing once", () => { | ||
| 285 | 286 | expect(home).not.toContain('id="i-webhook"'); |
| 286 | 287 | }); |
| 287 | 288 | |
| 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 | ||
| 288 | 340 | test("the thread fragment inlines its own drawings", async () => { |
| 289 | 341 | await fetch(`${base}/ada/engine/issues/1/comments`, { |
| 290 | 342 | method: "POST", |
| @@ -383,9 +435,12 @@ describe("web pages end to end", () => { | ||
| 383 | 435 | expect(text).toContain( |
| 384 | 436 | '<script type="application/json" id="palette-index">', |
| 385 | 437 | ); |
| 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("); | |
| 389 | 444 | }); |
| 390 | 445 | |
| 391 | 446 | test("stylesheet is content-addressed and immutable, at the path the page names", async () => { |
new above
offline