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

On a preview, the forge toolbar's 'Home' returns to the previewed app's own page on the forge, not the forge's front page #15670

Merged opened this

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

Merged

mason/forge:mason/15657-on-a-preview-the-forge-toolbar-s-home-re → main 0 commits fork 5 threads · 5 unresolved

  • Merged. mason/15657-on-a-preview-the-forge-toolbar-s-home-re was merged into main as 71bcf55.

Review

Sign in to review this change.
4 files changed +91 −38
src/apps/toolbar.ts +15 −15
@@ -113,28 +113,28 @@ const toolbarSource = `(function () {
113113 if (d.env === "production") line("production");
114114 var LC = "#8ab4ff";
115115 var LS = "color:" + LC + ";text-decoration:none;display:flex;align-items:center;min-height:44px";
116 var pullHref = "", pv = d.env !== "production" && d.pull;
117 // The pull this preview shows, one tap away: built from the script's own origin, never from page text.
118 if (pv && /^\\d{1,9}$/.test(d.pull) && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "")) {
119 try { pullHref = new URL("/" + d.repo + "/pulls/" + d.pull, fo).href; } catch (e) {}
116 var RE = /^(?!\\.*\\/|.*\\/\\.+$)[\\w.-]+\\/[\\w.-]+$/;
outdated

Accepts .. segments. Use a pattern that rejects a segment made only of dots.

117 var ph = "", pv = d.env !== "production" && d.pull;
118 if (pv && /^\\d{1,9}$/.test(d.pull) && RE.test(d.repo)) {
119 try { ph = new URL("/" + d.repo + "/pulls/" + d.pull, fo).href; } catch (e) {}
120120 }
121121 var cw = ${JSON.stringify(CHECK_WORDS)};
122 var cword = d.check && Object.prototype.hasOwnProperty.call(cw, d.check) ? cw[d.check] : "";
123 var pt = "Pull #" + d.pull + (cword ? ": " : "");
122 var cv = d.check && Object.prototype.hasOwnProperty.call(cw, d.check) ? cw[d.check] : "";
123 var pt = "Pull #" + d.pull + (cv ? ": " : "");
124124 // The word's own slot is as wide as the longest word: checking -> green never reflows the row.
125125 function slot(a) {
126 if (!cword) return;
126 if (!cv) return;
127127 var cs = document.createElement("span");
128 cs.textContent = cword;
128 cs.textContent = cv;
129129 cs.style.minWidth = "${CHECK_WIDTH}ch";
130130 cs.style.display = "inline-block";
131131 a.appendChild(cs);
132132 }
133 if (pullHref) {
133 if (ph) {
134134 var pl = document.createElement("a");
135135 pl.textContent = pt;
136136 if (d.title) pl.title = d.title;
137 pl.href = pullHref;
137 pl.href = ph;
138138 pl.rel = "noopener";
139139 pl.style.cssText = LS + ";overflow-wrap:anywhere";
140140 slot(pl);
@@ -149,7 +149,7 @@ const toolbarSource = `(function () {
149149 // The comment box is its own script, fetched on the first open (toolbar_comment.ts); it gets
150150 // the proof chain only while that exact script runs, and only once.
151151 var cm = null, cx = null;
152 if (pullHref) {
152 if (ph) {
153153 panel.appendChild(cm = document.createElement("div"));
154154 window.__forgeComment = function (b) {
155155 if (!cx || document.currentScript !== cx) return;
@@ -182,7 +182,7 @@ const toolbarSource = `(function () {
182182 var part = function (t) { var sp = document.createElement("span"); sp.textContent = t; sv.appendChild(sp); };
183183 part("Serving ");
184184 var short = d.commit.slice(0, 7), cl = null;
185 if (/^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "") && fo) {
185 if (RE.test(d.repo) && fo) {
186186 try { cl = document.createElement("a"); cl.href = new URL("/" + d.repo + "/commit/" + d.commit, fo).href; cl.rel = "noopener"; cl.style.color = LC; cl.textContent = short; } catch (e) { cl = null; }
187187 }
188188 if (cl) sv.appendChild(cl); else part(short);
@@ -196,8 +196,8 @@ const toolbarSource = `(function () {
196196 link.style.cssText = LS;
197197 var hasHome = false;
198198 try {
199 var target = new URL(back);
200 if (target.origin === fo) { link.href = target.href; hasHome = true; }
199 var target = new URL(RE.test(d.repo) ? "/" + d.repo : back, fo);
200 if (target.origin === fo) { link.href = target.href; hasHome = !ph; }
201201 } catch (e) {}
outdated

On a preview this equals the Pull #N link href, so the bar shows two links to one page. Merge them.

202202 // Tell the builders: one box, one button, no account. The note goes to
203203 // this app's own host (same-origin, so the sender's cookie goes along) and
@@ -440,7 +440,7 @@ const toolbarSource = `(function () {
440440 if (hasHome) panel.appendChild(link);
441441 // The actions live on a forge page, opened in a tab of its own: the bar
442442 // posts nothing and reads nothing of this page beyond its address.
443 if (d.repo && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo)) {
443 if (d.repo && RE.test(d.repo)) {
444444 var act = document.createElement("a");
445445 act.textContent = "Comment, tell, make it yours";
446446 act.target = "_blank";
test/apps-toolbar-state.test.ts +4 −1
@@ -38,9 +38,12 @@ const TITLE_ALLOWANCE = 170;
3838 // The toolbar's Make it yours saying why it cannot (a status, not a link), allowed by name: 40
3939 // bytes.
4040 const YOURS_WHY_ALLOWANCE = 50;
41 // Home on a preview is the app's page and checks the repo id more strictly (#15657), allowed by
42 // name: 20 bytes.
43 const HOME_ALLOWANCE = 30;
4144
4245 test("the addition stays under 300 bytes", () => {
43 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE);
46 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE + HOME_ALLOWANCE);
4447 const tag = toolbarTag("https://forge.test", where("x".repeat(CHANGE_MAX)), "p", "n");
4548 const bare = toolbarTag("https://forge.test", where(), "p", "n");
4649 expect(Buffer.byteLength(tag) - Buffer.byteLength(bare)).toBeLessThan(300);
test/lost-journey.test.ts +30 −8
@@ -71,6 +71,10 @@ describe("lost journey: where you are and three exits", () => {
7171 const record = getAppByRepo(app.db, made.value.repo.id)!;
7272 const p = createIssue(app.db, { repoId: record.repoId, authorId: alice, title: SECRET_TITLE, kind: "pull" });
7373 if (!p.ok) throw new Error(p.error);
74 // A pull with a head, so its page answers 200 for the journey to follow.
75 app.db
76 .query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?, 'main', 'h', 'b', 'h')")
77 .run(p.value.id);
7478 apps[visibility] = { record, pull: p.value.number };
7579 }
7680 }, 120_000);
@@ -227,9 +231,8 @@ describe("lost journey: where you are and three exits", () => {
227231 const run = await boot(html, await crewOf(host, cookie), `http://${host}/some/page`);
228232 const origin = new URL(servers.url).origin;
229233
230 const home = run.named("Home")!;
231 expect(focusable(home)).toBe(true);
232 expect(home.href).toBe(`${origin}/`);
234 // One link to the pull's page: the Pull link, not a second "Home" beside it.
235 expect(run.named("Home")).toBeUndefined();
233236
234237 const pullLink = run.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Pull #${pull}`))!;
235238 expect(focusable(pullLink)).toBe(true);
@@ -255,6 +258,18 @@ describe("lost journey: where you are and three exits", () => {
255258 expect(focusable(run.built.find((e) => e.tag === "button" && e.type === "submit"))).toBe(true);
256259 });
257260
261 test("run: a repo id with a dots-only segment builds no forge link", async () => {
262 const host = `public--${apps.public!.pull}.${DOMAIN}`;
263 const cookie = cookieFor("public", `pull-${apps.public!.pull}`);
264 const html = await (await ask(host, "/", cookie)).text();
265 for (const repo of ["../x", "x/..", "../.."]) {
266 const run = await boot(html.replace(/data-repo="[^"]*"/, `data-repo="${repo}"`), await crewOf(host, cookie), `http://${host}/`);
267 const hrefs = run.built.filter((e) => e.tag === "a").map((e) => String(e.href ?? ""));
268 expect(hrefs.some((h) => h.includes("/../") || /\/x$/.test(h) && !h.includes("/alice/"))).toBe(false);

Non-blocking: this predicate is hard to read and could pass for the wrong reason. Assert that no href contains /../ and that no Pull # anchor exists, or compare against the exact expected href list.

269 expect(run.built.some((e) => e.tag === "a" && String(e.textContent).startsWith("Pull #"))).toBe(false);
270 }
271 });
272
258273 test("run: production shows the environment and no pull link", async () => {
259274 const host = `public.${DOMAIN}`;
260275 const cookie = cookieFor("public", "production");
@@ -262,7 +277,7 @@ describe("lost journey: where you are and three exits", () => {
262277 const run = await boot(html, await crewOf(host, cookie), `http://${host}/`);
263278 expect(run.named("production")).toBeDefined();
264279 expect(run.built.some((e) => String(e.textContent).startsWith("Pull #"))).toBe(false);
265 expect(run.named("Home")!.href).toBe(`${new URL(servers.url).origin}/`);
280 expect(run.named("Home")!.href).toBe(`${new URL(servers.url).origin}/alice/public`);
266281 });
267282
268283 test("a stranger on a public preview still learns app, environment and pull, with no tell", async () => {
@@ -275,7 +290,7 @@ describe("lost journey: where you are and three exits", () => {
275290 expect(tag[2]).toContain(` data-pull="${pull}"`);
276291 const run = await boot(html, await crewOf(host), `http://${host}/`);
277292 expect(run.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Pull #${pull}`))!.href).toBe(`${new URL(servers.url).origin}/alice/public/pulls/${pull}`);
278 expect(run.named("Home")).toBeDefined();
293 expect(run.named("Home")).toBeUndefined();
279294 expect(run.named("Tell the crew")).toBeUndefined();
280295 // Comment goes to the forge's own page, which asks the stranger to sign in there.
281296 expect(new URL(run.named("Comment, tell, make it yours")!.href as string).origin).toBe(new URL(servers.url).origin);
@@ -335,12 +350,18 @@ describe("lost journey: where you are and three exits", () => {
335350 for (const l of links) {
336351 const where = new URL(l.href as string);
337352 if (l.textContent === "Open on production") expect(where.hostname).toBe(`public.${DOMAIN}`);
353 else if (String(l.textContent).startsWith("Newest preview")) expect(where.hostname).toEndWith(`.${DOMAIN}`);
338354 else expect([l.textContent, where.origin]).toEqual([l.textContent, origin]);
339355 }
340356
341357 const session = await ownerSession();
342358 expect(session).toContain("=");
343 for (const text of ["Home", "Comment, tell, make it yours", "Tell the crew"]) {
359 // The way back is the pull's page on a preview (the Pull link), else the app's (Home).

Non-blocking: stray space after [ in the array literal.

360 const back = preview ? run.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Pull #${pull}`))! : run.named("Home")!;
361 expect(new URL(back.href as string).pathname).toBe(preview ? `/alice/public/pulls/${pull}` : "/alice/public");
362 expect(Boolean(run.named("Home"))).toBe(!preview);
363 expect((await follow(back.href as string, session)).status).toBe(200);
364 for (const text of [ "Comment, tell, make it yours", "Tell the crew"]) {
344365 const link = run.named(text);
345366 expect(link, text).toBeDefined();
346367 const res = await follow(link!.href as string, session);
@@ -349,8 +370,9 @@ describe("lost journey: where you are and three exits", () => {
349370
350371 const strangerHtml = await (await ask(host, "/")).text();
351372 const stranger = await boot(strangerHtml, await crewOf(host), `http://${host}/page`);
352 const res = await follow(stranger.named("Home")!.href as string);
353 expect(res.status).toBe(200);
373 const strangerBack = preview ? stranger.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Pull #${pull}`))! : stranger.named("Home")!;
374 expect(new URL(strangerBack.href as string).pathname).toBe(preview ? `/alice/public/pulls/${pull}` : "/alice/public");
375 expect((await follow(strangerBack.href as string)).status).toBe(200);
354376 });
355377 }
356378
test/toolbar-back.test.ts +42 −14
@@ -2,27 +2,31 @@
22 import { expect, test } from "bun:test";
33 import { toolbarJs } from "../src/apps/toolbar.ts";
44
5 /** Run the client against a fake document; returns the Home link's href. */
6 function homeHref(referrer: string): string | undefined {
5 /**
6 * Run the client against a fake document; returns the href of the first link whose text starts with
7 * `text`.
8 */
9 function linkHref(data: Record<string, string>, referrer: string, origin: string, text: string): string | undefined {
710 const links: any[] = [];
8 const el = (): any => {
9 const e: any = { style: {}, dataset: {}, children: [], hidden: false,
10 appendChild(c: any) { return c; }, setAttribute() {}, addEventListener() {},
11 attachShadow: () => el(), classList: { add() {}, remove() {} } };
12 return e;
13 };
11 const el = (): any => ({ style: {}, dataset: {}, children: [], hidden: false,
12 appendChild(c: any) { return c; }, setAttribute() {}, addEventListener() {},
13 attachShadow: () => el(), classList: { add() {}, remove() {} } });
1414 const doc: any = {
15 referrer, currentScript: { dataset: { forge: "https://forge.test" } },
15 referrer, currentScript: { dataset: { forge: "https://forge.test", ...data } },
1616 createElement: () => { const e = el(); links.push(e); return e; },
1717 addEventListener() {}, body: el(), documentElement: el(),
1818 };
19 const win: any = { location: { origin: "https://app.test", pathname: "/" }, addEventListener() {}, matchMedia: () => ({ matches: false }) };
19 const win: any = { location: { origin, pathname: "/" }, addEventListener() {}, matchMedia: () => ({ matches: false }) };
2020 new Function("window", "document", "location", "localStorage", "fetch", "URL", "setTimeout", "setInterval", "requestAnimationFrame", toolbarJs)(
2121 win, doc, win.location, { getItem: () => null, setItem() {} }, () => new Promise(() => {}), URL, () => 0, () => 0, () => 0);
22 const home = links.find((l) => l.textContent === "Home");
23 expect(home).toBeDefined();
24 expect(home.href).toBeString();
25 return home.href;
22 return links.find((l) => String(l.textContent).startsWith(text))?.href;
23 }
24
25 /** The Home href for a referrer. */
26 function homeHref(referrer: string): string | undefined {
27 const href = linkHref({}, referrer, "https://app.test", "Home");
28 expect(href).toBeString();
29 return href;
2630 }
2731
2832 test("a same-origin forge referrer is the Home target", () => {
@@ -40,3 +44,27 @@ test("a foreign or malformed referrer falls back to the forge's /", () => {
4044 expect(homeHref("javascript:alert(1)")).toBe("https://forge.test/");
4145 expect(homeHref("")).toBe("https://forge.test/");
4246 });
47
48 /** The href of the link starting `text`, for a tag's data. */
49 const homeFor = (data: Record<string, string>, text = "Home") =>
50 linkHref(data, "https://forge.test/elsewhere", "https://evil.test", text);
51
52 test("on production Home is the app's page on the forge, from the stored repo", () => {
53 expect(homeFor({ repo: "trevato/lab", env: "production" })).toBe("https://forge.test/trevato/lab");
54 });
55
56 test("on a pull preview the Pull link is the pull's page", () => {
57 const data = { repo: "trevato/lab", env: "preview", pull: "15657" };
58 expect(homeFor(data, "Pull #")).toBe("https://forge.test/trevato/lab/pulls/15657");
59 });
60
61 test("a repo id with a dots-only segment never builds a link", () => {
62 for (const repo of ["../x", "x/..", "../..", "./x"]) {
63 expect(homeFor({ repo, env: "production" })).toBe("https://forge.test/elsewhere");
64 expect(homeFor({ repo, env: "preview", pull: "7" }, "Pull #")).toBeUndefined();
65 }
66 });
67
68 test("a malformed repo id falls back rather than building a link", () => {
69 expect(homeFor({ repo: "a/b/c", env: "production" })).toBe("https://forge.test/elsewhere");
70 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs