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

A first-party beacon reports each page's real load, LCP, INP, CLS and TTFB to the forge, keeping no IP #2731

Parked opened this
Closed without merging

scout/forge:scout/2711-a-first-party-beacon-reports-each-page-s → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +385 −2
README.md +4
@@ -224,6 +224,10 @@ form that mints one and shows its secret once; others see no section.
224224 `owner/name`. `n` mints (the child's name, then its https address) and shows
225225 the secret once on its own screen; `x` revokes the one under the cursor.
226226
227 ## Page-view beacon
228
229 Every page links one static, immutable script (`src/web/beacon.ts`, under 2 KB, no dependency) that sends, once per page view with `sendBeacon`, the route's path, TTFB, load time, LCP, INP (the worst interaction) and CLS to `POST /_measure`. The route is same-origin only, validates every field, caps the body at 512 bytes and the rate per client, and answers 204. Reports land in `page_vital` (bun:sqlite) keyed by route *pattern*; no IP and no user agent string is stored. A unique visitor is a hash under a salt that rotates daily (yesterday's salt is deleted), rows are kept 90 days. Do-Not-Track and the `forge_measure=off` cookie send nothing, and the server stores nothing for them either. The CSP is unchanged: the script is nonce'd like the shell's.
230
227231 ## Live in the terminal
228232
229233 `ssh` into the forge and you get the whole thing — repositories, code, issues,
src/core/migration-pins.json +5 −1
@@ -115,5 +115,9 @@
115115 "20261016190000-member": "9076848fe032dea6905927a1b454c2381a3129acb3ce357c2726e82f1c161bc4",
116116 "20261016200000-invite": "72bc7e9be6a7223048d1d1cf0226bc93ee4dbea9f00dbb20a6d457305886cbf9",
117117 "20261017195831-ceiling-reserved": "1e6756752ae06c78a5920ae839e911e837a14cff3ac766cbc38e117c0a40186b",
118 "20261018100000-incident-remembered": "61fefa1d0750f3be617fdc23c1e6e17abc1ba610d980d85aff8824f14bf3e253"
118 "20261018100000-incident-remembered": "61fefa1d0750f3be617fdc23c1e6e17abc1ba610d980d85aff8824f14bf3e253",
119 "20261018110000-limb-replan": "23d6a14e5ef934c4d8f1509377ac8a15dc6a0097313127558b4c5a655a24581e",
120 "20261019120000-drill-phases": "574071a8576f982fe8483af90b472a03793ffa03e3b391c786d5c5144e3bb82e",
121 "20261019130000-run-model-prompt": "ce2e94f439649fc042c0a951f1af4a740b91f674dc94521e865ec517f68994f5",
122 "20261019140000-page-vitals": "6ff13a58a50df0dce1da4bacf915baa846b658d04b8ef12eef41282768111336"
119123 }
src/core/migrations/20261019140000-page-vitals.ts added +24
@@ -0,0 +1,24 @@
1 // A first-party beacon reports each page view's real load, LCP, INP, CLS and
2 // TTFB (#2711). No IP and no user agent string is kept: `visitor` is a hash
3 // under a salt that rotates daily, and yesterday's salt is deleted, so a
4 // visitor cannot be followed from one day to the next. A metric the browser
5 // could not measure is NULL.
6 export default `
7 CREATE TABLE page_vital (
8 id INTEGER PRIMARY KEY,
9 day TEXT NOT NULL,
10 at INTEGER NOT NULL,
11 route TEXT NOT NULL,
12 visitor TEXT NOT NULL,
13 ttfb REAL,
14 load REAL,
15 lcp REAL,
16 inp REAL,
17 cls REAL NOT NULL
18 );
19 CREATE INDEX page_vital_route ON page_vital (route, at);
20 CREATE TABLE vital_salt (
21 day TEXT PRIMARY KEY,
22 salt TEXT NOT NULL
23 );
24 `;
src/http/measure.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * POST /_measure: the page-view beacon's door. Same-origin only (a beacon
3 * from a page always carries Origin; anything else is refused), opted-out
4 * visitors stored nothing, a rate per client and per forge, a body of a few
5 * hundred bytes at most, every field validated (`web/measure.ts`), and the
6 * route is one the forge serves. The answer is always an empty 204 or a
7 * short refusal; nothing is read back.
8 */
9
10 import { RateLimiter } from "../core/ratelimit.ts";
11 import type { App } from "../app.ts";
12 import { optedOut, parseReport, recordVital, REPORT_MAX } from "../web/measure.ts";
13 import type { Ctx } from "./context.ts";
14 import { readBounded } from "./limits.ts";
15 import { clientAddress, clientBucket } from "./peer.ts";
16
17 const PER_CLIENT = 30;
18 const PER_FORGE = 1200;
19
20 const limiter = (perMinute: number) =>
21 new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true });
22
23 /** One pair per forge, so a test's forge never throttles another's. */
24 const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter }>();
25
26 const refuse = (status: number, headers?: Record<string, string>): Response =>
27 new Response(null, { status, headers: { "cache-control": "no-store", ...headers } });
28
29 /** The route pattern a path belongs to, or undefined when none does. */
30 export type RouteOf = (path: string) => string | undefined;
31
32 export async function measureSubmit(ctx: Ctx, routeOf: RouteOf): Promise<Response> {
33 const { request, app } = ctx;
34 if (request.headers.get("origin") !== ctx.url.origin) return refuse(403);
35 if (optedOut(request)) return refuse(204);
36
37 let pair = limits.get(app);
38 if (pair === undefined) {
39 pair = { client: limiter(PER_CLIENT), forge: limiter(PER_FORGE) };
40 limits.set(app, pair);
41 }
42 for (const verdict of [
43 pair.client.take(clientBucket(request), "ro"),
44 pair.forge.take("forge", "ro"),
45 ]) {
46 if (!verdict.allowed)
47 return refuse(429, { "retry-after": String(Math.max(1, verdict.retryAfter)) });
48 }
49
50 const bytes = await readBounded(request, REPORT_MAX);
51 if (bytes === "too_large") return refuse(413);
52 const report = parseReport(new TextDecoder().decode(bytes));
53 if (report === "malformed") return refuse(400);
54 const route = routeOf(report.path);
55 if (route === undefined) return refuse(400);
56
57 recordVital(
58 app.db,
59 report,
60 route,
61 clientAddress(request),
62 request.headers.get("user-agent") ?? "",
63 );
64 return refuse(204);
65 }
src/http/server.ts +11
@@ -23,6 +23,7 @@ import { usagePage } from "../web/pages/usage.ts";
2323 import { domainsPage } from "../web/pages/domains.ts";
2424 import { resiliencePage } from "../web/pages/resilience.ts";
2525 import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts";
26 import { measureSubmit } from "./measure.ts";
2627 import { boardsPage } from "../web/pages/boards.ts";
2728 import { boardNew, boardPin, boardPost } from "../web/pages/boards-edit.ts";
2829 import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts";
@@ -97,6 +98,7 @@ import { sha256 } from "../kernel/hash.ts";
9798 import {
9899 assetResponse,
99100 highlightAsset,
101 beaconAsset,
100102 shellAsset,
101103 stylesheetAsset,
102104 stylesheetRedirect,
@@ -633,6 +635,7 @@ export function buildRouter(): Router<Handler> {
633635 router.add("GET", "/assets/:name.js", async (ctx) => {
634636 const shell = shellAsset();
635637 if (ctx.params.name === shell.name) return assetResponse(shell);
638 if (ctx.params.name === beaconAsset().name) return assetResponse(beaconAsset());
636639 if (ctx.params.name === TOOLBAR_NAME) return toolbarResponse();
637640 const asset = await highlightAsset();
638641 if (asset === null || ctx.params.name !== asset.name) return notFound();
@@ -641,6 +644,8 @@ export function buildRouter(): Router<Handler> {
641644 // The service worker: root scope needs a root path, and it must never be
642645 // cached by the browser's HTTP cache or an update would wait a day.
643646 router.add("GET", "/sw.js", serviceWorker);
647 // The page-view beacon's report (http/measure.ts): numbers only, no IP kept.
648 router.add("POST", "/_measure", (ctx) => measureSubmit(ctx, routeOf));
644649 router.add("GET", "/", home);
645650 // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts).
646651 router.add("GET", "/claim", claimFragmentPage);
@@ -1372,6 +1377,12 @@ export function buildApiRouter(): Router<Handler> {
13721377 return router;
13731378 }
13741379
1380 let pages: Router<Handler> | undefined;
1381 /** The route pattern a page's path belongs to, for the beacon: never the path itself. */
1382 function routeOf(path: string): string | undefined {
1383 return (pages ??= buildRouter()).match("GET", path)?.pattern;
1384 }
1385
13751386 let known: string[] | undefined;
13761387 /** Every pattern the studio's and the API's routers know, read once on first use. */
13771388 export function knownPatterns(): string[] {
src/web/asset.ts +12
@@ -18,6 +18,7 @@
1818
1919 import { sha256 } from "../kernel/hash.ts";
2020 import { createLog } from "../kernel/log.ts";
21 import { beaconJs } from "./beacon.ts";
2122 import { shellJs } from "./client.ts";
2223 import { css } from "./style.ts";
2324
@@ -128,3 +129,14 @@ export function shellAsset(): BuiltAsset {
128129 }
129130 return shell;
130131 }
132
133 let beacon: BuiltAsset | null = null;
134
135 /** The page-view beacon (`web/beacon.ts`), content-addressed and immutable. */
136 export function beaconAsset(): BuiltAsset {
137 if (beacon === null) {
138 const name = `beacon-${sha256(beaconJs).slice(0, 16)}`;
139 beacon = { path: `/assets/${name}.js`, name, code: beaconJs };
140 }
141 return beacon;
142 }
src/web/beacon.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * The page-view beacon, as static source: one classic script, under 2 KB,
3 * served content-addressed (`web/asset.ts`) and linked from every page. It
4 * watches LCP, layout shift (CLS) and interaction latency (INP, the worst
5 * interaction), and sends them once, with the route's path and the
6 * navigation's TTFB and load time, when the page is hidden or left. Nothing
7 * is sent under Do-Not-Track or with the `forge_measure=off` cookie; the
8 * server checks both again. A metric it could not measure is 0 (or absent).
9 */
10 export const beaconJs = `!function(n,d,w){
11 if(n.doNotTrack=="1"||/(^|; )forge_measure=off/.test(d.cookie)||!n.sendBeacon||!w.PerformanceObserver)return;
12 var c=0,i=0,l=0,x=0;
13 function o(t,f,e){try{new PerformanceObserver(function(s){s.getEntries().forEach(f)}).observe(Object.assign({type:t,buffered:true},e))}catch(_){}}
14 o("largest-contentful-paint",function(e){l=e.startTime});
15 o("layout-shift",function(e){e.hadRecentInput||(c+=e.value)});
16 o("event",function(e){e.interactionId&&e.duration>i&&(i=e.duration)},{durationThreshold:40});
17 function s(){if(x)return;x=1;var v=performance.getEntriesByType("navigation")[0]||{};
18 n.sendBeacon("/_measure",JSON.stringify({path:location.pathname,ttfb:v.responseStart||0,load:v.loadEventEnd||0,lcp:l,inp:i,cls:c}))}
19 d.addEventListener("visibilitychange",function(){d.visibilityState=="hidden"&&s()});
20 w.addEventListener("pagehide",s)
21 }(navigator,document,window)`;
src/web/layout.ts +2 −1
@@ -25,7 +25,7 @@ import {
2525 THEMES,
2626 type ThemeName,
2727 } from "../design/themes.ts";
28 import { shellAsset, stylesheetAsset } from "./asset.ts";
28 import { beaconAsset, shellAsset, stylesheetAsset } from "./asset.ts";
2929 import { linkHeader, pageLinks } from "./standards.ts";
3030 import {
3131 clearFlashCookie,
@@ -679,6 +679,7 @@ export function page(options: PageOptions, status = 200): Response {
679679 <body>
680680 ${shell}${iconSprite(shell.text)}
681681 <script nonce="${nonce}" src="${shellAsset().path}"></script>
682 <script nonce="${nonce}" src="${beaconAsset().path}" defer></script>
682683 ${options.scriptJs
683684 ? raw(`<script nonce="${nonce}">${options.scriptJs}</script>`)
684685 : null}
src/web/measure.ts added +121
@@ -0,0 +1,121 @@
1 /**
2 * The page-view beacon's receiver: validate a report, hash the visitor, store
3 * the numbers. Plain data in, plain data out. What is stored is the route
4 * pattern (never the path, which can name a repository), the five metrics,
5 * and a visitor hash; the address and the user agent string are read to make
6 * that hash and are never written anywhere.
7 *
8 * The salt rotates daily and the old salts are deleted, so a hash means "the
9 * same browser today" and cannot be joined across days. Rows are kept 90 days.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { sha256 } from "../kernel/hash.ts";
14
15 /** A report is a few dozen bytes; this is already generous. */
16 export const REPORT_MAX = 512;
17 /** Times in milliseconds: ten minutes is longer than any real page view. */
18 export const TIME_MAX = 600_000;
19 export const CLS_MAX = 100;
20 const KEEP_MS = 90 * 24 * 60 * 60 * 1000;
21
22 export interface Report {
23 readonly path: string;
24 readonly ttfb: number | null;
25 readonly load: number | null;
26 readonly lcp: number | null;
27 readonly inp: number | null;
28 readonly cls: number;
29 }
30
31 const FIELDS = new Set(["path", "ttfb", "load", "lcp", "inp", "cls"]);
32
33 const bounded = (value: unknown, max: number): number | undefined =>
34 typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max
35 ? value
36 : undefined;
37
38 /** A report from the body's text, or why not. Unknown keys are refused. */
39 export function parseReport(text: string): Report | "malformed" {
40 let raw: unknown;
41 try {
42 raw = JSON.parse(text);
43 } catch {
44 return "malformed";
45 }
46 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return "malformed";
47 const body = raw as Record<string, unknown>;
48 if (Object.keys(body).some((key) => !FIELDS.has(key))) return "malformed";
49 const { path } = body;
50 if (typeof path !== "string" || path.length > 512 || !path.startsWith("/"))
51 return "malformed";
52 // eslint-disable-next-line no-control-regex
53 if (/[\u0000-\u001f\u007f]/.test(path)) return "malformed";
54 const cls = bounded(body["cls"], CLS_MAX);
55 if (cls === undefined) return "malformed";
56 const times: Record<string, number | null> = {};
57 for (const key of ["ttfb", "load", "lcp", "inp"] as const) {
58 const given = body[key];
59 if (given === undefined) {
60 times[key] = null;
61 continue;
62 }
63 const value = bounded(given, TIME_MAX);
64 if (value === undefined) return "malformed";
65 // 0 is how the beacon says "not measured".
66 times[key] = value === 0 ? null : value;
67 }
68 return {
69 path,
70 ttfb: times["ttfb"] ?? null,
71 load: times["load"] ?? null,
72 lcp: times["lcp"] ?? null,
73 inp: times["inp"] ?? null,
74 cls,
75 };
76 }
77
78 /** The visitor asked not to be measured: Do-Not-Track, or the opt-out cookie. */
79 export function optedOut(request: Request): boolean {
80 if (request.headers.get("dnt") === "1") return true;
81 const cookie = request.headers.get("cookie") ?? "";
82 return cookie.split(";").some((pair) => pair.trim() === "forge_measure=off");
83 }
84
85 const dayOf = (at: number): string => new Date(at).toISOString().slice(0, 10);
86
87 /** Today's salt, made on first use; every other day's is deleted. */
88 function saltFor(db: Database, at: number): string {
89 const day = dayOf(at);
90 const found = db
91 .query<{ salt: string }, [string]>("SELECT salt FROM vital_salt WHERE day = ?")
92 .get(day);
93 if (found !== null) return found.salt;
94 const salt = new Bun.CryptoHasher("sha256")
95 .update(crypto.getRandomValues(new Uint8Array(32)))
96 .digest("hex");
97 db.run("DELETE FROM vital_salt WHERE day <> ?", [day]);
98 db.run("INSERT OR IGNORE INTO vital_salt (day, salt) VALUES (?, ?)", [day, salt]);
99 db.run("DELETE FROM page_vital WHERE at < ?", [at - KEEP_MS]);
100 return (
101 db
102 .query<{ salt: string }, [string]>("SELECT salt FROM vital_salt WHERE day = ?")
103 .get(day)?.salt ?? salt
104 );
105 }
106
107 /** Store one report. `client` and `agent` go into the hash and nowhere else. */
108 export function recordVital(
109 db: Database,
110 report: Report,
111 route: string,
112 client: string,
113 agent: string,
114 at: number = Date.now(),
115 ): void {
116 const visitor = sha256(`${saltFor(db, at)}\0${client}\0${agent}`).slice(0, 32);
117 db.run(
118 "INSERT INTO page_vital (day, at, route, visitor, ttfb, load, lcp, inp, cls) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
119 [dayOf(at), at, route, visitor, report.ttfb, report.load, report.lcp, report.inp, report.cls],
120 );
121 }
test/measure.test.ts added +120
@@ -0,0 +1,120 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { beaconJs } from "../src/web/beacon.ts";
8 import { beaconAsset } from "../src/web/asset.ts";
9 import { parseReport, recordVital } from "../src/web/measure.ts";
10
11 let dir: string;
12 let app: App;
13 let servers: Servers;
14 let base: string;
15
16 beforeAll(async () => {
17 dir = await mkdtemp(join(tmpdir(), "measure-"));
18 app = createApp({ dataDir: dir, port: 0 });
19 servers = await serve(app);
20 base = `http://127.0.0.1:${servers.port}`;
21 });
22 afterAll(async () => {
23 await servers.stop();
24 await rm(dir, { recursive: true, force: true });
25 });
26
27 const good = { path: "/", ttfb: 40, load: 300, lcp: 250, inp: 80, cls: 0.02 };
28 const send = (body: unknown, headers: Record<string, string> = {}) =>
29 fetch(`${base}/_measure`, {
30 method: "POST",
31 headers: { origin: base, ...headers },
32 body: typeof body === "string" ? body : JSON.stringify(body),
33 });
34 const rows = () => app.db.query("SELECT * FROM page_vital").all() as Record<string, unknown>[];
35 const count = () => rows().length;
36
37 describe("the page-view beacon", () => {
38 test("the script is under 2048 bytes, immutable, and linked from a page", async () => {
39 expect(new TextEncoder().encode(beaconJs).length).toBeLessThan(2048);
40 const asset = beaconAsset();
41 const script = await fetch(base + asset.path);
42 expect(script.status).toBe(200);
43 expect(script.headers.get("cache-control")).toContain("immutable");
44 expect(await script.text()).toBe(beaconJs);
45 const home = await fetch(base + "/");
46 expect(await home.text()).toContain(asset.path);
47 expect(home.headers.get("content-security-policy")).toContain("script-src 'nonce-");
48 expect(home.headers.get("content-security-policy")).not.toContain("unsafe");
49 });
50
51 test("a valid report is stored by route pattern, with no address or agent", async () => {
52 const before = count();
53 const res = await send({ ...good, path: "/someone/thing" }, { "user-agent": "Mozilla/5.0 Secret" });
54 expect(res.status).toBe(204);
55 expect(count()).toBe(before + 1);
56 const row = rows().at(-1)!;
57 expect(row["route"]).toBe("/:owner/:name");
58 expect(row["lcp"]).toBe(250);
59 expect(row["cls"]).toBe(0.02);
60 expect(String(row["visitor"])).toMatch(/^[0-9a-f]{32}$/);
61 const text = JSON.stringify(rows());
62 expect(text).not.toContain("Secret");
63 expect(text).not.toContain("127.0.0.1");
64 expect(text).not.toContain("someone");
65 });
66
67 test("a cross-origin, originless, oversized or malformed report is refused", async () => {
68 const before = count();
69 expect((await send(good, { origin: "https://evil.example" })).status).toBe(403);
70 const bare = await fetch(`${base}/_measure`, { method: "POST", body: JSON.stringify(good) });
71 expect(bare.status).toBe(403);
72 expect((await send("x".repeat(5000))).status).toBe(413);
73 expect((await send("{nope")).status).toBe(400);
74 expect((await send({ ...good, cls: "1" })).status).toBe(400);
75 expect((await send({ ...good, lcp: 1e12 })).status).toBe(400);
76 expect((await send({ ...good, lcp: -1 })).status).toBe(400);
77 expect((await send({ ...good, extra: 1 })).status).toBe(400);
78 expect((await send({ ...good, path: "https://evil.example/" })).status).toBe(400);
79 expect((await send({ ...good, path: "/a\nb" })).status).toBe(400);
80 expect((await send([1])).status).toBe(400);
81 expect((await send({ ...good, path: "/_nothing/at/all/here/x/y/z" })).status).toBe(400);
82 expect(count()).toBe(before);
83 });
84
85 test("Do-Not-Track and the opt-out cookie store nothing", async () => {
86 const before = count();
87 expect((await send(good, { dnt: "1" })).status).toBe(204);
88 expect((await send(good, { cookie: "a=b; forge_measure=off" })).status).toBe(204);
89 expect(count()).toBe(before);
90 });
91
92 test("a client past its rate is told to wait", async () => {
93 const statuses: number[] = [];
94 for (let i = 0; i < 40; i++) statuses.push((await send(good)).status);
95 expect(statuses).toContain(429);
96 });
97 });
98
99 describe("the report and the visitor hash", () => {
100 test("0 means not measured, and absent times are null", () => {
101 expect(parseReport('{"path":"/","cls":0,"lcp":0}')).toEqual({
102 path: "/", ttfb: null, load: null, lcp: null, inp: null, cls: 0,
103 });
104 });
105
106 test("the salt rotates daily: same browser, same day, same hash; next day, another", () => {
107 const report = parseReport(JSON.stringify(good));
108 if (report === "malformed") throw new Error("bad fixture");
109 const day = Date.UTC(2026, 0, 5, 10);
110 const visitor = () => (rows().at(-1) as { visitor: string }).visitor;
111 app.db.run("DELETE FROM page_vital");
112 recordVital(app.db, report, "/", "1.2.3.4", "ua", day);
113 const first = visitor();
114 recordVital(app.db, report, "/", "1.2.3.4", "ua", day + 1000);
115 expect(visitor()).toBe(first);
116 recordVital(app.db, report, "/", "1.2.3.4", "ua", day + 86_400_000);
117 expect(visitor()).not.toBe(first);
118 expect((app.db.query("SELECT COUNT(*) AS n FROM vital_salt").get() as { n: number }).n).toBe(1);
119 });
120 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs