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

The forge pill says where you are: app, production or preview of pull #n with its title, and a link home #1652

Closed opened this
Closed without merging

scout/forge:scout/1502-the-forge-pill-says-where-you-are-app-pr → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +130 −11
src/apps/proxy.ts +37 −1
@@ -34,7 +34,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
3434 import { loadKey } from "../kernel/secret.ts";
3535 import { previewEnv, type EnvName } from "./data.ts";
3636 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
37 import { rewritable, withToolbar } from "./toolbar.ts";
37 import { rewritable, withToolbar, type PillInfo } from "./toolbar.ts";
3838
3939 export interface AppTarget {
4040 readonly app: AppRecord;
@@ -342,6 +342,41 @@ function sealedPull(runtime: AppsRuntime, target: AppTarget): Issue | undefined
342342 return pull?.sealed === true ? pull : undefined;
343343 }
344344
345 /**
346 * What the pill says: the app, the environment and, for a preview, its pull.
347 * The title goes only to a viewer who may read the pull: the repository's
348 * readers, and for a sealed report those who may see it.
349 */
350 function pillInfo(
351 runtime: AppsRuntime,
352 target: AppTarget,
353 grant: Grant | undefined,
354 ): PillInfo {
355 const info = { app: target.app.slug, env: target.env };
356 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
357 if (number === undefined) return info;
358 const db = runtime.app.db;
359 const repo = getRepoById(db, target.app.repoId);
360 const pull = getIssue(db, target.app.repoId, Number(number));
361 if (repo === undefined || pull === undefined) return info;
362 const viewer =
363 grant?.who === undefined ? undefined : getUserById(db, grant.who.id);
364 const mayRead =
365 canRead(db, repo, viewer) &&
366 (!pull.sealed || mayView(db, repo, pull, viewer));
367 return {
368 ...info,
369 pull: {
370 number: pull.number,
371 ...(mayRead ? { title: pull.title } : {}),
372 href: new URL(
373 `/${repo.ownerName}/${repo.name}/pulls/${pull.number}`,
374 runtime.options.forgeUrl,
375 ).href,
376 },
377 };
378 }
379
345380 /** Whether the person a grant names may enter this app now. */
346381 function stillEntitled(
347382 runtime: AppsRuntime,
@@ -616,6 +651,7 @@ export async function proxyApp(
616651 page = withToolbar(
617652 new Uint8Array(await response.arrayBuffer()),
618653 runtime.options.forgeUrl,
654 pillInfo(runtime, target, vouched),
619655 );
620656 } catch {
621657 return unavailable(runtime, target, status, "the app stopped answering");
src/apps/toolbar.ts +44 −8
@@ -31,13 +31,29 @@ export const toolbarJs = `(function () {
3131 pill.setAttribute("aria-expanded", "false");
3232 pill.textContent = "\\u2692";
3333 pill.style.cssText = "all:unset;box-sizing:border-box;cursor:pointer;width:28px;height:28px;border-radius:14px;background:#1f2328;color:#fff;text-align:center;line-height:28px;font-size:14px;opacity:.55;box-shadow:0 1px 4px rgba(0,0,0,.4)";
34 var panel = document.createElement("a");
35 panel.href = home;
36 panel.target = "_blank";
37 panel.rel = "noopener";
38 panel.textContent = "Built on forge";
34 var d = (me && me.dataset) || {};
35 var panel = document.createElement("div");
3936 panel.hidden = true;
40 panel.style.cssText = "background:#1f2328;color:#fff;padding:6px 10px;border-radius:14px;text-decoration:none;white-space:nowrap;box-shadow:0 1px 4px rgba(0,0,0,.4)";
37 panel.style.cssText = "background:#1f2328;color:#fff;padding:8px 12px;border-radius:14px;box-shadow:0 1px 4px rgba(0,0,0,.4);max-width:min(320px,calc(100vw - 64px));display:flex;flex-direction:column;gap:4px";
38 function line(tag, text, href) {
39 var el = document.createElement(tag);
40 el.textContent = text;
41 if (href) {
42 el.href = href;
43 el.target = "_blank";
44 el.rel = "noopener";
45 }
46 el.style.cssText = "color:#fff;text-decoration:" + (href ? "underline" : "none") + ";overflow-wrap:anywhere";
47 panel.appendChild(el);
48 }
49 line("div", d.app || "forge app");
50 if (d.pull) {
51 var to = d.href && d.href.indexOf(home) === 0 ? d.href : "";
52 line(to ? "a" : "div", "preview of pull #" + d.pull + (d.title ? " \u2014 " + d.title : ""), to);
53 } else {
54 line("div", d.env || "production");
55 }
56 line("a", "Home", home);
4157 function set(open) {
4258 panel.hidden = !open;
4359 pill.setAttribute("aria-expanded", open ? "true" : "false");
@@ -97,10 +113,30 @@ export function rewritable(headers: Headers, status: number): boolean {
97113 return Number(length) <= REWRITE_MAX;
98114 }
99115
116 /** What the pill says about where it is; every value is escaped into the tag. */
117 export interface PillInfo {
118 readonly app: string;
119 readonly env: string;
120 /** A preview's pull: its number, and its title only when the viewer may read it. */
121 readonly pull?: { readonly number: number; readonly title?: string; readonly href: string };
122 }
123
124 const escapeAttr = (s: string): string =>
125 s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
126
100127 /** `bytes` with the pill's tag before the last `</body>`, or at the end. */
101 export function withToolbar(bytes: Uint8Array, forgeUrl: string): Uint8Array {
128 export function withToolbar(bytes: Uint8Array, forgeUrl: string, info?: PillInfo): Uint8Array {
129 const data =
130 info === undefined
131 ? ""
132 : ` data-app="${escapeAttr(info.app)}" data-env="${escapeAttr(info.env)}"` +
133 (info.pull === undefined
134 ? ""
135 : ` data-pull="${info.pull.number}"` +
136 (info.pull.title === undefined ? "" : ` data-title="${escapeAttr(info.pull.title)}"`) +
137 ` data-href="${escapeAttr(info.pull.href)}"`);
102138 const tag = Buffer.from(
103 `<script src="${new URL(TOOLBAR_PATH, forgeUrl).href}" defer></script>`,
139 `<script src="${new URL(TOOLBAR_PATH, forgeUrl).href}"${data} defer></script>`,
104140 );
105141 const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
106142 // latin1 is one character per byte, so an index in it is a byte offset.
test/apps-toolbar.test.ts +49 −2
@@ -13,7 +13,8 @@ import { gzipSync } from "node:zlib";
1313 import { createApp, type App } from "../src/app.ts";
1414 import { newApp } from "../src/actions/apps.ts";
1515 import { commitToBranch } from "../src/actions/repos.ts";
16 import { getAppByRepo } from "../src/core/apps.ts";
16 import { createIssue } from "../src/core/issues.ts";
17 import { getAppBySlug, getAppByRepo } from "../src/core/apps.ts";
1718 import { listRuns } from "../src/core/runs.ts";
1819 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1920 import { parseManifest } from "../src/apps/manifest.ts";
@@ -127,7 +128,8 @@ describe("the forge pill", () => {
127128 headers: { host: `notes.${DOMAIN}`, accept: "*/*" },
128129 redirect: "manual",
129130 });
130 const tag = () => `<script src="${servers.url}${TOOLBAR_PATH}" defer></script>`;
131 const tag = () =>
132 `<script src="${servers.url}${TOOLBAR_PATH}" data-app="notes" data-env="production" defer></script>`;
131133
132134 test("HTML gets one script tag before </body>, with its length fixed", async () => {
133135 toolbar = undefined;
@@ -189,6 +191,51 @@ describe("the forge pill", () => {
189191 expect(code).toContain("attachShadow");
190192 });
191193
194 test("the tag names the app and production; the script reads it with textContent", async () => {
195 expect(tag()).toContain('data-env="production"');
196 expect(toolbarJs).toContain("textContent");
197 expect(toolbarJs).not.toMatch(/innerHTML|insertAdjacentHTML|document\.write/);
198 expect(toolbarJs).toContain('"Home"');
199 });
200
201 test("a preview's tag names its pull and title, with markup escaped", async () => {
202 const owner = app.db
203 .query<{ id: string }, []>("SELECT id FROM user LIMIT 1")
204 .get()!;
205 const record = getAppBySlug(app.db, "notes");
206 const made = createIssue(app.db, {
207 repoId: record!.repoId,
208 authorId: owner.id,
209 title: `<img src=x onerror=alert(1)> "q" & 'a'`,
210 });
211 if (!made.ok) throw new Error(made.error);
212 const n = made.value.number;
213 const res = await fetch(`${servers.url}/`, {
214 headers: { host: `notes--${n}.${DOMAIN}`, accept: "*/*" },
215 redirect: "manual",
216 });
217 const text = await res.text();
218 expect(text).toContain(`data-env="pull-${n}"`);
219 expect(text).toContain(`data-pull="${n}"`);
220 expect(text).toContain(
221 'data-title="&#60;img src=x onerror=alert(1)&#62; &#34;q&#34; &#38; &#39;a&#39;"',
222 );
223 expect(text).not.toContain("<img");
224 expect(text).toContain(`data-href="${servers.url}/alice/notes/pulls/${n}"`);
225 });
226
227 test("withToolbar leaves out the title for a viewer who may not read it", () => {
228 const out = new TextDecoder().decode(
229 withToolbar(new TextEncoder().encode("<body></body>"), "http://f.test", {
230 app: "a",
231 env: "pull-2",
232 pull: { number: 2, href: "http://f.test/o/r/pulls/2" },
233 }),
234 );
235 expect(out).toContain('data-pull="2"');
236 expect(out).not.toContain("data-title");
237 });
238
192239 test("the tag lands before the last </body>, whatever its case", () => {
193240 const out = new TextDecoder().decode(
194241 withToolbar(new TextEncoder().encode("<BODY>x</BODY>"), "http://f.test"),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs