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

A note from the app's own origin is filed as a visitor's unless it carries the forge panel's one-use proof #5377

Parked opened this
Closed without merging

scout/forge:scout/5354-a-note-from-the-app-s-own-origin-is-file → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +172 −16
src/apps/feedback.ts +4 −2
@@ -34,6 +34,8 @@ export interface FeedbackAsk {
3434 readonly sealed: boolean;
3535 /** The person the app's grant names, if any. */
3636 readonly viewerId: string | undefined;
37 /** Whether the request spent a valid panel proof (`apps/proof.ts`): only then is the sender the person. */
38 readonly proven: boolean;
3739 readonly secure: boolean;
3840 /** The client's limit key, from the socket (`clientBucket`). */
3941 readonly source: string;
@@ -86,7 +88,7 @@ function doorFor(ask: FeedbackAsk): Door | undefined {
8688
8789 /** The sender: a person's key and name, or the anonymous cookie's. */
8890 function senderOf(ask: FeedbackAsk, door: Door): { sender: Sender; fresh?: string } {
89 if (door.viewer !== undefined)
91 if (door.viewer !== undefined && ask.proven)
9092 return { sender: { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true } };
9193 const have = cookieOf(ask.request, VISITOR_COOKIE);
9294 const cookie = have !== undefined && /^[0-9a-f]{32}$/.test(have) ? have : undefined;
@@ -159,7 +161,7 @@ function list(ask: FeedbackAsk, door: Door): Response {
159161 const notes = notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender);
160162 return json(
161163 200,
162 { name: sender.name, notes, admin: door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
164 { name: sender.name, notes, admin: ask.proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
163165 fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) },
164166 );
165167 }
src/apps/proof.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * The forge panel's one-use proof (#5354). The app's own page script shares
3 * its origin with the panel, so a same-origin request carrying the HttpOnly
4 * grant cookie says nothing about who sent it. A token the forge put in the
5 * panel's script tag on a page load, bound to that grant and host and spent
6 * on use, does: the panel holds it in a closure, and each answer hands over
7 * the next. Held in memory; a restart costs a reload, never a wrong name.
8 */
9 import { randomBytes } from "node:crypto";
10 import { sha256 } from "../kernel/hash.ts";
11
12 export const PROOF_HEADER = "x-forge-proof";
13 export const PROOF_TTL_MS = 60 * 60 * 1000;
14 export const PROOF_MAX = 10_000;
15
16 const live = new Map<string, { bind: string; expires: number }>();
17
18 const bindOf = (grant: string, host: string): string => sha256(`${grant}\n${host}`);
19
20 /** A fresh token for `grant` on `host`; only its hash is kept. */
21 export function issueProof(grant: string, host: string, now = Date.now()): string {
22 if (live.size >= PROOF_MAX) {
23 for (const [k, v] of live) if (v.expires <= now) live.delete(k);
24 while (live.size >= PROOF_MAX) live.delete(live.keys().next().value!);
25 }
26 const token = randomBytes(24).toString("hex");
27 live.set(sha256(token), { bind: bindOf(grant, host), expires: now + PROOF_TTL_MS });
28 return token;
29 }
30
31 /** Whether `token` is live for this grant and host; it is gone either way. */
32 export function spendProof(token: string | null, grant: string | undefined, host: string | null, now = Date.now()): boolean {
33 if (token === null || grant === undefined || host === null || !/^[0-9a-f]{48}$/.test(token)) return false;
34 const key = sha256(token);
35 const have = live.get(key);
36 if (have === undefined) return false;
37 live.delete(key);
38 return have.expires > now && have.bind === bindOf(grant, host);
39 }
40
41 /** Whether a request is a page load the panel may be handed a proof on. */
42 export function isPageLoad(headers: Headers): boolean {
43 const dest = headers.get("sec-fetch-dest");
44 if (dest === null || dest === "document") return true;
45 return dest === "iframe" && headers.get("sec-fetch-site") === "cross-site";
46 }
src/apps/proxy.ts +24 −2
@@ -43,6 +43,7 @@ import { notFound } from "../http/respond.ts";
4343 import { appMeasure } from "./measure.ts";
4444 import { holdPortRequest, holdPortSocket } from "./handoff.ts";
4545 import { htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts";
46 import { isPageLoad, issueProof, PROOF_HEADER, spendProof } from "./proof.ts";
4647
4748 export interface AppTarget {
4849 readonly app: AppRecord;
@@ -664,6 +665,10 @@ export async function proxyApp(
664665 (sealed || target.app.access === "private") && signed !== undefined && !stillEntitled(runtime, target, signed)
665666 ? undefined
666667 : signed?.who?.id;
668 const host = request.headers.get("host");
669 const proven =
670 signed?.who !== undefined &&
671 spendProof(request.headers.get(PROOF_HEADER), cookie, host);
667672 const answer = await feedback({
668673 app: runtime.app,
669674 forgeUrl: runtime.options.forgeUrl,
@@ -673,12 +678,18 @@ export async function proxyApp(
673678 env: target.env,
674679 sealed,
675680 viewerId,
681 proven,
676682 secure:
677683 url.protocol === "https:" ||
678684 request.headers.get("x-forwarded-proto") === "https",
679685 source: clientBucket(request),
680686 });
681 if (answer !== undefined) return answer;
687 if (answer !== undefined) {
688 if (!proven || cookie === undefined || host === null) return answer;
689 const next = new Response(answer.body, answer);
690 next.headers.set(PROOF_HEADER, issueProof(cookie, host));
691 return next;
692 }
682693 }
683694 // The beacon's report: filed against this app, never waking it. A private
684695 // app (or a sealed pull's preview) admits only the people it admits, so
@@ -811,11 +822,22 @@ export async function proxyApp(
811822 } catch {
812823 return unavailable(runtime, target, status, "the app stopped answering");
813824 }
825 // A signed-in person's page load hands the panel its proof; such a page
826 // is theirs alone, so no cache may keep it.
827 const grantCookie = cookieValue(request, grantCookieName(target));
828 const host = request.headers.get("host");
829 const proofed =
830 vouched?.who !== undefined &&
831 grantCookie !== undefined &&
832 host !== null &&
833 isPageLoad(request.headers);
834 const where = pillWhere(runtime, target, vouched?.who);
814835 const page = withToolbar(
815836 bytes,
816837 runtime.options.forgeUrl,
817 pillWhere(runtime, target, vouched?.who),
838 proofed ? { ...where, proof: issueProof(grantCookie, host) } : where,
818839 );
840 if (proofed) out.set("cache-control", "private, no-store");
819841 let sent = page;
820842 // Whether it is gzipped depends on the client, so every copy says so.
821843 out.append("vary", "accept-encoding");
src/apps/toolbar.ts +20 −2
@@ -30,6 +30,21 @@ export const toolbarJs = `(function () {
3030 var pill = document.createElement("button");
3131 pill.type = "button";
3232 var d = me.dataset || {};
33 var proof = d.proof || "";
34 try { me.removeAttribute("data-proof"); } catch (e) {}
35 var chain = Promise.resolve();
36 function api(url, init) {
37 var run = chain.then(function () {
38 init.headers = init.headers || {};
39 if (proof) init.headers["x-forge-proof"] = proof;
40 return fetch(url, init);
41 }).then(function (r) {
42 proof = r.headers.get("x-forge-proof") || "";
43 return r;
44 });
45 chain = run.catch(function () {});
46 return run;
47 }
3348 var where = d.env === "production" ? "production" : d.pull ? "preview of pull #" + d.pull : "";
3449 pill.setAttribute("aria-label", [d.app, where].filter(Boolean).join(", ") || "Forge");
3550 pill.setAttribute("aria-expanded", "false");
@@ -140,7 +155,7 @@ export const toolbarJs = `(function () {
140155 });
141156 }
142157 function refresh(sent) {
143 fetch("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
158 api("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
144159 .then(function (r) { return r.ok ? r.json() : null; })
145160 .then(function (j) {
146161 if (!j || !Array.isArray(j.notes)) return;
@@ -159,7 +174,7 @@ export const toolbarJs = `(function () {
159174 tellGo.setAttribute("aria-busy", "true");
160175 tellGo.style.opacity = ".6";
161176 function idle() { tellGo.disabled = false; tellGo.removeAttribute("aria-busy"); tellGo.style.opacity = "1"; }
162 fetch("/__forge/note", {
177 api("/__forge/note", {
163178 method: "POST",
164179 credentials: "same-origin",
165180 headers: { "content-type": "application/json" },
@@ -407,6 +422,8 @@ export type PillWhere = {
407422 env: string;
408423 pull?: number;
409424 title?: string;
425 /** The one-use proof for this page load (`apps/proof.ts`); the panel strips it. */
426 proof?: string;
410427 };
411428
412429 /** `text` safe inside a double-quoted HTML attribute. */
@@ -430,6 +447,7 @@ export function toolbarTag(forgeUrl: string, where?: PillWhere): string {
430447 ["env", where.env],
431448 ["pull", where.pull === undefined ? undefined : String(where.pull)],
432449 ["title", where.title],
450 ["proof", where.proof],
433451 ]
434452 .filter((pair): pair is [string, string] => pair[1] !== undefined)
435453 .map(([k, v]) => ` data-${k}="${escapeAttr(v)}"`)
test/apps-crew-pill.test.ts +1 −1
@@ -199,7 +199,7 @@ describe("the crew line", () => {
199199 expect(toolbarJs).toContain("/__forge/crew");
200200 // The crew line is asked once; the feedback door (#4758) adds the
201201 // sender's notes, polled only while the panel is open, and the send.
202 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
202 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2); // the crew line and the one `api` helper the notes go through
203203 expect(toolbarJs.match(/setInterval/g)?.length).toBe(1);
204204 expect(toolbarJs).not.toMatch(
205205 /document\.cookie|querySelector|getElementById|setTimeout/,
test/apps-feedback.test.ts +75 −7
@@ -11,7 +11,8 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { newApp } from "../src/actions/apps.ts";
1313 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { toolbarJs } from "../src/apps/toolbar.ts";
14 import { toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
15 import { isPageLoad, issueProof, PROOF_HEADER } from "../src/apps/proof.ts";
1516 import { filtered, moderateNote, noteClock, PER_APP_DAY, PER_SENDER, PER_SOURCE, saysFromApp } from "../src/actions/app_notes.ts";
1617 import { feedback, REQUEST_MAX } from "../src/apps/feedback.ts";
1718 import { getAppBySlug } from "../src/core/apps.ts";
@@ -279,7 +280,7 @@ describe("the forge button takes notes from anyone", () => {
279280 } as RequestInit);
280281 const res = await feedback({
281282 app, forgeUrl: servers.url, request, url: new URL(request.url), record, env: "production",
282 sealed: false, viewerId: undefined, secure: false, source: "10.4.0.1",
283 sealed: false, viewerId: undefined, proven: false, secure: false, source: "10.4.0.1",
283284 });
284285 expect(res!.status).toBe(400);
285286 // chunked, no honest length: stopped near the cap, not after 4 MB
@@ -297,21 +298,88 @@ describe("the forge button takes notes from anyone", () => {
297298 expect(await Bun.file(join(import.meta.dir, "../src/actions/app_notes.ts")).text()).not.toContain("x-forwarded-for");
298299 });
299300
300 test("a private app takes notes from a signed-in reader, as themselves, and from no one else", async () => {
301 /** The value of the grant cookie `cookie` (`name=value`). */
302 const grantOf = (cookie: string) => cookie.split(";")[0]!.split("=").slice(1).join("=");
303 const proofFor = (cookie: string, slug: string) => issueProof(grantOf(cookie), host(slug));
304 const withProof = (token: string, cookie: string, slug: string, text = "from the panel") =>
305 at(slug, "/__forge/note", {
306 method: "POST",
307 headers: { [PROOF_HEADER]: token },
308 body: JSON.stringify({ text, page: `http://${host(slug)}/`, viewport: "390x844" }),
309 }, cookie);
310 const nameOf = async (res: Response) => ((await res.json()) as { name: string }).name;
311
312 test("a private app takes notes from a signed-in reader, as themselves with the panel's proof, and from no one else", async () => {
301313 const reader = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
302 const res = await post("A note on the diary", reader, "10.5.0.1", "diary");
314 const res = await withProof(proofFor(reader, "diary"), reader, "diary", "A note on the diary");
303315 expect(res.status).toBe(201);
304 expect(((await res.json()) as { name: string }).name).toBe("@alice");
316 expect(await nameOf(res)).toBe("@alice");
317 const next = res.headers.get(PROOF_HEADER)!;
318 expect(next).toMatch(/^[0-9a-f]{48}$/);
305319 const repo = getRepo(app.db, "alice", "diary")!;
306320 const issue = app.db.query<{ body: string }, [string]>("SELECT body FROM issue WHERE repo_id = ?1 ORDER BY number DESC").get(repo.id)!;
307321 expect(issue.body).toContain("by @alice.");
308322 expect(issue.body).toContain("Untrusted data");
309 const mine = (await (await at("diary", "/__forge/notes", {}, reader)).json()) as { notes: unknown[]; admin: boolean };
310 expect(mine.notes.length).toBe(1);
323 const listed = await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: next } }, reader);
324 const mine = (await listed.json()) as { name: string; notes: unknown[]; admin: boolean };
325 expect(mine.name).toBe("@alice");
311326 expect(mine.admin).toBe(true);
327 expect(listed.headers.get(PROOF_HEADER)).toMatch(/^[0-9a-f]{48}$/);
312328 expect((await at("diary", "/__forge/notes")).status).toBe(404);
313329 });
314330
331 test("the app's own script, with the grant cookie but no proof, is a visitor and no admin", async () => {
332 const reader = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "notes")!);
333 const res = await post("unproven", reader, "10.7.0.1");
334 expect(res.status).toBe(201);
335 expect(await nameOf(res)).toMatch(/^visitor-[0-9a-f]{6}$/);
336 expect(res.headers.get(PROOF_HEADER)).toBeNull();
337 const list = (await (await at("notes", "/__forge/notes", {}, reader)).json()) as { name: string; admin: boolean };
338 expect(list.name).toMatch(/^visitor-/);
339 expect(list.admin).toBe(false);
340 });
341
342 test("a proof is spent once, and only for its own grant and host", async () => {
343 const notes = getAppBySlug(app.db, "notes")!;
344 const reader = await grantedCookie(app, servers.url, alice, notes);
345 const who = async (token: string, cookie = reader) =>
346 ((await (await at("notes", "/__forge/notes", { headers: { [PROOF_HEADER]: token } }, cookie)).json()) as { name: string }).name;
347 const token = proofFor(reader, "notes");
348 expect(await who(token)).toBe("@alice");
349 // Reused.
350 expect(await who(token)).toMatch(/^visitor-/);
351 // Issued for another grant.
352 expect(await who(issueProof("some-other-grant", host("notes")))).toMatch(/^visitor-/);
353 // Issued for another host.
354 expect(await who(issueProof(grantOf(reader), host("diary")))).toMatch(/^visitor-/);
355 // Made up.
356 expect(await who("a".repeat(48))).toMatch(/^visitor-/);
357 // And the same for a note: proven is the person, reused is not.
358 // The clock moves a day on, past the bounds the notes before spent.
359 const later = Date.now() + 3 * 86_400_000;
360 noteClock.now = () => later;
361 try {
362 const fresh = proofFor(reader, "notes");
363 expect(await nameOf(await withProof(fresh, reader, "notes", "proven note"))).toBe("@alice");
364 expect(await nameOf(await withProof(fresh, reader, "notes", "reused note"))).toMatch(/^visitor-/);
365 } finally {
366 noteClock.now = () => Date.now();
367 }
368 });
369
370 test("only a page load is handed a proof, and the panel strips it from its tag", () => {
371 const h = (o: Record<string, string>) => new Headers(o);
372 expect(isPageLoad(h({}))).toBe(true);
373 expect(isPageLoad(h({ "sec-fetch-dest": "document" }))).toBe(true);
374 expect(isPageLoad(h({ "sec-fetch-dest": "iframe", "sec-fetch-site": "cross-site" }))).toBe(true);
375 expect(isPageLoad(h({ "sec-fetch-dest": "iframe", "sec-fetch-site": "same-origin" }))).toBe(false);
376 expect(isPageLoad(h({ "sec-fetch-dest": "empty", "sec-fetch-site": "same-origin" }))).toBe(false);
377 expect(toolbarTag(servers.url, { app: "notes", env: "production", proof: "ab12" })).toContain(' data-proof="ab12"');
378 expect(toolbarTag(servers.url, { app: "notes", env: "production" })).not.toContain("data-proof");
379 expect(toolbarJs).toContain('removeAttribute("data-proof")');
380 expect(toolbarJs).toContain("x-forge-proof");
381 });
382
315383 test("the studio page lists the notes; a writer hides one, bans a sender and unbans them; a stranger sees and can do nothing", async () => {
316384 // The minute's bounds are spent by the tests before; this one starts a later minute.
317385 const start = Date.now() + 120_000;
test/toolbar-actions.test.ts +2 −2
@@ -90,9 +90,9 @@ describe("toolbar actions", () => {
9090 expect(toolbarJs).toContain('"/toolbar"');
9191 // Its requests are all to the app's own origin: the crew line (#2233) and,
9292 // for the feedback door (#4758), the sender's notes and their status.
93 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
93 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2); // the crew line and the one `api` helper the notes go through
9494 expect(toolbarJs).toContain('fetch("/__forge/crew"');
95 expect(toolbarJs).toContain('fetch("/__forge/note"');
95 expect(toolbarJs).toContain('api("/__forge/note"');
9696 expect(toolbarJs).not.toMatch(/FormData|\.send\(/);
9797 expect(toolbarJs).not.toContain("XMLHttpRequest");
9898 expect(toolbarJs).not.toContain("document.cookie");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs