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

The forge pill links a preview's page to the same path on production, and production's page to the newest open preview #5862

Closed opened this
Closed without merging

scout/forge:scout/5851-the-forge-pill-links-a-preview-s-page-to → main 6 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +246 −5
README.md +6 −1
@@ -1122,7 +1122,12 @@ closes it. When a crew run is working on the app (production) or on the preview'
11221122 pull, the panel also says `scout is working on this` and links the run; it asks
11231123 `/__forge/crew` once as the pill loads, answers only a signed-in person who may
11241124 read the repository (and, for a run on a sealed issue, that issue), and shows
1125 nothing when the crew is idle.
1125 nothing when the crew is idle. The panel also links the other side of the app,
1126 with the page's path and query kept: in a preview, `Open on production`; on
1127 production, `Newest preview: #N <title>` (the newest live preview the viewer may
1128 read, none if there is none). Both addresses come from `/__forge/crew`, never
1129 from the page's own host. This is a pill link only; the terminal has no twin for
1130 it, because it has no page to carry across.
11261131
11271132 **When the pill is not shown** (an app whose own policy refuses foreign
11281133 scripts), `/__forge/` on the app's host is the way back: a small page from the
src/apps/proxy.ts +13 −1
@@ -43,6 +43,7 @@ import { takePhases, timePhase } from "../core/route_timing.ts";
4343 import { notFound } from "../http/respond.ts";
4444 import { appMeasure } from "./measure.ts";
4545 import { holdPortRequest, holdPortSocket } from "./handoff.ts";
46 import { otherSide } from "./side.ts";
4647 import { htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts";
4748
4849 export interface AppTarget {
@@ -610,8 +611,19 @@ export async function proxyApp(
610611 target.app,
611612 signed?.who?.id,
612613 );
614 const side = otherSide(
615 runtime.app.db,
616 runtime,
617 target.app,
618 target.env,
619 signed?.who?.id,
620 );
613621 const body = timePhase(request, "render", () =>
614 JSON.stringify({ ...crew, ...(tell === undefined ? {} : { tell }) }),
622 JSON.stringify({
623 ...crew,
624 ...(tell === undefined ? {} : { tell }),
625 ...(side === undefined ? {} : { side }),
626 }),
615627 );
616628 return withPhases(
617629 request,
src/apps/side.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * The other side, for the forge pill: from a preview, the app's production;
3 * from production, its newest preview that is up. The address comes from the
4 * forge's own record of the app, never from the page's location; the pill
5 * only adds the path and query of the page it is on.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import type { AppRecord } from "../core/apps.ts";
10 import { getIssue } from "../core/issues.ts";
11 import { canRead, getRepoById } from "../core/repos.ts";
12 import { mayView } from "../core/sealed.ts";
13 import { getUserById, isActive } from "../core/users.ts";
14 import type { EnvName } from "./data.ts";
15 import type { EnvStatus } from "./runtime.ts";
16
17 export type Side = { label: string; url: string };
18
19 /** What the runtime tells of an app's environments and addresses. */
20 export interface SideSource {
21 status(record: AppRecord): EnvStatus[];
22 urlFor(record: AppRecord, env: EnvName): string;
23 }
24
25 export function otherSide(
26 db: Database,
27 source: SideSource,
28 app: AppRecord,
29 env: string,
30 viewerId: string | undefined,
31 ): Side | undefined {
32 if (/^pull-\d+$/.test(env)) {
33 return { label: "Open on production", url: source.urlFor(app, "production") };
34 }
35 if (env !== "production") return undefined;
36 const repo = getRepoById(db, app.repoId);
37 if (repo === undefined) return undefined;
38 const viewer = viewerId === undefined ? undefined : getUserById(db, viewerId);
outdated

Returns the preview's number and URL to every caller. Check canRead and mayView before returning anything for production, not only before adding the title.

39 const user = viewer !== undefined && isActive(viewer) ? viewer : undefined;
40 if (!canRead(db, repo, user)) return undefined;
41 const live = source
42 .status(app)
43 .filter((s) => s.state === "running" || s.state === "asleep")
44 .map((s) => ({ number: Number(/^pull-(\d+)$/.exec(s.env)?.[1] ?? NaN), url: s.url }))
45 .filter((s) => Number.isInteger(s.number))
46 .sort((a, b) => b.number - a.number);
47 // A pull's number, title and address are the pull's: only a reader of it
48 // is told of it, so the newest one this viewer may see is the one named.
49 for (const { number, url } of live) {
50 const pull = getIssue(db, app.repoId, number);
51 if (pull === undefined || !mayView(db, repo, pull, user)) continue;
52 return { label: `Newest preview: #${number} ${pull.title}`, url };
53 }
54 return undefined;
55 }
src/apps/toolbar.ts +16 −3
@@ -233,7 +233,7 @@ export const toolbarJs = `(function () {
233233 .then(function (r) { return r.ok ? r.json() : {}; })
234234 .then(function (c) {
235235 if (!c) return;
236 var forge = new URL(me.src).origin;
236 var forge = new URL(me.src).origin, ls = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
237237 // Signed in, the crew can be told from here. The form is the forge's
238238 // own page, on its own origin, with its own CSRF check: the app's
239239 // page only carries the address and the pull to it.
@@ -247,10 +247,23 @@ export const toolbarJs = `(function () {
247247 ta.target = "_blank";
248248 ta.rel = "noopener";
249249 ta.href = t.href;
250 ta.style.cssText = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
250 ta.style.cssText = ls;
251251 crew.appendChild(ta);
252252 }
253253 }
254 // The other side, on the forge's address plus this page's path.
255 var sd = c.side;
256 if (sd && typeof sd.url === "string" && typeof sd.label === "string") {
257 var su = new URL(sd.url);
258 if (/^https?:$/.test(su.protocol)) {
259 var sa = document.createElement("a");
260 sa.textContent = sd.label;
261 sa.rel = "noopener";
262 sa.href = su.origin + location.pathname + location.search;
263 sa.style.cssText = ls;
264 crew.appendChild(sa);
265 }
266 }
254267 if (typeof c.who !== "string" || typeof c.url !== "string") return;
255268 var u = new URL(c.url);
256269 if (u.origin !== forge) return;
@@ -258,7 +271,7 @@ export const toolbarJs = `(function () {
258271 a.textContent = c.who + " is working on this";
259272 a.rel = "noopener";
260273 a.href = u.href;
261 a.style.cssText = "color:#8ab4ff;text-decoration:none;display:flex;align-items:center;min-height:44px";
274 a.style.cssText = ls;
262275 crew.appendChild(a);
263276 })
264277 .catch(function () {});
test/apps-side.test.ts added +156
@@ -0,0 +1,156 @@
1 /**
2 * The pill links to the other side (#5851): a preview to the same page on
3 * production, production to the newest live preview. The address is the
4 * forge's; the page adds only its path and query.
5 */
6
7 import { describe, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp } from "../src/app.ts";
12 import { otherSide, type SideSource } from "../src/apps/side.ts";
13 import { toolbarJs } from "../src/apps/toolbar.ts";
14 import { newApp } from "../src/actions/apps.ts";
15 import { getAppByRepo } from "../src/core/apps.ts";
outdated

repoId: "nope" skips the title and privacy branch. Use a real repo and pull, and cover a reader, a guest, and a private repo.

16 import { createIssue, getIssue } from "../src/core/issues.ts";
17 import { setSealed } from "../src/core/sealed.ts";
18 import { createUser } from "../src/core/users.ts";
19
20 const forge = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-side-")), port: 0, host: "forge.test" });
21 const db = forge.db;
22 const source = (previews: [number, string][]): SideSource => ({
23 status: () =>
24 [
25 { env: "production", state: "running", url: "https://notes.apps.test" },
26 ...previews.map(([n, state]) => ({
27 env: `pull-${n}`,
28 state,
29 url: `https://notes--${n}.apps.test`,
30 })),
31 ] as never,
32 urlFor: (_a, env) => (env === "production" ? "https://notes.apps.test" : `https://x--${env}`),
33 });
34
35 async function person(username: string, first = false) {
36 const u = await createUser(db, {
37 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
38 password: "a-good-passphrase", ...(first ? { adminIfFirst: true } : {}),
39 });
40 if (!u.ok) throw new Error(u.error);
41 return u.value;
42 }
43
44 let people: { owner: { id: string } & any; stranger: { id: string } } | undefined;
45 let count = 0;
46
47 /** An app with pulls 1..n (titled "pull N") and who may see it. */
48 async function world(visibility: "public" | "private", n: number) {
49 people ??= { owner: await person("alice", true), stranger: await person("bob") };
50 const { owner, stranger } = people;
51 const made = await newApp(forge, owner, { name: `notes-${++count}`, description: "x", visibility });
52 if (!made.ok) throw new Error(String(made.error));
53 const app = getAppByRepo(db, made.value.repo.id)!;
54 // The new app's own first issue is number 1: the pulls are 2 and up.
55 for (let i = 0; i < n; i++) {
56 const p = createIssue(db, { repoId: app.repoId, authorId: owner.id, title: "pull", kind: "pull" });
57 if (!p.ok) throw new Error(p.error);
58 db.run("UPDATE issue SET title = ?1 WHERE id = ?2", [`pull ${p.value.number}`, p.value.id]);
59 }
60 return { app, owner: owner.id, stranger: stranger.id };
61 }
62
63 describe("the other side", () => {
64 test("a preview offers production", async () => {
65 const { app } = await world("public", 1);
66 expect(otherSide(db, source([[2, "running"]]), app, "pull-2", undefined)).toEqual({
67 label: "Open on production",
68 url: "https://notes.apps.test",
69 });
70 });
71
72 test("production offers the newest live preview, with its title to a reader", async () => {
73 const { app, owner } = await world("public", 5);
74 const live = source([[3, "running"], [6, "failed"], [5, "asleep"], [2, "running"]]);
75 const want = { label: "Newest preview: #5 pull 5", url: "https://notes--5.apps.test" };
76 expect(otherSide(db, live, app, "production", owner)).toEqual(want);
77 // A public repository is read by a guest too.
78 expect(otherSide(db, live, app, "production", undefined)).toEqual(want);
79 });
80
81 test("an app with no previews offers nothing", async () => {
82 const { app, owner } = await world("public", 2);
83 expect(otherSide(db, source([]), app, "production", owner)).toBeUndefined();
84 expect(otherSide(db, source([[2, "stopped"]]), app, "production", owner)).toBeUndefined();
85 });
86
87 test("a private repository tells a guest and a non-reader nothing, and its reader everything", async () => {
88 const { app, owner, stranger } = await world("private", 2);
89 const live = source([[2, "running"]]);
90 expect(otherSide(db, live, app, "production", undefined)).toBeUndefined();
91 expect(otherSide(db, live, app, "production", stranger)).toBeUndefined();
92 expect(otherSide(db, live, app, "production", "nobody")).toBeUndefined();
93 expect(otherSide(db, live, app, "production", owner)!.label).toBe("Newest preview: #2 pull 2");
94 });
95
96 test("a sealed pull is skipped for who cannot see it: the next newest is named", async () => {
97 const { app, owner, stranger } = await world("public", 3);
98 const sealed = getIssue(db, app.repoId, 4)!;
99 setSealed(db, sealed.id, true);
100 const live = source([[4, "running"], [3, "running"]]);
101 expect(otherSide(db, live, app, "production", stranger)!.label).toBe("Newest preview: #3 pull 3");
102 expect(otherSide(db, live, app, "production", owner)!.label).toBe("Newest preview: #4 pull 4");
103 expect(otherSide(db, source([[4, "running"]]), app, "production", stranger)).toBeUndefined();
104 });
105 });
106
107 describe("the pill's link", () => {
108 function run(side: unknown, location: { pathname: string; search: string; href: string }) {
109 const links: { textContent: string; href?: string }[] = [];
110 const el = (tag: string): any => ({
111 tag, style: {}, children: [], textContent: "", dataset: {},
112 setAttribute() {}, appendChild(c: any) { return c; }, addEventListener() {}, focus() {},
113 attachShadow: () => el("shadow"),
114 });
115 const doc: any = {
116 currentScript: { src: "https://forge.test/assets/t.js", dataset: { app: "notes", env: "pull-7", pull: "7" } },
117 createElement: (tag: string) => {
118 const e = el(tag);
119 if (tag === "a") links.push(e);
120 return e;
121 },
122 addEventListener() {},
123 body: { appendChild() {} },
124 };
125 const fetchStub = (u: string) =>
126 Promise.resolve({ ok: true, json: () => Promise.resolve(u === "/__forge/crew" ? { side } : {}) });
127 new Function("window", "document", "URL", "fetch", "location", toolbarJs)(
128 { innerWidth: 400, innerHeight: 800 }, doc, URL, fetchStub, location,
129 );
130 return new Promise<typeof links>((r) => setTimeout(() => r(links), 20));
131 }
132
133 test("carries the page's path and query to the forge's address, not the page's host", async () => {
134 const links = await run(
135 { label: "Open on production", url: "https://notes.apps.test" },
136 { pathname: "/list/a%20b", search: "?q=1&x=%26", href: "https://evil.test/list/a%20b?q=1&x=%26" },
137 );
138 const link = links.find((l) => l.textContent === "Open on production")!;
139 expect(link.href).toBe("https://notes.apps.test/list/a%20b?q=1&x=%26");
140 });
141
142 test("a path that starts with // stays on the forge's address", async () => {
143 const links = await run(
144 { label: "Open on production", url: "https://notes.apps.test/base?x=1" },
145 { pathname: "//evil.test/x", search: "?q=1", href: "https://p.test//evil.test/x?q=1" },
146 );
147 const link = links.find((l) => l.textContent === "Open on production")!;
148 expect(new URL(link.href!).origin).toBe("https://notes.apps.test");
149 expect(link.href).toBe("https://notes.apps.test//evil.test/x?q=1");
150 });
151
152 test("no side, no link", async () => {
153 const links = await run(undefined, { pathname: "/", search: "", href: "https://x/" });
154 expect(links.some((l) => /production|preview/i.test(l.textContent))).toBe(false);
155 });
156 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs