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

A forge toolbar in every app and preview: where you are, who is working, comment, tell, make it yours, home #1437

Closed opened this
Closed without merging

scout/forge:scout/1057-a-forge-toolbar-in-every-app-and-preview → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +740 −2
docs/APPS.md +28
@@ -532,6 +532,34 @@ over the same SQLite file the web page uses, so a new app is reachable two
532532 ways from its first minute. An app without a `tty` says so, in words, when
533533 someone tries.
534534
535 ## The forge's bar
536
537 Every HTML page an app or preview serves carries one `<script>` tag, added by
538 the proxy before `</body>` (`apps/toolbar.ts`). The script draws a collapsed
539 pill at the bottom-right corner, in a closed shadow root, and fetches the
540 facts from `/__forge/toolbar.json` on the app's own host: which app, which
541 environment (production, or preview of pull #n and its title), and the crew
542 member whose run is working on it now. Its panel offers *Comment on this
543 page* (a preview: the pull; production: a new issue that starts with the page
544 address), *Tell the crew* (the repository's tell page), *Make it yours* and
545 *Home* (the feed). Both paths are the forge's, on the app's origin, so an
546 app's `script-src 'self'` lets the bar run; the stylesheet is built through
547 the CSSOM so `style-src` has no say.
548
549 Only a navigation's plain HTML is touched: `GET`, `text/html`, not
550 compressed, not a frame. To make that possible a navigation asks the app for
551 an uncompressed body: the request is made before the response type is
552 known, so a navigation that turns out not to be HTML (a download, a PDF)
553 travels uncompressed too, which costs bandwidth; `"toolbar": false` avoids
554 it. The bar is a browser-only surface and the app's `tty` is not involved; what
555 it links to has its own doors (the tell feed API, the forge's terminal for
556 commenting on issues and pulls).
557 Everything else - JSON, assets, streams, redirects,
558 posts, websockets - is byte-for-byte what the app sent. The pull title and
559 the name of who is working are shown only where the repository is public.
560 `"toolbar": false` in `forge.json` (under `app`, or at the top level) turns
561 the bar off for the app.
562
535563 ## Hostnames and the proxy
536564
537565 Apps are served from the forge's port by `Host`. With `FORGE_APP_DOMAIN`
scripts/gate.ts +2
@@ -99,6 +99,7 @@ export const GATE: readonly string[] = [
9999 "test/apps-adversarial.test.ts",
100100 "test/apps-busy.test.ts",
101101 "test/apps-token.test.ts",
102 "test/apps-toolbar.test.ts",
102103 "test/contain.test.ts",
103104 "test/contract.test.ts",
104105 "test/subscription-budget.test.ts",
@@ -234,6 +235,7 @@ export const GATE: readonly string[] = [
234235 ];
235236
236237 export const EXCLUDED: readonly Exclusion[] = [
238 { file: "test/plan-route.test.ts", reason: "not yet admitted", issue: 261 },
237239 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
238240 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
239241 {
src/apps/manifest.ts +6
@@ -51,6 +51,8 @@ export interface AppManifest {
5151 readonly egress?: readonly string[] | undefined;
5252 /** `app.limits`: the app process's memory, CPU and disk, within the machine's maximum. */
5353 readonly limits?: DeclaredLimits | undefined;
54 /** `toolbar: false` turns the forge's bar off for this app; absent is on. */
55 readonly toolbar?: boolean | undefined;
5456 }
5557
5658 export type ManifestError =
@@ -138,6 +140,9 @@ export function parseManifest(
138140 if (!egress.ok) return egress;
139141 const limits = limitsField(app, "app");
140142 if (!limits.ok) return limits;
143 const toolbar = app["toolbar"] ?? parsed.value["toolbar"];
144 if (toolbar !== undefined && typeof toolbar !== "boolean")
145 return invalid("forge.json: toolbar must be true or false");
141146 const kind = app["kind"];
142147 if (kind !== undefined && kind !== "web" && kind !== "service")
143148 return invalid('forge.json: app.kind must be "web" or "service"');
@@ -166,6 +171,7 @@ export function parseManifest(
166171 service,
167172 egress: egress.value,
168173 limits: limits.value,
174 toolbar,
169175 });
170176 }
171177
src/apps/proxy.ts +59
@@ -34,6 +34,14 @@ 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 {
38 TOOLBAR_FACTS,
39 TOOLBAR_JS,
40 TOOLBAR_SCRIPT,
41 toolbarFacts,
42 wantsToolbar,
43 withToolbar,
44 } from "./toolbar.ts";
3745
3846 export interface AppTarget {
3947 readonly app: AppRecord;
@@ -534,6 +542,32 @@ export async function proxyApp(
534542 const admitted = admit(runtime, request, target);
535543 if (!admitted.ok) return admitted.error;
536544 const { status, port, grant: vouched } = admitted.value;
545 // The forge's bar is the forge's to answer, on the app's own host.
546 if (
547 !target.nested &&
548 (request.method === "GET" || request.method === "HEAD") &&
549 (url.pathname === TOOLBAR_SCRIPT || url.pathname === TOOLBAR_FACTS)
550 ) {
551 const script = url.pathname === TOOLBAR_SCRIPT;
552 const facts = script
553 ? undefined
554 : toolbarFacts(
555 runtime.app,
556 runtime.options.forgeUrl,
557 target.app,
558 target.env,
559 );
560 if (script || facts !== undefined)
561 return new Response(script ? TOOLBAR_JS : JSON.stringify(facts), {
562 headers: {
563 "content-type": script
564 ? "text/javascript; charset=utf-8"
565 : "application/json; charset=utf-8",
566 "cache-control": script ? "private, max-age=3600" : "no-store",
567 "x-content-type-options": "nosniff",
568 },
569 });
570 }
537571 runtime.touch(target.app, target.env);
538572
539573 const upstream = new URL(url);
@@ -550,6 +584,16 @@ export async function proxyApp(
550584 ))
551585 headers.set(name, value);
552586
587 // A page the bar may go on is asked for uncompressed — the proxy passes the
588 // app's bytes through and cannot edit an encoded body. Only a navigation.
589 if (
590 request.method === "GET" &&
591 (request.headers.get("accept") ?? "").includes("text/html") &&
592 ["document", null].includes(request.headers.get("sec-fetch-dest")) &&
593 runtime.envStatus(target.app, target.env)?.toolbar !== false
594 )
595 headers.set("accept-encoding", "identity");
596
553597 if (isWebSocketHandshake(request)) {
554598 return proxyWebSocket(
555599 runtime,
@@ -589,6 +633,21 @@ export async function proxyApp(
589633 // without the app having to say so.
590634 if (isHtml(out) && reportUrl(runtime, target) !== undefined)
591635 out.append("link", REPORT_LINK);
636 if (
637 !target.nested &&
638 wantsToolbar(
639 request,
640 response,
641 runtime.envStatus(target.app, target.env)?.toolbar !== false,
642 )
643 )
644 return withToolbar(
645 new Response(response.body, {
646 status: response.status,
647 statusText: response.statusText,
648 headers: out,
649 }),
650 );
592651 const eventStream =
593652 response.body !== null &&
594653 (response.headers.get("content-type") ?? "")
src/apps/runtime.ts +4
@@ -183,6 +183,8 @@ export interface EnvStatus {
183183 * already answers.
184184 */
185185 readonly note?: string | undefined;
186 /** `forge.json`'s `toolbar`: false when the app turned the forge's bar off. */
187 readonly toolbar?: boolean | undefined;
186188 /**
187189 * The app's own `tty` command, once known live — `null` when its
188190 * `forge.json` declares none. Unset while never live, since a checkout
@@ -478,6 +480,7 @@ export class AppsRuntime {
478480 createdAt: state.live.createdAt,
479481 tty: state.live.manifest.tty,
480482 looks: state.live.manifest.looks,
483 toolbar: state.live.manifest.toolbar,
481484 ...(state.live.deployStartedAt === null
482485 ? {}
483486 : { deployStartedAt: state.live.deployStartedAt }),
@@ -514,6 +517,7 @@ export class AppsRuntime {
514517 createdAt: state.live.createdAt,
515518 tty: state.live.manifest.tty,
516519 looks: state.live.manifest.looks,
520 toolbar: state.live.manifest.toolbar,
517521 ...(state.live.deployStartedAt === null
518522 ? {}
519523 : { deployStartedAt: state.live.deployStartedAt }),
src/apps/toolbar.ts added +192
@@ -0,0 +1,192 @@
1 /**
2 * The forge's bar inside every app and preview: a collapsed pill that says
3 * which app and environment this page is, who is working on it, and offers
4 * comment, tell, make it yours and home. The proxy adds one `<script>` tag
5 * to an HTML page; the script and the facts it shows are answered by the
6 * forge on the app's own host (`/__forge/toolbar.js`, `/__forge/toolbar.json`)
7 * — same origin, so an app's `script-src 'self'` lets it run. Nothing else
8 * about a response changes, and a response that is not a plain HTML page is
9 * never touched. An app opts out with `"toolbar": false` in `forge.json`.
10 */
11
12 import type { App } from "../app.ts";
13 import { getIssue } from "../core/issues.ts";
14 import { getPull } from "../core/pulls.ts";
15 import { canRead, getRepoById } from "../core/repos.ts";
16 import { listRuns } from "../core/runs.ts";
17 import { getUserById } from "../core/users.ts";
18 import type { AppRecord } from "../core/apps.ts";
19 import type { EnvName } from "./data.ts";
20
21 export const TOOLBAR_SCRIPT = "/__forge/toolbar.js";
22 export const TOOLBAR_FACTS = "/__forge/toolbar.json";
23
24 const TAG = `<script src="${TOOLBAR_SCRIPT}" defer></script>`;
25
26 export interface ToolbarFacts {
27 readonly app: string;
28 readonly env: "production" | "preview";
29 readonly pull?: { readonly number: number; readonly title: string };
30 /** The crew member whose run is working on it now. */
31 readonly working?: string;
32 readonly links: {
33 /** On a preview, the pull; on production, the new-issue form to which the page address is added. */
34 readonly comment: string;
35 readonly commentIsPull: boolean;
36 readonly tell: string;
37 readonly yours: string;
38 readonly home: string;
39 };
40 }
41
42 /**
43 * What the bar says for one environment. The pull's title and the name of
44 * who is working are the repository's own words, so they appear only where
45 * the repository is public; a private repository's app shows its name, its
46 * environment and the links, which lead to a page the visitor may not see.
47 */
48 export function toolbarFacts(
49 app: App,
50 forgeUrl: string,
51 record: AppRecord,
52 env: EnvName,
53 ): ToolbarFacts | undefined {
54 const repo = getRepoById(app.db, record.repoId);
55 if (repo === undefined) return undefined;
56 const open = canRead(app.db, repo, undefined);
57 const base = new URL(`/${repo.ownerName}/${repo.name}`, forgeUrl).toString();
58 const number = env === "production" ? undefined : Number(env.slice(5));
59 const pull =
60 number === undefined ? undefined : getPull(app.db, repo.id, number);
61
62 let working: string | undefined;
63 if (open) {
64 const run = listRuns(app.db, repo.id, { kind: "agent", limit: 20 }).find(
65 (r) =>
66 r.state === "running" &&
67 (pull === undefined ? true : r.branch === pull.headBranch),
68 );
69 const who =
70 run?.actorId == null ? undefined : getUserById(app.db, run.actorId);
71 if (who !== undefined) working = who.displayName || who.username;
72 }
73 return {
74 app: record.slug,
75 env: number === undefined ? "production" : "preview",
76 ...(number === undefined
77 ? {}
78 : {
79 pull: {
80 number,
81 title: open
82 ? (pull?.title ?? getIssue(app.db, repo.id, number)?.title ?? "")
83 : "",
84 },
85 }),
86 ...(working === undefined ? {} : { working }),
87 links: {
88 comment:
89 number === undefined ? `${base}/issues/new` : `${base}/pulls/${number}`,
90 commentIsPull: number !== undefined,
91 tell: `${base}/tells/new`,
92 yours: `${base}/make-it-yours`,
93 home: new URL("/", forgeUrl).toString(),
94 },
95 };
96 }
97
98 /** The page with the bar's tag before `</body>`; the same bytes, streamed, when there is no body to put it in. */
99 export function withToolbar(response: Response): Response {
100 const out = new Headers(response.headers);
101 // The length changes; everything else about the response stands.
102 out.delete("content-length");
103 const rewritten = new HTMLRewriter()
104 .on("body", {
105 element(body) {
106 body.onEndTag((end) => {
107 end.before(TAG, { html: true });
108 });
109 },
110 })
111 .transform(response);
112 return new Response(rewritten.body, {
113 status: response.status,
114 statusText: response.statusText,
115 headers: out,
116 });
117 }
118
119 /**
120 * Whether this response is a page the bar belongs on: a navigation's plain
121 * HTML, uncompressed (the proxy passes the app's bytes through, so an
122 * encoded body cannot be edited), with a body to read, from an app that did
123 * not opt out.
124 */
125 export function wantsToolbar(
126 request: Request,
127 response: Response,
128 enabled: boolean,
129 ): boolean {
130 if (!enabled || request.method !== "GET" || response.body === null)
131 return false;
132 if (response.status < 200 || response.status === 204) return false;
133 if (response.status === 206 || response.headers.has("content-encoding"))
134 return false;
135 if (
136 !(response.headers.get("content-type") ?? "")
137 .toLowerCase()
138 .startsWith("text/html")
139 )
140 return false;
141 const dest = request.headers.get("sec-fetch-dest");
142 return dest === null || dest === "document";
143 }
144
145 /** The bar itself, in a shadow root. Styled through the CSSOM so an app's `style-src` has no say. */
146 export const TOOLBAR_JS = `(()=>{
147 if(window.__forgeBar)return;window.__forgeBar=1;
148 var D=document,H=D.createElement("div");
149 H.setAttribute("data-forge-toolbar","");
150 H.style.cssText="all:initial;position:fixed;z-index:2147483647;right:12px;bottom:12px";
151 var R=H.attachShadow({mode:"closed"});
152 try{var S=new CSSStyleSheet();S.replaceSync(
153 ":host{font:13px/1.4 system-ui,sans-serif}"+
154 "*{box-sizing:border-box}"+
155 "button,a{font:inherit;color:inherit}"+
156 ".pill{display:flex;align-items:center;gap:6px;max-width:calc(100vw - 24px);min-height:44px;padding:6px 14px;border:1px solid #0003;border-radius:999px;background:#111;color:#fff;cursor:pointer;white-space:nowrap}"+
157 ".pill b{overflow:hidden;text-overflow:ellipsis;max-width:40vw}"+
158 ".dot{width:8px;height:8px;border-radius:50%;background:#7c8}"+
159 ".panel{display:none;position:absolute;right:0;bottom:50px;width:min(280px,calc(100vw - 24px));padding:10px;border-radius:12px;background:#111;color:#fff;box-shadow:0 4px 20px #0006}"+
160 ".open .panel{display:block}"+
161 ".panel p{margin:0 0 8px;color:#ccc}"+
162 ".panel a{display:flex;align-items:center;min-height:44px;padding:7px 8px;border-radius:8px;color:#fff;text-decoration:none}"+
163 ".panel a:hover,.panel a:focus-visible,.pill:focus-visible{outline:2px solid #8af;outline-offset:1px}"+
164 ".hide{transform:translateY(80px)}"+
165 "@media(prefers-reduced-motion:no-preference){.panel{transition:opacity .1s}.hide{transition:transform .15s}}");
166 R.adoptedStyleSheets=[S]}catch(e){}
167 var W=D.createElement("div");R.appendChild(W);
168 var B=D.createElement("button");B.className="pill";B.type="button";
169 B.setAttribute("aria-expanded","false");
170 var dot=D.createElement("span");dot.className="dot";
171 var nm=D.createElement("b");B.append(dot,nm);
172 var P=D.createElement("div");P.className="panel";P.setAttribute("role","group");
173 W.append(B,P);
174 var on=false,y=scrollY;
175 function open(v){on=v;W.className=v?"open":"";B.setAttribute("aria-expanded",v?"true":"false")}
176 B.onclick=function(){open(!on)};
177 D.addEventListener("keydown",function(e){if(e.key==="Escape"&&on){open(false);B.focus()}});
178 addEventListener("scroll",function(){var n=scrollY;if(!on)W.className=n>y+8&&n>80?"hide":"";y=n},{passive:true});
179 function link(t,h){var a=D.createElement("a");a.textContent=t;a.href=h;a.target="_top";a.rel="noopener";P.appendChild(a)}
180 fetch("${TOOLBAR_FACTS}",{credentials:"same-origin",cache:"no-store"}).then(function(r){return r.ok?r.json():null}).then(function(f){
181 if(!f)return;
182 nm.textContent=f.app+(f.env==="preview"?" · #"+f.pull.number:"");B.setAttribute("aria-label",nm.textContent+", forge toolbar");
183 var p=D.createElement("p");
184 p.textContent=f.env==="preview"?"Preview of pull #"+f.pull.number+(f.pull.title?" — "+f.pull.title:""):"Production";
185 P.appendChild(p);
186 if(f.working){var w=D.createElement("p");w.textContent=f.working+" is working on it now";P.appendChild(w)}
187 var c=f.links.comment;
188 if(!f.links.commentIsPull){var u=new URL(c);u.searchParams.set("title","About "+location.pathname);u.searchParams.set("body",location.href+"\\n\\n");c=u.toString()}
189 link("Comment on this page",c);link("Tell the crew",f.links.tell);link("Make it yours",f.links.yours);link("Home",f.links.home);
190 D.body.appendChild(H)}).catch(function(){})
191 })();
192 `;
src/web/pages/issues.ts +4 −2
@@ -138,9 +138,11 @@ export function newIssuePage(ctx: Ctx): Response {
138138 ? accountOrReport(ctx, repo)
139139 : signInFirst(ctx);
140140 // `?sealed=1`: the repository page's "report it sealed" link.
141 // `?title=&body=`: the forge toolbar's "comment on this page" starts the
142 // issue with the page address; nothing is saved until the person submits.
141143 return composePage(ctx, repo, {
142 title: "",
143 body: "",
144 title: (ctx.url.searchParams.get("title") ?? "").slice(0, 256),
145 body: (ctx.url.searchParams.get("body") ?? "").slice(0, 2000),
144146 sealed: ctx.url.searchParams.get("sealed") === "1",
145147 });
146148 }
test/apps-toolbar.test.ts added +445
@@ -0,0 +1,445 @@
1 /**
2 * The forge's bar inside an app (#1057): HTML pages get one script tag,
3 * the script and its facts are the forge's to answer on the app's host,
4 * `"toolbar": false` turns it off, and nothing that is not a plain HTML
5 * page is touched.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { newApp, updateAppSettings } from "../src/actions/apps.ts";
14 import { commitToBranch } from "../src/actions/repos.ts";
15 import { AppsRuntime } from "../src/apps/runtime.ts";
16 import { parseManifest } from "../src/apps/manifest.ts";
17 import {
18 TOOLBAR_JS,
19 toolbarFacts,
20 wantsToolbar,
21 type ToolbarFacts,
22 withToolbar,
23 } from "../src/apps/toolbar.ts";
24 import { createIssue } from "../src/core/issues.ts";
25 import { createSession } from "../src/core/sessions.ts";
26 import { createUser, type User } from "../src/core/users.ts";
27 import type { Repo } from "../src/core/repos.ts";
28 import { claimRun, createRun, listRuns } from "../src/core/runs.ts";
29 import { serve, type Servers } from "../src/http/server.ts";
30 import { quietLogs } from "./helpers/globals.ts";
31
32 quietLogs();
33
34 const DOMAIN = "apps.test";
35 const TAG = '<script src="/__forge/toolbar.js" defer></script>';
36
37 describe("toolbar, in parts", () => {
38 const page = (body: string, type = "text/html; charset=utf-8") =>
39 new Response(body, { headers: { "content-type": type } });
40 const get = (headers: Record<string, string> = {}) =>
41 new Request("http://x.test/", { headers });
42
43 test("the tag goes before </body> and the length header goes", async () => {
44 const res = new Response("<html><body><p>hi</p></body></html>", {
45 headers: { "content-type": "text/html", "content-length": "35" },
46 });
47 const out = withToolbar(res);
48 expect(await out.text()).toBe(`<html><body><p>hi</p>${TAG}</body></html>`);
49 expect(out.headers.get("content-length")).toBeNull();
50 });
51
52 test("only a navigation's uncompressed HTML qualifies", () => {
53 expect(wantsToolbar(get(), page("<p>"), true)).toBe(true);
54 expect(wantsToolbar(get(), page("<p>"), false)).toBe(false);
55 expect(wantsToolbar(get(), page("<p>", "application/json"), true)).toBe(
56 false,
57 );
58 expect(
59 wantsToolbar(get({ "sec-fetch-dest": "iframe" }), page("x"), true),
60 ).toBe(false);
61 expect(
62 wantsToolbar(
63 new Request("http://x.test/", { method: "POST" }),
64 page("x"),
65 true,
66 ),
67 ).toBe(false);
68 const gz = page("x");
69 gz.headers.set("content-encoding", "gzip");
70 expect(wantsToolbar(get(), gz, true)).toBe(false);
71 expect(wantsToolbar(get(), new Response(null, { status: 304 }), true)).toBe(
72 false,
73 );
74 });
75
76 test("the script is small and the manifest opt-out is read", () => {
77 expect(TOOLBAR_JS.length).toBeLessThan(6 * 1024);
78 const make = (extra: string) =>
79 parseManifest(`{"app":{"run":"bun x.ts"${extra}}}`, undefined);
80 const off = make(',"toolbar":false');
81 expect(off.ok && off.value.toolbar).toBe(false);
82 const dflt = make("");
83 expect(dflt.ok && dflt.value.toolbar).toBeUndefined();
84 expect(make(',"toolbar":"no"').ok).toBe(false);
85 });
86 });
87
88 describe("toolbar facts", () => {
89 test("production and a preview say where they are and where to go", async () => {
90 const dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-facts-"));
91 const app = createApp({ dataDir, port: 0, host: "forge.test" });
92 try {
93 const a = await createUser(app.db, {
94 trusted: true,
95 username: "alice",
96 email: "[email protected]",
97 password: "a-good-passphrase",
98 adminIfFirst: true,
99 });
100 if (!a.ok) throw new Error(a.error);
101 const made = await newApp(app, a.value, {
102 name: "notes",
103 description: "A place for words",
104 visibility: "public",
105 });
106 if (!made.ok) throw new Error(String(made.error));
107 const forge = "http://forge.test";
108 const prod = toolbarFacts(app, forge, made.value.app, "production")!;
109 expect(prod.env).toBe("production");
110 expect(prod.pull).toBeUndefined();
111 expect(prod.links.commentIsPull).toBe(false);
112 expect(prod.links.comment).toBe(`${forge}/alice/notes/issues/new`);
113 const preview = toolbarFacts(app, forge, made.value.app, "pull-7")!;
114 expect(preview.env).toBe("preview");
115 expect(preview.pull?.number).toBe(7);
116 expect(preview.links.commentIsPull).toBe(true);
117 expect(preview.links.comment).toBe(`${forge}/alice/notes/pulls/7`);
118 expect(preview.links.yours).toBe(`${forge}/alice/notes/make-it-yours`);
119 expect(preview.links.home).toBe(`${forge}/`);
120 } finally {
121 app.close();
122 await rm(dataDir, { recursive: true, force: true });
123 }
124 });
125 });
126
127 describe("toolbar facts and privacy", () => {
128 test("a private repository shows neither the title nor who is working; a public one does", async () => {
129 const dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-priv-"));
130 const app = createApp({ dataDir, port: 0, host: "forge.test" });
131 try {
132 const a = await createUser(app.db, {
133 trusted: true,
134 username: "alice",
135 email: "[email protected]",
136 password: "a-good-passphrase",
137 adminIfFirst: true,
138 });
139 if (!a.ok) throw new Error(a.error);
140 const forge = "http://forge.test";
141 for (const visibility of ["public", "private"] as const) {
142 const made = await newApp(app, a.value, {
143 name: `${visibility}-app`,
144 description: "x",
145 visibility,
146 });
147 if (!made.ok) throw new Error(String(made.error));
148 const issue = createIssue(app.db, {
149 repoId: made.value.repo.id,
150 authorId: a.value.id,
151 title: "Secret plans",
152 });
153 if (!issue.ok) throw new Error(String(issue.error));
154 const run = createRun(app.db, {
155 repoId: made.value.repo.id,
156 kind: "agent",
157 actorId: a.value.id,
158 branch: "scout/x",
159 });
160 expect(claimRun(app.db, run.id)?.state).toBe("running");
161 const facts = toolbarFacts(
162 app,
163 forge,
164 made.value.app,
165 `pull-${issue.value.number}`,
166 )!;
167 const prod = toolbarFacts(app, forge, made.value.app, "production")!;
168 if (visibility === "public") {
169 expect(facts.pull?.title).toBe("Secret plans");
170 expect(facts.working).toBe(a.value.displayName || "alice");
171 expect(prod.working).toBe(a.value.displayName || "alice");
172 } else {
173 expect(facts.pull?.number).toBe(issue.value.number);
174 expect(facts.pull?.title).toBe("");
175 expect(facts.working).toBeUndefined();
176 expect(prod.working).toBeUndefined();
177 expect(JSON.stringify(facts)).not.toContain("Secret plans");
178 expect(JSON.stringify(facts)).not.toContain('alice"');
179 }
180 }
181 } finally {
182 app.close();
183 await rm(dataDir, { recursive: true, force: true });
184 }
185 });
186
187 test("a finished run is not someone working", async () => {
188 const dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-done-"));
189 const app = createApp({ dataDir, port: 0, host: "forge.test" });
190 try {
191 const a = await createUser(app.db, {
192 trusted: true,
193 username: "alice",
194 email: "[email protected]",
195 password: "a-good-passphrase",
196 adminIfFirst: true,
197 });
198 if (!a.ok) throw new Error(a.error);
199 const made = await newApp(app, a.value, {
200 name: "calm",
201 description: "x",
202 visibility: "public",
203 });
204 if (!made.ok) throw new Error(String(made.error));
205 createRun(app.db, {
206 repoId: made.value.repo.id,
207 kind: "agent",
208 actorId: a.value.id,
209 });
210 const facts = toolbarFacts(
211 app,
212 "http://forge.test",
213 made.value.app,
214 "production",
215 )!;
216 expect(facts.working).toBeUndefined();
217 } finally {
218 app.close();
219 await rm(dataDir, { recursive: true, force: true });
220 }
221 });
222 });
223
224 /** An app that shows the `accept-encoding` it was asked with, in a page. */
225 const ECHO_SERVER = `const port = Number(process.env.PORT ?? "0");
226 export const server = Bun.serve({
227 port,
228 fetch(request) {
229 const url = new URL(request.url);
230 if (url.pathname === "/healthz") return new Response("ok");
231 return new Response(
232 "<html><body><p>ae=" + request.headers.get("accept-encoding") + "</p></body></html>",
233 { headers: { "content-type": "text/html" } },
234 );
235 },
236 });
237 `;
238
239 const forgeJson = (extra: string) =>
240 `{"app":{"run":"bun run src/server.ts","health":"/healthz"${extra}}}\n`;
241
242 describe("toolbar in a running app", () => {
243 let alice: User;
244 let notesRepo: Repo;
245 let quiet: { repo: Repo };
246 let dataDir: string;
247 let app: App;
248 let servers: Servers;
249 let runtime: AppsRuntime;
250
251 beforeAll(async () => {
252 dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-"));
253 app = createApp({ dataDir, port: 0, host: "forge.test" });
254 servers = await serve(app);
255 runtime = new AppsRuntime(app, {
256 domain: DOMAIN,
257 scheme: "http",
258 publicPort: servers.port,
259 forgeUrl: servers.url,
260 concurrency: 1,
261 });
262 await runtime.start();
263 const a = await createUser(app.db, {
264 trusted: true,
265 username: "alice",
266 email: "[email protected]",
267 password: "a-good-passphrase",
268 adminIfFirst: true,
269 });
270 if (!a.ok) throw new Error(a.error);
271 alice = a.value;
272 const deployed = async (repo: Repo, oid?: string) => {
273 const deadline = Date.now() + 90_000;
274 while (Date.now() < deadline) {
275 const run = listRuns(app.db, repo.id, { kind: "deploy" }).find(
276 (r) => oid === undefined || r.commitOid === oid,
277 );
278 if (run && ["ok", "failed"].includes(run.state)) return;
279 await Bun.sleep(100);
280 }
281 throw new Error("no deploy settled");
282 };
283 for (const [name, extra] of [
284 ["notes", ""],
285 ["quiet", ',"toolbar":false'],
286 ] as const) {
287 const made = await newApp(app, a.value, {
288 name,
289 description: "A place for words",
290 visibility: "public",
291 });
292 if (!made.ok) throw new Error(String(made.error));
293 await deployed(made.value.repo);
294 const committed = await commitToBranch(app, a.value, made.value.repo, {
295 message: "Echo the encoding",
296 files: [
297 { path: "src/server.ts", content: ECHO_SERVER },
298 { path: "forge.json", content: forgeJson(extra) },
299 ],
300 });
301 if (!committed.ok) throw new Error(String(committed.error));
302 await deployed(made.value.repo, committed.value.commitOid);
303 if (name === "notes") notesRepo = made.value.repo;
304 else quiet = { repo: made.value.repo };
305 }
306 }, 240_000);
307
308 afterAll(async () => {
309 await runtime.stop();
310 servers.stop();
311 app.close();
312 await rm(dataDir, { recursive: true, force: true });
313 });
314
315 const at = (path: string, headers: Record<string, string> = {}) =>
316 fetch(`${servers.url}${path}`, {
317 headers: { host: `notes.${DOMAIN}`, accept: "text/html", ...headers },
318 redirect: "manual",
319 });
320
321 test("the app's page carries the tag, once", async () => {
322 const res = await at("/");
323 expect(res.status).toBe(200);
324 const text = await res.text();
325 expect(text.split(TAG).length).toBe(2);
326 expect(text.indexOf(TAG)).toBeLessThan(text.lastIndexOf("</body>"));
327 });
328
329 test("the script and the facts are answered on the app's host", async () => {
330 const js = await at("/__forge/toolbar.js");
331 expect(js.status).toBe(200);
332 expect(js.headers.get("content-type")).toContain("javascript");
333 expect(await js.text()).toBe(TOOLBAR_JS);
334 const facts = (await (
335 await at("/__forge/toolbar.json")
336 ).json()) as ToolbarFacts;
337 expect(facts.app).toBe("notes");
338 expect(facts.env).toBe("production");
339 expect(facts.links.comment).toBe(`${servers.url}/alice/notes/issues/new`);
340 expect(facts.links.tell).toBe(`${servers.url}/alice/notes/tells/new`);
341 expect(facts.links.yours).toBe(`${servers.url}/alice/notes/make-it-yours`);
342 expect(facts.links.home).toBe(`${servers.url}/`);
343 });
344
345 test("a non-HTML response is untouched", async () => {
346 const direct = await at("/healthz", { accept: "*/*" });
347 const text = await direct.text();
348 expect(text).not.toContain("toolbar");
349 const post = await fetch(`${servers.url}/`, {
350 method: "POST",
351 headers: { host: `notes.${DOMAIN}` },
352 redirect: "manual",
353 });
354 expect(await post.text()).not.toContain("__forge/toolbar");
355 });
356
357 test("a frame's request does not get the bar", async () => {
358 const res = await at("/", { "sec-fetch-dest": "iframe" });
359 expect(await res.text()).not.toContain(TAG);
360 });
361
362 test("the comment form starts from the page address", async () => {
363 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
364 const ask = async (query: string) => {
365 const res = await fetch(
366 `${servers.url}/alice/notes/issues/new?${query}`,
367 {
368 headers: { cookie },
369 redirect: "manual",
370 },
371 );
372 expect(res.status).toBe(200);
373 return res.text();
374 };
375 const plain = await ask("");
376 expect(plain).not.toContain("About /");
377
378 const filled = await ask(
379 `title=${encodeURIComponent("About /")}&body=${encodeURIComponent("http://notes.apps.test/\n\n")}`,
380 );
381 expect(filled).toContain('value="About /"');
382 expect(filled).toContain("http://notes.apps.test/");
383
384 const hostile = await ask(
385 `title=${encodeURIComponent("<script>alert(1)</script>")}&body=${encodeURIComponent("<img src=x onerror=1>")}`,
386 );
387 expect(hostile).not.toContain("<script>alert(1)</script>");
388 expect(hostile).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
389 expect(hostile).not.toContain("<img src=x");
390
391 const long = await ask(`body=${"b".repeat(5000)}`);
392 expect(long).toContain("b".repeat(2000));
393 expect(long).not.toContain("b".repeat(2001));
394 const longTitle = await ask(`title=${"t".repeat(600)}`);
395 expect(longTitle).toContain("t".repeat(256));
396 expect(longTitle).not.toContain("t".repeat(257));
397 });
398
399 test("an app that opts out gets no tag and is not asked for identity", async () => {
400 const ae = (text: string) => /ae=([^<]*)</.exec(text)?.[1];
401 const on = await (await at("/", { "accept-encoding": "gzip" })).text();
402 expect(on).toContain(TAG);
403 expect(ae(on)).toBe("identity");
404
405 const off = await fetch(`${servers.url}/`, {
406 headers: {
407 host: `quiet.${DOMAIN}`,
408 accept: "text/html",
409 "accept-encoding": "gzip",
410 },
411 });
412 const body = await off.text();
413 expect(body).not.toContain("__forge/toolbar");
414 expect(ae(body)).toBe("gzip");
415 expect(quiet.repo.name).toBe("quiet");
416 });
417
418 test("a nested host does not get the forge's routes", async () => {
419 for (const path of ["/__forge/toolbar.json", "/__forge/toolbar.js"]) {
420 const res = await fetch(`${servers.url}${path}`, {
421 headers: { host: `inner--notes.${DOMAIN}` },
422 });
423 const text = await res.text();
424 expect(text).not.toContain('"links"');
425 expect(text).not.toBe(TOOLBAR_JS);
426 }
427 });
428
429 test("a private app's facts go through the same door as its pages", async () => {
430 expect(
431 updateAppSettings(app, alice, notesRepo, { access: "private" }).ok,
432 ).toBe(true);
433 for (const path of ["/__forge/toolbar.json", "/__forge/toolbar.js"]) {
434 const res = await at(path, { accept: "*/*" });
435 expect(res.status).not.toBe(200);
436 const text = await res.text();
437 expect(text).not.toContain('"links"');
438 expect(text).not.toBe(TOOLBAR_JS);
439 }
440 // A guest asking for the page is sent to sign in, not shown the bar.
441 const page = await at("/");
442 expect(page.status).toBe(303);
443 expect(await page.text()).not.toContain(TAG);
444 });
445 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs