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

A preview's forge toolbar names the pull it previews and links to it #13148

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13128-a-preview-s-forge-toolbar-names-the-pull → main 5 commits fork

  • Merged. scout/13128-a-preview-s-forge-toolbar-names-the-pull was merged into main as bf06085.

Review

Sign in to review this change.
7 files changed +85 −31
src/apps/proxy.ts +9 −5
@@ -440,9 +440,9 @@ function sealedPull(runtime: AppsRuntime, target: AppTarget): Issue | undefined
440440 /**
441441 * The response with the phases the request named, as `Server-Timing`: the
442442 * one writer for the proxy, on the forge's own `/__forge/*` pages and, for
443 * a reader who may see them (`relayAnswer`), on a relayed app answer. It appends, so an app's own entries stay first;
444 * on an app answer the forge's phases are `forge-` named (`relayPhase`) so
445 * none can collide with the app's or with the server's `route`.
443 * a reader who may see them (`relayAnswer`), on a relayed app answer. It appends, so an app's own
444 * entries stay first; on an app answer the forge's phases are `forge-` named (`relayPhase`) so none
445 * can collide with the app's or with the server's `route`.
446446 */
447447 function withPhases(request: Request, res: Response): Response {
448448 const phases = takePhases(request);
@@ -579,13 +579,15 @@ export function pillWhere(
579579 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
580580 if (number === undefined) return where;
581581 where.pull = Number(number);
582 // What a waiting guest's preview runs on is said to whoever looks at it: it is about the page in front of them.
582 // What a waiting guest's preview runs on is said to whoever looks at it: it is about the page in
583 // front of them.
583584 const row = getPull(db, target.app.repoId, where.pull);
584585 if (row !== undefined && guestWaits(db, row)) where.waits = true;
585586 const pull = getIssue(db, target.app.repoId, where.pull);
586587 if (pull === undefined) return where;
587588 if (!reads || !mayView(db, repo, pull, user)) return where;
588589 where.title = pull.title;
590 if (row !== undefined && row.headBranch !== "") where.branch = row.headBranch;
589591 const head = getPull(db, target.app.repoId, where.pull);
590592 if (head !== undefined && head.headOid !== "") where.check = pillCheck(db, pull.id, head.headOid);
591593 // How current the preview is: the row's head against the commit it runs. A
@@ -671,7 +673,9 @@ function sideFor(
671673 return sideForViewer(runtime, target.app, target.env, getUserById(runtime.app.db, who.id));
672674 }
673675
674 /** The repository, when `viewer` is an active reader of it: the only one the other side is told to. */
676 /**
677 * The repository, when `viewer` is an active reader of it: the only one the other side is told to.
678 */
675679 export function sideReader(db: App["db"], record: AppRecord, viewer: User | undefined): Repo | undefined {
676680 if (viewer === undefined || !isActive(viewer)) return undefined;
677681 const repo = getRepoById(db, record.repoId);
src/apps/toolbar.ts +40 −14
@@ -24,10 +24,15 @@ export const FRESHNESS_WORDS = {
2424 behind: "Shows an older push than the pull's newest",
2525 } as const;
2626
27 /** What the pill says on a guest pull's preview nobody has approved yet; sent with the tag, so the script carries no copy. */
27 /**
28 * What the pill says on a guest pull's preview nobody has approved yet; sent with the tag, so the
29 * script carries no copy.
30 */
2831 export const PREVIEW_WAITS = "This preview uses empty data until a writer approves the pull";
2932
30 /** The client, as plain source: no `eval`, no inline handlers. Its comments are for readers here. */
33 /**
34 * The client, as plain source: no `eval`, no inline handlers. Its comments are for readers here.
35 */
3136 const toolbarSource = `(function () {
3237 if (window.__forgeToolbar) return;
3338 window.__forgeToolbar = true;
@@ -92,21 +97,22 @@ const toolbarSource = `(function () {
9297 if (d.env === "production") line("production");
9398 var LC = "#8ab4ff";
9499 var LS = "color:" + LC + ";text-decoration:none;display:flex;align-items:center;min-height:44px";
95 var pullHref = "";
100 var pullHref = "", pv = d.env !== "production" && d.pull;
96101 // The pull this preview shows, one tap away: built from the script's own origin, never from page text.
97 if (d.env !== "production" && /^\\d{1,9}$/.test(d.pull || "") && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "")) {
102 if (pv && /^\\d{1,9}$/.test(d.pull) && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "")) {
98103 try { pullHref = new URL("/" + d.repo + "/pulls/" + d.pull, fo).href; } catch (e) {}
99104 }
100 if (d.env === "production") {}
101 else if (pullHref) {
105 if (pullHref) {
102106 var pl = document.createElement("a");
103 pl.textContent = "preview \\u00b7 #" + d.pull;
107 pl.textContent = "Pull #" + d.pull;
104108 pl.href = pullHref;
105109 pl.rel = "noopener";
106110 pl.style.cssText = LS;
107111 panel.appendChild(pl);
108 } else if (d.pull) line("preview \\u00b7 #" + d.pull);
112 } else if (pv) line("Pull #" + d.pull);
113 if (pv) line("Environment: preview");
109114 if (d.title) line(d.title);
115 if (pv && d.branch) line("Branch: " + d.branch);
110116 var CW = ${JSON.stringify(CHECK_WORDS)};
111117 if (d.env !== "production" && d.check && Object.prototype.hasOwnProperty.call(CW, d.check)) line(CW[d.check]);
112118 // Whether this is the pull as it stands now; an open, current preview says nothing.
@@ -605,7 +611,10 @@ const toolbarSource = `(function () {
605611 })();
606612 `;
607613
608 /** What is served: the source without its whole-line comments, so the notes cost the pill none of its 24 KB (#10869). */
614 /**
615 * What is served: the source without its whole-line comments, so the notes cost the pill none of
616 * its 24 KB (#10869).
617 */
609618 export const toolbarJs = toolbarSource.replace(/^[ \t]*\/\/[^\n]*\n/gm, "");
610619
611620 const hash = sha256(toolbarJs);
@@ -617,7 +626,9 @@ export const TOOLBAR_NAME = name;
617626
618627 /** The same script on an app's own host, where a strict `script-src 'self'` allows it. */
619628 export const TOOLBAR_ASSET_PATH = `/__forge/${name}.js`;
620 /** Every path under this prefix on an app host is the forge's, whether or not it names the script. */
629 /**
630 * Every path under this prefix on an app host is the forge's, whether or not it names the script.
631 */
621632 export const TOOLBAR_ASSET_PREFIX = "/__forge/toolbar";
622633
623634 /** The forge's answer for the script: immutable, because its name is its hash. */
@@ -670,17 +681,25 @@ export type PillWhere = {
670681 env: string;
671682 pull?: number;
672683 title?: string;
684 /** The pull's head branch, for a reader of the pull only. */
685 branch?: string;
673686 /** Whether the pull is open, merged or closed; for a reader of the pull only. */
674687 state?: "open" | "merged" | "closed";
675688 /** The preview runs a commit that is not the pull's head (and none is deploying). */
676689 behind?: boolean;
677690 /** A newer commit is being deployed now. */
678691 deploying?: boolean;
679 /** The pull is a guest's nobody has approved yet: its preview runs on empty data, without the app's variables. */
692 /**
693 * The pull is a guest's nobody has approved yet: its preview runs on empty data, without the
694 * app's variables.
695 */
680696 waits?: boolean;
681697 /** The newest check of the pull's head, a key of `CHECK_WORDS`. */
682698 check?: PillCheck;
683 /** The commit the environment is serving and the instant it went live, from the forge's own record. */
699 /**
700 * The commit the environment is serving and the instant it went live, from the forge's own
701 * record.
702 */
684703 serving?: { oid: string; at: string };
685704 };
686705
@@ -729,6 +748,7 @@ export function toolbarTag(
729748 ["env", where.env],
730749 ["pull", where.pull === undefined ? undefined : String(where.pull)],
731750 ["title", where.title],
751 ["branch", where.branch],
732752 ["state", where.state],
733753 ["check", where.check],
734754 ["commit", where.serving?.oid],
@@ -758,7 +778,10 @@ function lastBodyClose(buffer: Buffer): number {
758778 return -1;
759779 }
760780
761 /** The opening of the tag the proxy writes, with the hashed name: what a page that has the toolbar contains. */
781 /**
782 * The opening of the tag the proxy writes, with the hashed name: what a page that has the toolbar
783 * contains.
784 */
762785 const TAG_OPEN = Buffer.from(`<script src="${TOOLBAR_ASSET_PATH}"`);
763786
764787 /**
@@ -770,7 +793,10 @@ export function carriesToolbar(bytes: Uint8Array): boolean {
770793 return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).includes(TAG_OPEN);
771794 }
772795
773 /** `bytes` with the pill's tag before the last `</body>`, or at the end; a page that has one is returned as it is. */
796 /**
797 * `bytes` with the pill's tag before the last `</body>`, or at the end; a page that has one is
798 * returned as it is.
799 */
774800 export function withToolbar(
775801 bytes: Uint8Array,
776802 forgeUrl: string,
test/apps-pill-freshness.test.ts +2 −2
@@ -269,14 +269,14 @@ describe("the pill's script draws the freshness line", () => {
269269 ];
270270 for (const [extra, said] of cases) {
271271 const lines = panelLines({ ...base, ...extra });
272 expect(lines.slice(0, 4)).toEqual(["site", "preview \u00b7 #7", "Add a thing", said]);
272 expect(lines.slice(0, 5)).toEqual(["site", "Pull #7", "Environment: preview", "Add a thing", said]);
273273 expect(lines.filter((l) => words.includes(l as never))).toEqual([said]);
274274 }
275275 });
276276
277277 test("the line follows the pull when there is no title", () => {
278278 const lines = panelLines({ ...base, title: "", state: "merged" });
279 expect(lines.slice(0, 3)).toEqual(["site", "preview \u00b7 #7", FRESHNESS_WORDS.merged]);
279 expect(lines.slice(0, 4)).toEqual(["site", "Pull #7", "Environment: preview", FRESHNESS_WORDS.merged]);
280280 });
281281
282282 test("merged and closed win over deploying and behind; deploying wins over behind", () => {
test/apps-pill-where.test.ts +6
@@ -63,6 +63,10 @@ describe("the pill's data", () => {
6363 });
6464 if (!pull.ok) throw new Error(pull.error);
6565 pulls[name] = pull.value.number;
66 app.db.run(
67 "INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', ?2, '', '')",
68 [pull.value.id, `scout/${name}-branch`],
69 );
6670 }
6771 }, 120_000);
6872
@@ -87,12 +91,14 @@ describe("the pill's data", () => {
8791 expect(where.pull).toBe(pulls.open!);
8892 expect(where.env).toBe(`pull-${pulls.open}`);
8993 expect(where.title).toContain("onerror");
94 expect(where.branch).toBe("scout/open-branch");
9095 });
9196
9297 test("the title is withheld from a viewer who may not read the pull", () => {
9398 const anon = pillWhere(runtime, preview("closed"), undefined);
9499 expect(anon.pull).toBe(pulls.closed!);
95100 expect(anon.title).toBeUndefined();
101 expect(anon.branch).toBeUndefined();
96102 const owner = pillWhere(runtime, preview("closed"), { id: aliceId } as never);
97103 expect(owner.title).toContain("closed");
98104 });
test/apps-toolbar.test.ts +19 −4
@@ -17,7 +17,7 @@ import { getAppByRepo } from "../src/core/apps.ts";
1717 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";
20 import { REWRITE_MAX, TOOLBAR_ASSET_PATH, TOOLBAR_PATH, readPage, toolbarJs, withToolbar } from "../src/apps/toolbar.ts";
20 import { REWRITE_MAX, TOOLBAR_ASSET_PATH, TOOLBAR_PATH, readPage, toolbarJs, toolbarTag, withToolbar } from "../src/apps/toolbar.ts";
2121 import { createUser } from "../src/core/users.ts";
2222 import { serve, type Servers } from "../src/http/server.ts";
2323 import { quietLogs } from "./helpers/globals.ts";
@@ -476,23 +476,38 @@ describe("the pill's keyboard and touch behaviour", () => {
476476
477477
478478 test("on a preview with a repo the pull line links to the pull; otherwise it is plain text", () => {
479 const a = tree({ app: "notes", repo: "alice/notes", pull: "12" }).lines.find((l) => l.textContent === "preview \u00b7 #12")!;
479 const a = tree({ app: "notes", repo: "alice/notes", pull: "12" }).lines.find((l) => l.textContent === "Pull #12")!;
480480 expect(a.tag).toBe("a");
481481 expect(a.href).toBe("https://forge.test/alice/notes/pulls/12");
482482 expect(a.style.cssText).toContain("min-height:44px");
483483 const prod = tree({ app: "notes", repo: "alice/notes", env: "production", pull: "12" });
484 expect(prod.lines.some((l) => l.textContent.startsWith("preview \u00b7"))).toBe(false);
484 expect(prod.lines.some((l) => l.textContent.startsWith("Pull #"))).toBe(false);
485485 expect(prod.lines.some((l) => l.textContent === "production")).toBe(true);
486486 // An unknown environment with no pull draws no environment line at all.
487487 const unknown = tree({ app: "notes", repo: "alice/notes", env: "staging" });
488488 expect(unknown.lines.some((l) => l.textContent === "production" || l.textContent.startsWith("preview"))).toBe(false);
489489 for (const bad of [{ pull: "12x" }, { pull: "../1" }, { pull: "1234567890" }, { repo: "" }]) {
490490 const t = tree({ app: "notes", repo: "alice/notes", pull: "12", ...bad });
491 const l = t.lines.find((x) => x.textContent.startsWith("preview \u00b7"))!;
491 const l = t.lines.find((x) => x.textContent.startsWith("Pull #"))!;
492492 expect(l.tag === "a").toBe(false);
493493 }
494494 });
495495
496 test("a preview names its environment and branch in words; production shows neither", () => {
497 const t = tree({ app: "notes", repo: "alice/notes", env: "pull-12", pull: "12", branch: "scout/x" });
498 expect(t.lines.some((l) => l.textContent === "Environment: preview")).toBe(true);
499 expect(t.lines.some((l) => l.textContent === "Branch: scout/x")).toBe(true);
500 const prod = tree({ app: "notes", env: "production", branch: "scout/x" });
501 expect(prod.lines.some((l) => /^(Branch|Environment|Pull)/.test(l.textContent))).toBe(false);
502 });
503
504 test("the tag escapes the branch and title", () => {
505 const tag = toolbarTag("https://forge.test", { app: "a", env: "pull-1", pull: 1, title: '"><b>', branch: '"><script>' });
506 expect(tag).not.toContain("<b>");
507 expect(tag.match(/<script/g)!.length).toBe(1);
508 expect(tag).toContain('data-branch="&quot;&gt;&lt;script&gt;"');
509 });
510
496511 test("the panel is a labelled region, opens with focus inside, and Escape returns focus to the pill", () => {
497512 const { doc, pill, panel } = tree({ app: "notes", env: "production" });
498513 expect(panel.attrs["aria-label"]).toBeTruthy();
test/lost-journey.test.ts +6 −4
@@ -176,7 +176,9 @@ describe("lost journey: where you are and three exits", () => {
176176 const walk = (e: El): El[] => [e, ...e.children.flatMap(walk)];
177177 const unescape = (v: string) =>
178178 v.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
179 /** Boot the toolbar exactly as the browser would for the served tag, and let the crew answer land. */
179 /**
180 * Boot the toolbar exactly as the browser would for the served tag, and let the crew answer land.
181 */
180182 const boot = async (html: string, crew: object, href: string) => {
181183 const t = tagOf(html)!;
182184 const dataset: Record<string, string> = {};
@@ -229,7 +231,7 @@ describe("lost journey: where you are and three exits", () => {
229231 expect(focusable(home)).toBe(true);
230232 expect(home.href).toBe(`${origin}/`);
231233
232 const pullLink = run.named(`preview \u00b7 #${pull}`)!;
234 const pullLink = run.named(`Pull #${pull}`)!;
233235 expect(focusable(pullLink)).toBe(true);
234236 expect(pullLink.href).toBe(`${origin}/alice/public/pulls/${pull}`);
235237
@@ -259,7 +261,7 @@ describe("lost journey: where you are and three exits", () => {
259261 const html = await (await ask(host, "/", cookie)).text();
260262 const run = await boot(html, await crewOf(host, cookie), `http://${host}/`);
261263 expect(run.named("production")).toBeDefined();
262 expect(run.built.some((e) => String(e.textContent).startsWith("preview \u00b7"))).toBe(false);
264 expect(run.built.some((e) => String(e.textContent).startsWith("Pull #"))).toBe(false);
263265 expect(run.named("Home")!.href).toBe(`${new URL(servers.url).origin}/`);
264266 });
265267
@@ -272,7 +274,7 @@ describe("lost journey: where you are and three exits", () => {
272274 expect(tag[2]).toContain(` data-env="pull-${pull}"`);
273275 expect(tag[2]).toContain(` data-pull="${pull}"`);
274276 const run = await boot(html, await crewOf(host), `http://${host}/`);
275 expect(run.named(`preview \u00b7 #${pull}`)!.href).toBe(`${new URL(servers.url).origin}/alice/public/pulls/${pull}`);
277 expect(run.named(`Pull #${pull}`)!.href).toBe(`${new URL(servers.url).origin}/alice/public/pulls/${pull}`);
276278 expect(run.named("Home")).toBeDefined();
277279 expect(run.named("Tell the crew")).toBeUndefined();
278280 // Comment goes to the forge's own page, which asks the stranger to sign in there.
test/toolbar-injection.test.ts +3 −2
@@ -75,7 +75,8 @@ test("a nonce from the app's own policy rides on the tag; a policy without one a
7575 expect(toolbarTag(FORGE)).toContain('src="/__forge/');
7676 });
7777
78 // A source check only; the layout proof is the proxy tests in apps-toolbar.test.ts (data untouched, one tag).
78 // A source check only; the layout proof is the proxy tests in apps-toolbar.test.ts (data untouched,
79 // one tag).
7980 test("the pill overlays the page: fixed, out of flow, in a shadow root", () => {
8081 expect(toolbarJs).toContain("position:fixed");
8182 expect(toolbarJs).toContain("attachShadow");
@@ -85,6 +86,6 @@ test("the pill overlays the page: fixed, out of flow, in a shadow root", () => {
8586 });
8687
8788 test("on a preview the pill links to the pull's forge page in plain words", () => {
88 expect(toolbarJs).toContain('"preview \\u00b7 #"');
89 expect(toolbarJs).toContain('"Pull #"');
8990 expect(toolbarJs).toContain('"/pulls/"');
9091 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs