Web: WebAssembly build served cross-origin isolated, immutable and precompressed
The web app is built with --wasm (skwasm, JS/CanvasKit fallback beside it). The proxy serves it with COOP same-origin + COEP credentialless so skwasm renders on a worker; an installed build loads from /_v/<buildId>/ cached as immutable, other files revalidate by ETag, and the installer precompresses .br/.gz variants the proxy sends by Accept-Encoding. The bootstrap no longer registers Flutter's deprecated service worker (a reload per install). Read aloud on the web uses the Web Speech API through package:web: the flutter_tts web plugin's interop casts fail under wasm. Bench kit: isolation and headed modes, renderer and memory reporting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,13 @@ node serve.mjs --port 8082 --host 0.0.0.0 --pipelines 127.0.0.1:8080 \
|
||||
|
||||
- `--root` is the web app (default: `../app/build/web`). Without a build, the
|
||||
page explains how to make one (`./install --web`).
|
||||
- The app is served cross-origin isolated (COOP `same-origin`, COEP
|
||||
`credentialless`), so its WebAssembly renderer runs multi-threaded. An
|
||||
installed build (with `release.json`) loads its files from
|
||||
`/_v/<buildId>/`, cached as immutable; the shell is never cached and the
|
||||
other files revalidate by ETag. Files precompressed by the installer
|
||||
(`.br`, `.gz`, `scripts/precompress_web.mjs`) are sent to browsers that
|
||||
accept them. See `src/appFiles.js`.
|
||||
- `--updates` serves the Android app's `version.json` and APK at `/updates/`
|
||||
(`./install --apk`), behind the same sign-in.
|
||||
- The password lives in `~/.config/pipelines/web-auth.json`
|
||||
|
||||
+28
-7
@@ -44,6 +44,7 @@ import {
|
||||
} from "./src/webSecurity.js";
|
||||
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
|
||||
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
|
||||
import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.js";
|
||||
|
||||
// The proxy's own directory holds the sign-in page's icons.
|
||||
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
|
||||
@@ -350,6 +351,7 @@ const MIME = {
|
||||
// route still serves the shell, while an asset-looking path elsewhere (`/nope.js`)
|
||||
// stays an honest 404 and a real file (`/src/app.js`) is still served.
|
||||
const ASSET_EXTENSIONS = new Set([...Object.keys(MIME), ".woff", ".woff2", ".txt"]);
|
||||
const appFiles = new AppFiles(ROOT, MIME);
|
||||
const PAGE_PREFIXES = new Set(["pipelines", "runs", "chat", "settings", "templates"]);
|
||||
|
||||
/** The decoded first path segment, or "" for the root. */
|
||||
@@ -441,8 +443,13 @@ async function serveIndex(res) {
|
||||
// A deep URL such as /runs/440 would otherwise resolve the shell's relative
|
||||
// `./src/app.js` against /runs/. A root <base> keeps the shell's own asset URLs
|
||||
// absolute without changing the address bar (and without editing index.html).
|
||||
const body = html.replace(/<head>/i, '<head>\n <base href="/" />');
|
||||
// An installed build also names its versioned, immutable asset base, which
|
||||
// the app's flutter_bootstrap.js reads (src/appFiles.js).
|
||||
const base = await appFiles.assetBase();
|
||||
const meta = base ? `\n <meta name="pipelines-asset-base" content="${base}" />` : "";
|
||||
const body = html.replace(/<head>/i, `<head>\n <base href="/" />${meta}`);
|
||||
res.writeHead(200, {
|
||||
...ISOLATION_HEADERS,
|
||||
"Content-Type": MIME[".html"],
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
@@ -630,6 +637,20 @@ const server = createServer(async (req, res) => {
|
||||
const assetLike = ASSET_EXTENSIONS.has(extname(pathname).toLowerCase());
|
||||
const pageLike = PAGE_PREFIXES.has(firstSegment(pathname));
|
||||
const serveShell = pageLike || !assetLike;
|
||||
if (pathname.startsWith(VERSIONED_PREFIX)) {
|
||||
const file = await appFiles.versioned(pathname);
|
||||
if (file === false) {
|
||||
res.writeHead(403).end("Forbidden");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!file) throw new Error("malformed");
|
||||
await appFiles.send(req, res, file.path, { immutable: file.immutable });
|
||||
} catch {
|
||||
if (!res.headersSent) res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const target = resolvePath(req.url ?? "/");
|
||||
if (target === null) {
|
||||
// A malformed percent escape is an unknown page route, not a handler throw.
|
||||
@@ -650,12 +671,12 @@ const server = createServer(async (req, res) => {
|
||||
let path = target;
|
||||
const info = await stat(path).catch(() => null);
|
||||
if (info?.isDirectory()) path = join(path, "index.html");
|
||||
const body = await readFile(path);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": MIME[extname(path)] ?? "application/octet-stream",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
res.end(body);
|
||||
// The shell itself always goes through serveIndex (no-store, base tags).
|
||||
if (path === join(ROOT, "index.html")) {
|
||||
await serveIndex(res);
|
||||
return;
|
||||
}
|
||||
await appFiles.send(req, res, path);
|
||||
} catch {
|
||||
if (serveShell) {
|
||||
await serveIndex(res).catch(() => {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// 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/<buildId>/` 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/<buildId>/<file>`. */
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtemp, mkdir, utimes, writeFile } from "node:fs/promises";
|
||||
import { get } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import net from "node:net";
|
||||
import { brotliCompressSync, brotliDecompressSync, gzipSync } from "node:zlib";
|
||||
import { acceptedEncodings } from "../src/appFiles.js";
|
||||
|
||||
const here = fileURLToPath(new URL("..", import.meta.url));
|
||||
|
||||
async function freePort() {
|
||||
const server = net.createServer().listen(0, "127.0.0.1");
|
||||
await new Promise((done) => server.once("listening", done));
|
||||
const { port } = server.address();
|
||||
await new Promise((done) => server.close(done));
|
||||
return port;
|
||||
}
|
||||
|
||||
async function start(root) {
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", root], {
|
||||
cwd: here,
|
||||
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
|
||||
stdio: ["ignore", "pipe", "inherit"],
|
||||
});
|
||||
await new Promise((done) => child.stdout.once("data", done));
|
||||
return { port, stop: () => child.kill() };
|
||||
}
|
||||
|
||||
/** A raw GET (fetch would decode the body and hide Content-Encoding). */
|
||||
function request(port, path, headers = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
get({ host: "127.0.0.1", port, path, headers }, (res) => {
|
||||
const chunks = [];
|
||||
res.on("data", (chunk) => chunks.push(chunk));
|
||||
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
|
||||
}).on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function build({ release = true } = {}) {
|
||||
const root = join(await mkdtemp(join(tmpdir(), "app-files-")), "app");
|
||||
await mkdir(join(root, "canvaskit"), { recursive: true });
|
||||
await writeFile(join(root, "index.html"), '<!DOCTYPE html><html><head><base href="/"></head><body></body></html>');
|
||||
await writeFile(join(root, "flutter_bootstrap.js"), "bootstrap()");
|
||||
const script = "main();".repeat(400);
|
||||
await writeFile(join(root, "main.dart.js"), script);
|
||||
await writeFile(join(root, "main.dart.js.br"), brotliCompressSync(script));
|
||||
await writeFile(join(root, "main.dart.js.gz"), gzipSync(script));
|
||||
await writeFile(join(root, "canvaskit", "skwasm.wasm"), "wasm");
|
||||
if (release) await writeFile(join(root, "release.json"), '{"schema":1,"platform":"web","buildId":"web-abc123"}');
|
||||
return { root, script };
|
||||
}
|
||||
|
||||
test("the shell is isolated, uncached and names the versioned asset base", async (t) => {
|
||||
const { root } = await build();
|
||||
const server = await start(root);
|
||||
t.after(server.stop);
|
||||
for (const path of ["/", "/chat/7"]) {
|
||||
const page = await request(server.port, path);
|
||||
assert.equal(page.status, 200);
|
||||
assert.equal(page.headers["cross-origin-opener-policy"], "same-origin");
|
||||
assert.equal(page.headers["cross-origin-embedder-policy"], "credentialless");
|
||||
assert.equal(page.headers["cache-control"], "no-store");
|
||||
assert.match(page.body.toString(), /<meta name="pipelines-asset-base" content="\/_v\/web-abc123\/" \/>/);
|
||||
}
|
||||
});
|
||||
|
||||
test("versioned assets of the current build are immutable; another build's revalidate", async (t) => {
|
||||
const { root, script } = await build();
|
||||
const server = await start(root);
|
||||
t.after(server.stop);
|
||||
const current = await request(server.port, "/_v/web-abc123/main.dart.js", { "accept-encoding": "gzip, br" });
|
||||
assert.equal(current.status, 200);
|
||||
assert.equal(current.headers["cache-control"], "private, max-age=31536000, immutable");
|
||||
assert.equal(current.headers["content-encoding"], "br");
|
||||
assert.equal(current.headers.vary, "Accept-Encoding");
|
||||
assert.equal(current.headers["cross-origin-embedder-policy"], "credentialless");
|
||||
assert.equal(brotliDecompressSync(current.body).toString(), script);
|
||||
const wasm = await request(server.port, "/_v/web-abc123/canvaskit/skwasm.wasm");
|
||||
assert.equal(wasm.headers["content-type"], "application/wasm");
|
||||
assert.equal(wasm.body.toString(), "wasm");
|
||||
const stale = await request(server.port, "/_v/web-old/main.dart.js");
|
||||
assert.equal(stale.status, 200);
|
||||
assert.equal(stale.headers["cache-control"], "no-cache");
|
||||
assert.equal(stale.body.toString(), script);
|
||||
assert.equal((await request(server.port, "/_v/web-abc123/missing.js")).status, 404);
|
||||
assert.equal((await request(server.port, "/_v/web-abc123/%2e%2e/%2e%2e/etc/passwd")).status, 403);
|
||||
assert.equal((await request(server.port, "/_v/web-abc123/")).status, 404);
|
||||
});
|
||||
|
||||
test("unversioned files revalidate with an ETag, compressed only when accepted", async (t) => {
|
||||
const { root, script } = await build({ release: false });
|
||||
const server = await start(root);
|
||||
t.after(server.stop);
|
||||
const page = await request(server.port, "/");
|
||||
assert.doesNotMatch(page.body.toString(), /pipelines-asset-base/);
|
||||
const plain = await request(server.port, "/main.dart.js");
|
||||
assert.equal(plain.headers["cache-control"], "no-cache");
|
||||
assert.equal(plain.headers["content-encoding"], undefined);
|
||||
assert.equal(plain.body.toString(), script);
|
||||
const gzip = await request(server.port, "/main.dart.js", { "accept-encoding": "gzip" });
|
||||
assert.equal(gzip.headers["content-encoding"], "gzip");
|
||||
const again = await request(server.port, "/main.dart.js", { "if-none-match": plain.headers.etag });
|
||||
assert.equal(again.status, 304);
|
||||
assert.equal(again.body.length, 0);
|
||||
const bootstrap = await request(server.port, "/flutter_bootstrap.js");
|
||||
assert.equal(bootstrap.headers["cache-control"], "no-cache");
|
||||
// A variant older than its file (a hand-edited build) is not sent.
|
||||
const past = new Date(Date.now() - 60_000);
|
||||
await utimes(join(root, "main.dart.js.br"), past, past);
|
||||
const edited = await request(server.port, "/main.dart.js", { "accept-encoding": "br" });
|
||||
assert.equal(edited.headers["content-encoding"], undefined);
|
||||
});
|
||||
|
||||
test("accepted encodings honour q=0", () => {
|
||||
assert.deepEqual([...acceptedEncodings("gzip, deflate, br, zstd")], ["gzip", "deflate", "br", "zstd"]);
|
||||
assert.deepEqual([...acceptedEncodings("br;q=0, gzip;q=0.5")], ["gzip"]);
|
||||
assert.deepEqual([...acceptedEncodings(undefined)], []);
|
||||
});
|
||||
Reference in New Issue
Block a user