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 #5386
scout/forge:scout/5354-a-note-from-the-app-s-own-origin-is-file → main 2 commits fork
7 files
changed +172
−16
src/apps/feedback.ts +4 −2
| @@ -34,6 +34,8 @@ export interface FeedbackAsk { | ||
| 34 | 34 | readonly sealed: boolean; |
| 35 | 35 | /** The person the app's grant names, if any. */ |
| 36 | 36 | 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; | |
| 37 | 39 | readonly secure: boolean; |
| 38 | 40 | /** The client's limit key, from the socket (`clientBucket`). */ |
| 39 | 41 | readonly source: string; |
| @@ -86,7 +88,7 @@ function doorFor(ask: FeedbackAsk): Door | undefined { | ||
| 86 | 88 | |
| 87 | 89 | /** The sender: a person's key and name, or the anonymous cookie's. */ |
| 88 | 90 | function senderOf(ask: FeedbackAsk, door: Door): { sender: Sender; fresh?: string } { |
| 89 | if (door.viewer !== undefined) | |
| 91 | if (door.viewer !== undefined && ask.proven) | |
| 90 | 92 | return { sender: { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true } }; |
| 91 | 93 | const have = cookieOf(ask.request, VISITOR_COOKIE); |
| 92 | 94 | const cookie = have !== undefined && /^[0-9a-f]{32}$/.test(have) ? have : undefined; |
| @@ -159,7 +161,7 @@ function list(ask: FeedbackAsk, door: Door): Response { | ||
| 159 | 161 | const notes = notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender); |
| 160 | 162 | return json( |
| 161 | 163 | 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) }, | |
| 163 | 165 | fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) }, |
| 164 | 166 | ); |
| 165 | 167 | } |
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"; | ||
| 43 | 43 | import { appMeasure } from "./measure.ts"; |
| 44 | 44 | import { holdPortRequest, holdPortSocket } from "./handoff.ts"; |
| 45 | 45 | import { htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts"; |
| 46 | import { isPageLoad, issueProof, PROOF_HEADER, spendProof } from "./proof.ts"; | |
| 46 | 47 | |
| 47 | 48 | export interface AppTarget { |
| 48 | 49 | readonly app: AppRecord; |
| @@ -664,6 +665,10 @@ export async function proxyApp( | ||
| 664 | 665 | (sealed || target.app.access === "private") && signed !== undefined && !stillEntitled(runtime, target, signed) |
| 665 | 666 | ? undefined |
| 666 | 667 | : 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); | |
| 667 | 672 | const answer = await feedback({ |
| 668 | 673 | app: runtime.app, |
| 669 | 674 | forgeUrl: runtime.options.forgeUrl, |
| @@ -673,12 +678,18 @@ export async function proxyApp( | ||
| 673 | 678 | env: target.env, |
| 674 | 679 | sealed, |
| 675 | 680 | viewerId, |
| 681 | proven, | |
| 676 | 682 | secure: |
| 677 | 683 | url.protocol === "https:" || |
| 678 | 684 | request.headers.get("x-forwarded-proto") === "https", |
| 679 | 685 | source: clientBucket(request), |
| 680 | 686 | }); |
| 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 | } | |
| 682 | 693 | } |
| 683 | 694 | // The beacon's report: filed against this app, never waking it. A private |
| 684 | 695 | // app (or a sealed pull's preview) admits only the people it admits, so |
| @@ -811,11 +822,22 @@ export async function proxyApp( | ||
| 811 | 822 | } catch { |
| 812 | 823 | return unavailable(runtime, target, status, "the app stopped answering"); |
| 813 | 824 | } |
| 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); | |
| 814 | 835 | const page = withToolbar( |
| 815 | 836 | bytes, |
| 816 | 837 | runtime.options.forgeUrl, |
| 817 | pillWhere(runtime, target, vouched?.who), | |
| 838 | proofed ? { ...where, proof: issueProof(grantCookie, host) } : where, | |
| 818 | 839 | ); |
| 840 | if (proofed) out.set("cache-control", "private, no-store"); | |
| 819 | 841 | let sent = page; |
| 820 | 842 | // Whether it is gzipped depends on the client, so every copy says so. |
| 821 | 843 | out.append("vary", "accept-encoding"); |
src/apps/toolbar.ts +20 −2
| @@ -30,6 +30,21 @@ export const toolbarJs = `(function () { | ||
| 30 | 30 | var pill = document.createElement("button"); |
| 31 | 31 | pill.type = "button"; |
| 32 | 32 | 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 | } | |
| 33 | 48 | var where = d.env === "production" ? "production" : d.pull ? "preview of pull #" + d.pull : ""; |
| 34 | 49 | pill.setAttribute("aria-label", [d.app, where].filter(Boolean).join(", ") || "Forge"); |
| 35 | 50 | pill.setAttribute("aria-expanded", "false"); |
| @@ -140,7 +155,7 @@ export const toolbarJs = `(function () { | ||
| 140 | 155 | }); |
| 141 | 156 | } |
| 142 | 157 | function refresh(sent) { |
| 143 | fetch("/__forge/notes", { credentials: "same-origin", cache: "no-store" }) | |
| 158 | api("/__forge/notes", { credentials: "same-origin", cache: "no-store" }) | |
| 144 | 159 | .then(function (r) { return r.ok ? r.json() : null; }) |
| 145 | 160 | .then(function (j) { |
| 146 | 161 | if (!j || !Array.isArray(j.notes)) return; |
| @@ -159,7 +174,7 @@ export const toolbarJs = `(function () { | ||
| 159 | 174 | tellGo.setAttribute("aria-busy", "true"); |
| 160 | 175 | tellGo.style.opacity = ".6"; |
| 161 | 176 | function idle() { tellGo.disabled = false; tellGo.removeAttribute("aria-busy"); tellGo.style.opacity = "1"; } |
| 162 | fetch("/__forge/note", { | |
| 177 | api("/__forge/note", { | |
| 163 | 178 | method: "POST", |
| 164 | 179 | credentials: "same-origin", |
| 165 | 180 | headers: { "content-type": "application/json" }, |
| @@ -407,6 +422,8 @@ export type PillWhere = { | ||
| 407 | 422 | env: string; |
| 408 | 423 | pull?: number; |
| 409 | 424 | title?: string; |
| 425 | /** The one-use proof for this page load (`apps/proof.ts`); the panel strips it. */ | |
| 426 | proof?: string; | |
| 410 | 427 | }; |
| 411 | 428 | |
| 412 | 429 | /** `text` safe inside a double-quoted HTML attribute. */ |
| @@ -430,6 +447,7 @@ export function toolbarTag(forgeUrl: string, where?: PillWhere): string { | ||
| 430 | 447 | ["env", where.env], |
| 431 | 448 | ["pull", where.pull === undefined ? undefined : String(where.pull)], |
| 432 | 449 | ["title", where.title], |
| 450 | ["proof", where.proof], | |
| 433 | 451 | ] |
| 434 | 452 | .filter((pair): pair is [string, string] => pair[1] !== undefined) |
| 435 | 453 | .map(([k, v]) => ` data-${k}="${escapeAttr(v)}"`) |
test/apps-crew-pill.test.ts +1 −1
| @@ -199,7 +199,7 @@ describe("the crew line", () => { | ||
| 199 | 199 | expect(toolbarJs).toContain("/__forge/crew"); |
| 200 | 200 | // The crew line is asked once; the feedback door (#4758) adds the |
| 201 | 201 | // 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 | |
| 203 | 203 | expect(toolbarJs.match(/setInterval/g)?.length).toBe(1); |
| 204 | 204 | expect(toolbarJs).not.toMatch( |
| 205 | 205 | /document\.cookie|querySelector|getElementById|setTimeout/, |
test/apps-feedback.test.ts +75 −7
| @@ -11,7 +11,8 @@ import { join } from "node:path"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { newApp } from "../src/actions/apps.ts"; |
| 13 | 13 | 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"; | |
| 15 | 16 | import { filtered, moderateNote, noteClock, PER_APP_DAY, PER_SENDER, PER_SOURCE, saysFromApp } from "../src/actions/app_notes.ts"; |
| 16 | 17 | import { feedback, REQUEST_MAX } from "../src/apps/feedback.ts"; |
| 17 | 18 | import { getAppBySlug } from "../src/core/apps.ts"; |
| @@ -279,7 +280,7 @@ describe("the forge button takes notes from anyone", () => { | ||
| 279 | 280 | } as RequestInit); |
| 280 | 281 | const res = await feedback({ |
| 281 | 282 | 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", | |
| 283 | 284 | }); |
| 284 | 285 | expect(res!.status).toBe(400); |
| 285 | 286 | // chunked, no honest length: stopped near the cap, not after 4 MB |
| @@ -297,21 +298,88 @@ describe("the forge button takes notes from anyone", () => { | ||
| 297 | 298 | expect(await Bun.file(join(import.meta.dir, "../src/actions/app_notes.ts")).text()).not.toContain("x-forwarded-for"); |
| 298 | 299 | }); |
| 299 | 300 | |
| 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 () => { | |
| 301 | 313 | 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"); | |
| 303 | 315 | 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}$/); | |
| 305 | 319 | const repo = getRepo(app.db, "alice", "diary")!; |
| 306 | 320 | const issue = app.db.query<{ body: string }, [string]>("SELECT body FROM issue WHERE repo_id = ?1 ORDER BY number DESC").get(repo.id)!; |
| 307 | 321 | expect(issue.body).toContain("by @alice."); |
| 308 | 322 | 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"); | |
| 311 | 326 | expect(mine.admin).toBe(true); |
| 327 | expect(listed.headers.get(PROOF_HEADER)).toMatch(/^[0-9a-f]{48}$/); | |
| 312 | 328 | expect((await at("diary", "/__forge/notes")).status).toBe(404); |
| 313 | 329 | }); |
| 314 | 330 | |
| 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 | ||
| 315 | 383 | 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 () => { |
| 316 | 384 | // The minute's bounds are spent by the tests before; this one starts a later minute. |
| 317 | 385 | const start = Date.now() + 120_000; |
test/toolbar-actions.test.ts +2 −2
| @@ -90,9 +90,9 @@ describe("toolbar actions", () => { | ||
| 90 | 90 | expect(toolbarJs).toContain('"/toolbar"'); |
| 91 | 91 | // Its requests are all to the app's own origin: the crew line (#2233) and, |
| 92 | 92 | // 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 | |
| 94 | 94 | expect(toolbarJs).toContain('fetch("/__forge/crew"'); |
| 95 | expect(toolbarJs).toContain('fetch("/__forge/note"'); | |
| 95 | expect(toolbarJs).toContain('api("/__forge/note"'); | |
| 96 | 96 | expect(toolbarJs).not.toMatch(/FormData|\.send\(/); |
| 97 | 97 | expect(toolbarJs).not.toContain("XMLHttpRequest"); |
| 98 | 98 | expect(toolbarJs).not.toContain("document.cookie"); |
new above
offline