// How the proxy serves the Flutter web build: cross-origin isolation, cache // policy, validators and precompressed variants. // // Flutter's output names are not content-hashed (main.dart.js, canvaskit/…), so // a long-lived cache needs a versioned address instead. An installed build // carries release.json with its buildId; the shell page then names // `/_v//` as the asset base (see app/web/flutter_bootstrap.js), and // everything under it is immutable for a year. A new install changes the id, // so the next page load fetches the new files. The shell, the bootstrap script // and the small metadata files are revalidated on every load (ETag, 304). import { createReadStream } from "node:fs"; import { readFile, stat } from "node:fs/promises"; import { extname, join, normalize, resolve, sep } from "node:path"; /** * Cross-origin isolation, so the WebAssembly build's renderer (skwasm) can run * multi-threaded (SharedArrayBuffer). `credentialless` rather than * `require-corp`: images and other no-cors loads from other sites (in chat * markdown or a sandboxed HTML preview) still load, without cookies, instead * of being blocked for lacking a Cross-Origin-Resource-Policy header. */ export const ISOLATION_HEADERS = Object.freeze({ "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "credentialless", }); /** The versioned asset prefix: `/_v//`. */ export const VERSIONED_PREFIX = "/_v/"; const IMMUTABLE = "private, max-age=31536000, immutable"; const REVALIDATE = "no-cache"; const BUILD_ID = /^[A-Za-z0-9._-]{1,80}$/; /** Encodings precompressed at install time (scripts/app_build.py), best first. */ const ENCODINGS = [ ["br", ".br"], ["gzip", ".gz"], ]; /** The encodings a request accepts (`q=0` excluded). */ export function acceptedEncodings(header) { const accepted = new Set(); for (const part of String(header ?? "").split(",")) { const [name, ...params] = part.trim().toLowerCase().split(";"); const q = params.map((p) => p.trim()).find((p) => p.startsWith("q=")); if (name && !(q && Number(q.slice(2)) === 0)) accepted.add(name); } return accepted; } export class AppFiles { /** [root] is the web build directory; [mime] maps extensions to types. */ constructor(root, mime) { this.root = resolve(root); this.mime = mime; this._release = { mtimeMs: -1, id: null }; } /** The installed build's id from release.json, or null (a dev build). */ async buildId() { const path = join(this.root, "release.json"); const info = await stat(path).catch(() => null); if (!info?.isFile()) return null; if (info.mtimeMs !== this._release.mtimeMs) { let id = null; try { const value = JSON.parse(await readFile(path, "utf8"))?.buildId; id = typeof value === "string" && BUILD_ID.test(value) ? value : null; } catch { id = null; } this._release = { mtimeMs: info.mtimeMs, id }; } return this._release.id; } /** The asset base the shell page names, or null when the build has no id. */ async assetBase() { const id = await this.buildId(); return id ? `${VERSIONED_PREFIX}${id}/` : null; } /** * A versioned request's file: `{ path, immutable }`, false when it escapes * the root, or null for a malformed one. A request for another build's id * (a tab left open across an install) gets the current file, revalidated. */ async versioned(pathname) { const rest = pathname.slice(VERSIONED_PREFIX.length); const slash = rest.indexOf("/"); if (slash <= 0) return null; const id = rest.slice(0, slash); let rel; try { rel = decodeURIComponent(rest.slice(slash + 1)); } catch { return null; } rel = normalize(rel).replace(/^([/\\])+/, ""); if (!rel || rel === ".") return null; const path = resolve(join(this.root, rel)); if (!path.startsWith(this.root + sep)) return false; return { path, immutable: id === (await this.buildId()) }; } /** * Sends one file of the build: an ETag (304 when it matches), the cache * policy, the isolation headers and, when the client accepts it, the * precompressed variant beside the file. Rejects when the file is missing. */ async send(req, res, path, { immutable = false } = {}) { const info = await stat(path); if (!info.isFile()) throw new Error("not a file"); const etag = `W/"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`; const headers = { ...ISOLATION_HEADERS, "Content-Type": this.mime[extname(path)] ?? "application/octet-stream", "Cache-Control": immutable ? IMMUTABLE : REVALIDATE, ETag: etag, Vary: "Accept-Encoding", }; const match = String(req.headers["if-none-match"] ?? ""); if (match && match.split(",").some((tag) => tag.trim() === etag || tag.trim() === "*")) { res.writeHead(304, headers).end(); return; } let file = path; let size = info.size; const accepted = acceptedEncodings(req.headers["accept-encoding"]); for (const [encoding, suffix] of ENCODINGS) { if (!accepted.has(encoding)) continue; const variant = await stat(path + suffix).catch(() => null); // A variant older than its file is stale (a hand-copied build). if (variant?.isFile() && variant.mtimeMs >= info.mtimeMs) { file = path + suffix; size = variant.size; headers["Content-Encoding"] = encoding; break; } } headers["Content-Length"] = size; res.writeHead(200, headers); if (req.method === "HEAD") { res.end(); return; } await new Promise((done) => { const stream = createReadStream(file); stream.on("error", () => { res.destroy(); done(); }); stream.on("end", done); stream.pipe(res); }); } }