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

A note filed from the app's own origin is a visitor's, never the signed-in person's, unless it carries the forge panel's proof #5098

Closed opened this
Closed without merging

scout/forge:scout/4940-a-note-filed-from-the-app-s-own-origin-i → main 5 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +322 −30
README.md +17
@@ -1001,6 +1001,23 @@ Under the box, four starter sentences are plain links (no script):
10011001 status (queued, being built by a member, shipped on a date), polled every 15 s
10021002 while the panel is open; a public app's note links to its issue. Left out: the
10031003 optional screenshot and a version name in "shipped".
1004 **A note is a person's only with the panel's proof (#4940).** The door sits
1005 on the app's own origin, where the app's scripts send the grant cookie too, so
1006 for a signed-in person's page load the forge renders a one-use token into the
1007 panel's script tag (bound to the grant and host, removed from the tag at once,
1008 answered with the next in `x-forge-proof`). Without it a note is a
1009 `visitor-xxxxxx`'s and the list is the visitor's; a token presented but spent,
1010 expired or foreign is a 409 "Reload the page to send as yourself." that files
1011 nothing. That page is sent `private, no-store`. Tokens live in memory (6 hours,
1012 5000 at most), so a restart or a second tab asks for a reload. A script that
1013 patches `fetch` before the panel loads can still capture one, as can one that
1014 watches the DOM for the tag, and a same-origin page the person's own click
1015 opened is given a token like any other; closing that needs the panel in a
1016 forge-origin iframe. The token is withheld from iframes, from fetches, and
1017 from same-origin navigations without the user's activation (`Sec-Fetch-Dest`,
1018 `-Site`, `-User`), so the app's script cannot embed or pop up its own page to
1019 read one; a page the person reaches that way has no token and files as a
1020 visitor.
10041021 From the terminal, a repository screen that is an app has two palette rows
10051022 (`:`): *Tell the builders* sends a note as you, and *Notes from the app*
10061023 lists yours with their status; the repository's admin sees every sender's and
src/apps/feedback.ts +65 −11
@@ -22,6 +22,38 @@ import { sha256 } from "../kernel/hash.ts";
2222
2323 export const REQUEST_MAX = 16 * 1024;
2424 export const VISITOR_COOKIE = "forge_visitor";
25 export const PROOF_HEADER = "x-forge-proof";
26
27 /**
28 * The panel's proof (#4940). The door sits on the app's own origin, where the
29 * app's scripts send the grant cookie as surely as the panel does, so the
30 * cookie alone says only who is looking, not who chose to write. A note is a
31 * person's only when it carries a token the forge rendered into the panel's
32 * own script tag: bound to the grant it was rendered for, used once, and
33 * answered with the next one. Held in memory: a restart asks for a reload.
34 */
35 const PROOF_TTL_MS = 6 * 3600 * 1000;
36 const PROOF_MAX = 5000;
37 const proofs = new Map<string, { bind: string; until: number }>();
38
39 const bindOf = (grant: string, host: string): string => sha256(`${host}\n${grant}`);
40
41 /** A fresh token for the panel on `host`, bound to `grant`. */
42 export function issueProof(grant: string, host: string, now = Date.now()): string {
43 while (proofs.size >= PROOF_MAX) proofs.delete(proofs.keys().next().value as string);
44 const token = randomBytes(24).toString("hex");
45 proofs.set(token, { bind: bindOf(grant, host), until: now + PROOF_TTL_MS });
46 return token;
47 }
48
49 /** Spend `token`: true once, for the grant and host it was issued for. */
50 function spendProof(token: string | null, grant: string | undefined, host: string | null): boolean {
51 if (token === null || grant === undefined || host === null) return false;
52 const have = proofs.get(token);
53 if (have === undefined) return false;
54 proofs.delete(token);
55 return have.until > Date.now() && have.bind === bindOf(grant, host);
56 }
2557
2658 export interface FeedbackAsk {
2759 readonly app: App;
@@ -34,6 +66,8 @@ export interface FeedbackAsk {
3466 readonly sealed: boolean;
3567 /** The person the app's grant names, if any. */
3668 readonly viewerId: string | undefined;
69 /** The grant cookie's value the viewer came with, which a proof is bound to. */
70 readonly grant?: string | undefined;
3771 readonly secure: boolean;
3872 /** The client's limit key, from the socket (`clientBucket`). */
3973 readonly source: string;
@@ -85,8 +119,8 @@ function doorFor(ask: FeedbackAsk): Door | undefined {
85119 }
86120
87121 /** The sender: a person's key and name, or the anonymous cookie's. */
88 function senderOf(ask: FeedbackAsk, door: Door): { sender: Sender; fresh?: string } {
89 if (door.viewer !== undefined)
122 function senderOf(ask: FeedbackAsk, door: Door, proven: boolean): { sender: Sender; fresh?: string } {
123 if (proven && door.viewer !== undefined)
90124 return { sender: { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true } };
91125 const have = cookieOf(ask.request, VISITOR_COOKIE);
92126 const cookie = have !== undefined && /^[0-9a-f]{32}$/.test(have) ? have : undefined;
@@ -124,12 +158,12 @@ async function readJson(request: Request): Promise<Record<string, unknown> | und
124158 }
125159 }
126160
127 async function send(ask: FeedbackAsk, door: Door): Promise<Response> {
161 async function send(ask: FeedbackAsk, door: Door, proven: boolean, next: Record<string, string>): Promise<Response> {
128162 const { request } = ask;
129163 const body = await readJson(request);
130164 if (body === undefined) return json(400, { error: "bad_request", message: "That did not go through. Try again." });
131 const { sender, fresh } = senderOf(ask, door);
132 const cookies = fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) };
165 const { sender, fresh } = senderOf(ask, door, proven);
166 const cookies = fresh === undefined ? next : { ...next, "set-cookie": visitorCookie(fresh, ask.secure) };
133167 let page = "";
134168 if (typeof body.page === "string") {
135169 try {

Error returns earlier in send() (bad_request, filtered, rate limited) drop next; the spent token is lost and the panel is stuck at 409. Return next headers on every answer.

@@ -154,16 +188,32 @@ async function send(ask: FeedbackAsk, door: Door): Promise<Response> {
154188 return json(201, { note: sent.value, name: sender.name }, cookies);
155189 }
156190
157 function list(ask: FeedbackAsk, door: Door): Response {
158 const { sender, fresh } = senderOf(ask, door);
191 function list(ask: FeedbackAsk, door: Door, proven: boolean, next: Record<string, string>): Response {
192 const { sender, fresh } = senderOf(ask, door, proven);
159193 const notes = notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender);
160194 return json(
161195 200,
162 { name: sender.name, notes, admin: door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
163 fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) },
196 { name: sender.name, notes, admin: proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) },
197 fresh === undefined ? next : { ...next, "set-cookie": visitorCookie(fresh, ask.secure) },
164198 );
165199 }
166200
201 /**
202 * Whether the request carries the panel's proof, and the header for the next
203 * one. A proof that is presented but does not hold (spent, expired, lost to a
204 * restart, another tab's) is `stale`: the panel is told, not left to file as a
outdated

No next token is issued when the presented proof fails, so the panel stays a visitor until a reload, with no message. Answer an invalid proof with a worded error the panel can show.

205 * visitor unseen.
206 */
207 function proof(ask: FeedbackAsk, door: Door): { proven: boolean; stale: boolean; next: Record<string, string> } {
208 const host = ask.request.headers.get("host");
209 const presented = ask.request.headers.get(PROOF_HEADER);
210 const ok = spendProof(presented, ask.grant, host) && door.viewer !== undefined;
211 const next = ok && ask.grant !== undefined && host !== null ? { [PROOF_HEADER]: issueProof(ask.grant, host) } : {};
212 return { proven: ok, stale: presented !== null && !ok, next };
213 }
214
215 const STALE = { error: "stale_proof", message: "Reload the page to send as yourself." };
216
167217 /** Answer a `/__forge/note*` request; `undefined` when the path is not one. */
168218 export async function feedback(ask: FeedbackAsk): Promise<Response | undefined> {
169219 const path = ask.url.pathname;
@@ -174,9 +224,13 @@ export async function feedback(ask: FeedbackAsk): Promise<Response | undefined>
174224 if (door === undefined) return json(404, { error: "not_found" });
175225 if (path === "/__forge/notes") {
176226 if (method !== "GET") return json(405, { error: "method" }, { allow: "GET" });
177 return list(ask, door);
227 const { proven, stale, next } = proof(ask, door);
228 if (stale) return json(409, STALE);
229 return list(ask, door, proven, next);
178230 }
179231 if (method !== "POST") return json(405, { error: "method" }, { allow: "POST" });
180232 if (!sameOrigin(ask.request)) return json(403, { error: "cross_origin" });
181 return send(ask, door);
233 const { proven, stale, next } = proof(ask, door);
234 if (stale) return json(409, STALE);
235 return send(ask, door, proven, next);
182236 }
src/apps/proxy.ts +36 −6
@@ -36,7 +36,7 @@ import { loadKey } from "../kernel/secret.ts";
3636 import { previewEnv, type EnvName } from "./data.ts";
3737 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
3838 import { crewNow, tellLink } from "./crew.ts";
39 import { feedback } from "./feedback.ts";
39 import { feedback, issueProof } from "./feedback.ts";
4040 import { clientBucket } from "../http/peer.ts";
4141 import { doorPage } from "./door.ts";
4242 import { notFound } from "../http/respond.ts";
@@ -375,6 +375,33 @@ function sealedPull(runtime: AppsRuntime, target: AppTarget): Issue | undefined
375375 return pull?.sealed === true ? pull : undefined;
376376 }
377377
378 /**
379 * The pill with the note door's proof (#4940), for a signed-in person's own
380 * page navigation only: a script's fetch says `empty`, its iframe says `iframe`,
381 * its popup lacks the user flag; none is given a token.
382 */
383 function withProof(
384 where: PillWhere,
385 who: GrantWho | undefined,
386 request: Request,
387 target: AppTarget,
388 ): PillWhere {
389 const grant = cookieValue(request, grantCookieName(target));
390 const host = request.headers.get("host");
391 const dest = request.headers.get("sec-fetch-dest");
392 if (who === undefined || grant === undefined || host === null) return where;
393 // Never an iframe, and never a same-origin document the person did not ask
outdated

Accepting dest=iframe with no Sec-Fetch-Site check lets the app's own script obtain a token by embedding a same-origin iframe of the page. Require sec-fetch-site !== same-origin when dest is iframe, and test it.

394 // for: the app's own script can embed or open its own page and read the tag.
395 // A same-origin navigation counts only with the user's activation.
396 if (dest !== null && dest !== "document") return where;
397 if (
398 request.headers.get("sec-fetch-site") === "same-origin" &&
399 request.headers.get("sec-fetch-user") !== "?1"
400 )
401 return where;
402 return { ...where, proof: issueProof(grant, host) };
403 }
404
378405 /**
379406 * What the pill says: the app, the environment and, for a preview, the pull
380407 * and its title. The title goes only to a viewer who may read the pull.
@@ -673,6 +700,7 @@ export async function proxyApp(
673700 env: target.env,
674701 sealed,
675702 viewerId,
703 grant: cookie,
676704 secure:
677705 url.protocol === "https:" ||
678706 request.headers.get("x-forwarded-proto") === "https",
@@ -811,11 +839,13 @@ export async function proxyApp(
811839 } catch {
812840 return unavailable(runtime, target, status, "the app stopped answering");
813841 }
814 const page = withToolbar(
815 bytes,
816 runtime.options.forgeUrl,
817 pillWhere(runtime, target, vouched?.who),
818 );
842 const where = withProof(pillWhere(runtime, target, vouched?.who), vouched?.who, request, target);
843 const page = withToolbar(bytes, runtime.options.forgeUrl, where);
844 // A page with a one-use token is one person's, once: no cache keeps it.
845 if (where.proof !== undefined) {
846 out.set("cache-control", "private, no-store");
847 out.append("vary", "cookie");
848 }
819849 let sent = page;
820850 // Whether it is gzipped depends on the client, so every copy says so.
821851 out.append("vary", "accept-encoding");
src/apps/toolbar.ts +29 −3
@@ -30,6 +30,28 @@ export const toolbarJs = `(function () {
3030 var pill = document.createElement("button");
3131 pill.type = "button";
3232 var d = me.dataset || {};
33 // The note door's proof is the panel's alone: taken off the tag at once,
34 // used once per request, and handed on by each answer.
35 var proof = d.proof || "";
36 var signed = !!proof;
37 try { me.removeAttribute("data-proof"); } catch (e) {}
38 var chain = Promise.resolve();
39 function call(url, init) {
40 var run = function () {
41 init.headers = init.headers || {};
42 // Once given a proof, always present one: a lost chain is told so (409).
43 if (signed) init.headers["x-forge-proof"] = proof || "-";

proof is cleared before fetch; on a rejected fetch the chain is lost. Restore it in a catch handler.

44 proof = "";
45 return fetch(url, init).then(function (r) {
46 var next = r.headers.get("x-forge-proof");
47 if (next) proof = next;
48 return r;
49 });
50 };
51 var p = chain.then(run, run);
52 chain = p.catch(function () {});
53 return p;
54 }
3355 var where = d.env === "production" ? "production" : d.pull ? "preview of pull #" + d.pull : "";
3456 pill.setAttribute("aria-label", [d.app, where].filter(Boolean).join(", ") || "Forge");
3557 pill.setAttribute("aria-expanded", "false");
@@ -140,9 +162,10 @@ export const toolbarJs = `(function () {
140162 });
141163 }
142164 function refresh(sent) {
143 fetch("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
144 .then(function (r) { return r.ok ? r.json() : null; })
165 call("/__forge/notes", { credentials: "same-origin", cache: "no-store" })
166 .then(function (r) { return r.ok || r.status === 409 ? r.json() : null; })
145167 .then(function (j) {
168 if (j && j.error === "stale_proof") { tellSay.textContent = j.message; return; }
146169 if (!j || !Array.isArray(j.notes)) return;
147170 show(j.notes);
148171 // A browser that keeps no cookie cannot be told which notes are its own.
@@ -159,7 +182,7 @@ export const toolbarJs = `(function () {
159182 tellGo.setAttribute("aria-busy", "true");
160183 tellGo.style.opacity = ".6";
161184 function idle() { tellGo.disabled = false; tellGo.removeAttribute("aria-busy"); tellGo.style.opacity = "1"; }
162 fetch("/__forge/note", {
185 call("/__forge/note", {
163186 method: "POST",
164187 credentials: "same-origin",
165188 headers: { "content-type": "application/json" },
@@ -407,6 +430,8 @@ export type PillWhere = {
407430 env: string;
408431 pull?: number;
409432 title?: string;
433 /** The note door's one-use proof for a signed-in person's page (#4940). */
434 proof?: string;
410435 };
411436
412437 /** `text` safe inside a double-quoted HTML attribute. */
@@ -430,6 +455,7 @@ export function toolbarTag(forgeUrl: string, where?: PillWhere): string {
430455 ["env", where.env],
431456 ["pull", where.pull === undefined ? undefined : String(where.pull)],
432457 ["title", where.title],
458 ["proof", where.proof],
433459 ]
434460 .filter((pair): pair is [string, string] => pair[1] !== undefined)
435461 .map(([k, v]) => ` data-${k}="${escapeAttr(v)}"`)
test/apps-crew-pill.test.ts +2 −2
@@ -198,8 +198,8 @@ describe("the crew line", () => {
198198 test("the script asks once, same-origin, and never reads the page or its cookies", () => {
199199 expect(toolbarJs).toContain("/__forge/crew");
200200 // The crew line is asked once; the feedback door (#4758) adds the
201 // sender's notes, polled only while the panel is open, and the send.
202 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
201 // sender's notes, polled only while the panel is open, and the send, through the one call that carries the door's proof (#4940).
202 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2);
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 +70 −4
@@ -13,7 +13,7 @@ import { newApp } from "../src/actions/apps.ts";
1313 import { AppsRuntime } from "../src/apps/runtime.ts";
1414 import { toolbarJs } from "../src/apps/toolbar.ts";
1515 import { filtered, moderateNote, noteClock, PER_APP_DAY, PER_SENDER, PER_SOURCE, saysFromApp } from "../src/actions/app_notes.ts";
16 import { feedback, REQUEST_MAX } from "../src/apps/feedback.ts";
16 import { feedback, issueProof, PROOF_HEADER, REQUEST_MAX } from "../src/apps/feedback.ts";
1717 import { getAppBySlug } from "../src/core/apps.ts";
1818 import { getNote } from "../src/core/app_notes.ts";
1919 import { grantedCookie } from "./helpers/identity.ts";
@@ -85,6 +85,9 @@ describe("the forge button takes notes from anyone", () => {
8585 });
8686 const post = (text: string, cookie = "", source = "", slug = "notes") =>
8787 at(slug, "/__forge/note", { method: "POST", body: JSON.stringify({ text, page: `http://${host(slug)}/lists?x=1`, viewport: "390x844" }) }, cookie, source);
88 const proofFor = (cookie: string, slug: string) => issueProof(cookie.slice(cookie.indexOf("=") + 1), host(slug));
89 const posted = (text: string, cookie: string, source: string, slug: string, proof: string) =>
90 at(slug, "/__forge/note", { method: "POST", headers: { [PROOF_HEADER]: proof }, body: JSON.stringify({ text, viewport: "390x844" }) }, cookie, source);
8891 const cookieOf = (res: Response) => (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
8992
9093 test("a visitor's note files a from-app issue with page, viewport and time", async () => {
@@ -192,6 +195,67 @@ describe("the forge button takes notes from anyone", () => {
192195 expect((await post("still open", "", "", "notes")).status).toBe(201);
193196 });
194197
198 test("a signed-in person's note is theirs only with the panel's one-use proof (#4940)", async () => {
199 const owner = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
200 // The app's own script: same origin, the grant cookie, no proof.
201 const bare = await post("filed by the page's script", owner, "10.6.0.1", "diary");
202 expect(bare.status).toBe(201);
203 expect(((await bare.json()) as { name: string }).name).toMatch(/^visitor-[0-9a-f]{6}$/);
204 // The panel's POST with the proof is the person's, and hands on the next.
205 const token = proofFor(owner, "diary");
206 const good = await posted("filed by the panel", owner, "10.6.0.2", "diary", token);
207 expect(good.status).toBe(201);
208 expect(((await good.json()) as { name: string }).name).toBe("@alice");
209 const next = good.headers.get(PROOF_HEADER)!;
210 expect(next).toMatch(/^[0-9a-f]{48}$/);
211 // A reused token files nothing and says to reload.
212 const reused = await posted("again", owner, "10.6.0.3", "diary", token);
213 expect(reused.status).toBe(409);
214 // A token issued for someone else's grant, or another host, is refused.
215 const foreign = await posted("foreign", owner, "10.6.0.4", "diary", issueProof("another-grant", host("diary")));
216 expect(foreign.status).toBe(409);
217 const elsewhere = await posted("elsewhere", owner, "10.6.0.5", "diary", issueProof(owner.slice(owner.indexOf("=") + 1), host("notes")));
218 expect(elsewhere.status).toBe(409);
219 // The listing: the person's notes only with the proof, one use each.
220 const listed = async (proof?: string) =>
221 (await (await at("diary", "/__forge/notes", { headers: proof === undefined ? {} : { [PROOF_HEADER]: proof } }, owner)).json()) as { name: string; notes: { text: string }[] };
222 expect((await listed()).name).toMatch(/^visitor-/);
223 const mine = await listed(next);
224 expect(mine.name).toBe("@alice");
225 expect(mine.notes.map((n) => n.text)).toContain("filed by the panel");
226 expect((await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: next } }, owner)).status).toBe(409);
227 });
228
229 test("a presented proof that does not hold is told to reload, and files nothing (#4940)", async () => {
230 const owner = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
231 const repo = getRepo(app.db, "alice", "diary")!;
232 const count = () => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?1").get(repo.id)!.n;
233 const before = count();
234 const token = proofFor(owner, "diary");
235 expect((await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: token } }, owner)).status).toBe(200);
236 for (const bad of [token, "-", "f".repeat(48)]) {
237 const res = await posted("late", owner, "10.7.0.2", "diary", bad);
238 expect(res.status).toBe(409);
239 expect(((await res.json()) as { message: string }).message).toBe("Reload the page to send as yourself.");
240 }
241 const list = await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: "-" } }, owner);
242 expect(list.status).toBe(409);
243 expect(count()).toBe(before);
244 });
245
246 test("a proof is good for six hours and no longer (#4940)", async () => {
247 const owner = await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!);
248 const grant = owner.slice(owner.indexOf("=") + 1);
249 const list = (token: string) => at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: token } }, owner);
250 expect((await list(issueProof(grant, host("diary"), Date.now() - 5 * 3600_000))).status).toBe(200);
251 expect((await list(issueProof(grant, host("diary"), Date.now() - 7 * 3600_000))).status).toBe(409);
252 });
253
254 test("the pill's tag carries a proof for a signed-in page navigation only", () => {
255 expect(toolbarJs).toContain("x-forge-proof");
256 expect(toolbarJs).toContain('removeAttribute("data-proof")');
257 });
258
195259 test("the word filter and the rate limit apply", async () => {
196260 const rude = await post("this is sh1t", "", "10.0.0.3");
197261 expect(rude.status).toBe(422);
@@ -299,15 +363,17 @@ describe("the forge button takes notes from anyone", () => {
299363
300364 test("a private app takes notes from a signed-in reader, as themselves, and from no one else", async () => {
301365 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");
366 const res = await posted("A note on the diary", reader, "10.5.0.1", "diary", proofFor(reader, "diary"));
303367 expect(res.status).toBe(201);
304368 expect(((await res.json()) as { name: string }).name).toBe("@alice");
305369 const repo = getRepo(app.db, "alice", "diary")!;
306370 const issue = app.db.query<{ body: string }, [string]>("SELECT body FROM issue WHERE repo_id = ?1 ORDER BY number DESC").get(repo.id)!;
307371 expect(issue.body).toContain("by @alice.");
308372 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);
373 const more = await posted("second", reader, "10.5.0.2", "diary", res.headers.get(PROOF_HEADER)!);
374 expect(more.status).toBe(201);
375 const mine = (await (await at("diary", "/__forge/notes", { headers: { [PROOF_HEADER]: more.headers.get(PROOF_HEADER)! } }, reader)).json()) as { notes: unknown[]; admin: boolean };
376 expect(mine.notes.length).toBeGreaterThanOrEqual(2);
311377 expect(mine.admin).toBe(true);
312378 expect((await at("diary", "/__forge/notes")).status).toBe(404);
313379 });
test/apps-toolbar.test.ts +98 −1
@@ -18,7 +18,9 @@ import { listRuns } from "../src/core/runs.ts";
1818 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1919 import { parseManifest } from "../src/apps/manifest.ts";
2020 import { REWRITE_MAX, TOOLBAR_PATH, readPage, toolbarJs, withToolbar } from "../src/apps/toolbar.ts";
21 import { createUser } from "../src/core/users.ts";
21 import { getAppBySlug } from "../src/core/apps.ts";
22 import { grantedCookie } from "./helpers/identity.ts";
23 import { createUser, getUserByName } from "../src/core/users.ts";
2224 import { serve, type Servers } from "../src/http/server.ts";
2325 import { quietLogs } from "./helpers/globals.ts";
2426
@@ -55,6 +57,10 @@ describe("the forge pill", () => {
5557 })
5658 : new Response(HTML, { headers });
5759 }
60 if (path === "/cached")
61 return new Response(HTML, {
62 headers: { ...html, "cache-control": "public, max-age=3600", etag: '"v1"' },
63 });
5864 if (path === "/json") return Response.json({ a: 1 });
5965 if (path === "/img") return new Response(PNG, { headers: { "content-type": "image/png" } });
6066 if (path === "/bare") return new Response("<p>no body tag</p>", { headers: html });
@@ -189,6 +195,39 @@ describe("the forge pill", () => {
189195 const tag = () =>
190196 `<script src="${servers.url}${TOOLBAR_PATH}" data-app="notes" data-repo="alice/notes" data-env="production" defer></script>`;
191197
198 test("a page carrying a one-use proof is private and uncached; a stranger's keeps the app's headers (#4940)", async () => {
199 toolbar = undefined;
200 const record = getAppBySlug(app.db, "notes")!;
201 const alice = getUserByName(app.db, "alice")!;
202 const cookie = await grantedCookie(app, servers.url, alice, record);
203 const signed = await fetch(`${servers.url}/cached`, {
204 headers: { host: `notes.${DOMAIN}`, accept: "text/html", cookie },
205 redirect: "manual",
206 });
207 expect(await signed.text()).toMatch(/data-proof="[0-9a-f]{48}"/);
208 expect(signed.headers.get("cache-control")).toBe("private, no-store");
209 expect(signed.headers.get("vary")).toContain("cookie");
210 // The app's own script embedding or opening its own page is given none.
211 const page = async (extra: Record<string, string>) =>
212 (
213 await fetch(`${servers.url}/cached`, {
214 headers: { host: `notes.${DOMAIN}`, accept: "text/html", cookie, ...extra },
215 redirect: "manual",
216 })
217 ).text();
218 expect(await page({ "sec-fetch-dest": "iframe", "sec-fetch-site": "same-origin" })).not.toContain("data-proof");
219 expect(await page({ "sec-fetch-dest": "iframe", "sec-fetch-site": "none" })).not.toContain("data-proof");
220 expect(await page({ "sec-fetch-dest": "empty" })).not.toContain("data-proof");
221 expect(await page({ "sec-fetch-dest": "document", "sec-fetch-site": "same-origin" })).not.toContain("data-proof");
222 // The person's own navigation: typed, followed from elsewhere, or clicked within the app.
223 expect(await page({ "sec-fetch-dest": "document", "sec-fetch-site": "none", "sec-fetch-user": "?1" })).toContain("data-proof");
224 expect(await page({ "sec-fetch-dest": "document", "sec-fetch-site": "cross-site" })).toContain("data-proof");
225 expect(await page({ "sec-fetch-dest": "document", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1" })).toContain("data-proof");
226 const stranger = await at("/cached");
227 expect(await stranger.text()).not.toContain("data-proof");
228 expect(stranger.headers.get("cache-control")).toBe("public, max-age=3600");
229 });
230
192231 test("HTML gets one script tag before </body>, with its length fixed", async () => {
193232 toolbar = undefined;
194233 const res = await at("/");
@@ -404,6 +443,7 @@ describe("the pill's keyboard and touch behaviour", () => {
404443 tabIndex?: number;
405444 focused: boolean;
406445 setAttribute(k: string, v: string): void;
446 removeAttribute(k: string): void;
407447 appendChild(c: El): El;
408448 addEventListener(t: string, f: (e?: unknown) => void): void;
409449 focus(): void;
@@ -419,6 +459,7 @@ describe("the pill's keyboard and touch behaviour", () => {
419459 textContent: "",
420460 focused: false,
421461 setAttribute(k, v) { this.attrs[k] = v; },
462 removeAttribute(k) { delete this.attrs[k]; },
422463 appendChild(c) { this.children.push(c); return c; },
423464 addEventListener(t, f) { (this.listeners[t] ??= []).push(f); },
424465 focus() { this.focused = true; },
@@ -449,6 +490,62 @@ describe("the pill's keyboard and touch behaviour", () => {
449490 }
450491
451492
493 test("run: each request carries the proof, the next comes from the answer, a lost chain is told", async () => {
494 const calls: { url: string; proof: string | undefined }[] = [];
495 const answers = [
496 { status: 200, next: "t2", body: { notes: [] } },
497 { status: 201, next: "t3", body: { note: {}, name: "@alice" } },
498 { status: 200, next: "t4", body: { notes: [] } },
499 { status: 409, next: null, body: { error: "stale_proof", message: "Reload the page to send as yourself." } },
500 ];
501 let attrs: string[] = [];
502 const fetchStub = async (url: string, init: { headers?: Record<string, string> }) => {
503 if (url === "/__forge/crew")
504 return { ok: false, status: 404, headers: { get: () => null }, json: async () => ({}) };
505 calls.push({ url, proof: init.headers?.["x-forge-proof"] });
506 const a = answers[calls.length - 1]!;
507 return {
508 ok: a.status < 300,
509 status: a.status,
510 headers: { get: (k: string) => (k === "x-forge-proof" ? a.next : null) },
511 json: async () => a.body,
512 };
513 };
514 let root!: El;
515 const doc = {
516 currentScript: {
517 src: "https://forge.test/assets/t.js",
518 dataset: { app: "notes", env: "production", proof: "t1" },
519 removeAttribute: (k: string) => attrs.push(k),
520 },
521 createElement: (tag: string): El => {
522 const el = make(tag);
523 el.attachShadow = () => (root = make("shadow"));
524 return el;
525 },
526 body: { appendChild: () => undefined },
527 addEventListener: () => undefined,
528 };
529 new Function("window", "document", "URL", "fetch", "location", toolbarJs)({ innerWidth: 390, innerHeight: 844 }, doc, URL, fetchStub, { href: "https://notes.test/" });
530 expect(attrs).toEqual(["data-proof"]);
531 const els = all(root);
532 const pill = els.find((e) => e.tag === "button")!;
533 const form = els.find((e) => e.tag === "form")!;
534 const text = els.find((e) => e.tag === "textarea") as El & { value: string };
535 const say = form.children.find((e) => e.attrs["aria-live"] === "polite")!;
536 const flush = () => new Promise((r) => setTimeout(r, 5));
537 pill.listeners.click![0]!(); // opens: lists with t1
538 text.value = "hello";
539 form.listeners.submit![0]!({ preventDefault() {} }); // queued behind the list: t2
540 await flush();
541 expect(calls.map((c) => c.proof)).toEqual(["t1", "t2", "t3"]);
542 text.value = "again";
543 form.listeners.submit![0]!({ preventDefault() {} }); // the refresh took t3, so this takes t4, answered 409
544 await flush();
545 expect(calls.map((c) => c.proof)).toEqual(["t1", "t2", "t3", "t4"]);
546 expect(say.textContent).toBe("Reload the page to send as yourself.");
547 });
548
452549 test("the panel is a labelled region, opens with focus inside, and Escape returns focus to the pill", () => {
453550 const { doc, pill, panel } = tree({ app: "notes", env: "production" });
454551 expect(panel.attrs["aria-label"]).toBeTruthy();
test/toolbar-actions.test.ts +5 −3
@@ -89,10 +89,12 @@ describe("toolbar actions", () => {
8989 test("the bar links to the forge page and never posts or reads the app", () => {
9090 expect(toolbarJs).toContain('"/toolbar"');
9191 // Its requests are all to the app's own origin: the crew line (#2233) and,
92 // for the feedback door (#4758), the sender's notes and their status.
93 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(3);
92 // for the feedback door (#4758), the sender's notes and their status,
93 // which go through the one `call` that carries the door's proof (#4940).
94 expect(toolbarJs.match(/fetch\(/g)?.length).toBe(2);
9495 expect(toolbarJs).toContain('fetch("/__forge/crew"');
95 expect(toolbarJs).toContain('fetch("/__forge/note"');
96 expect(toolbarJs).toContain("return fetch(url, init)");
97 expect(toolbarJs.match(/call\("\/__forge\/notes?"/g)?.length).toBe(2);
9698 expect(toolbarJs).not.toMatch(/FormData|\.send\(/);
9799 expect(toolbarJs).not.toContain("XMLHttpRequest");
98100 expect(toolbarJs).not.toContain("document.cookie");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs