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 #1020

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +431 −0
docs/APPS.md +13
@@ -198,6 +198,19 @@ What a person sees, in order:
198198 Nothing above required a terminal. Everything above is also reachable from
199199 one, and from the JSON API, because each step is an action.
200200
201 ## The forge's bar
202
203 Every HTML page an app or preview serves ends with the forge's bar: a small
204 pill at the bottom right (in a shadow root, under 6 KB) that opens to the app,
205 its environment (production, or the preview of pull #n and its title) and a
206 way home to the forge. The tag is appended to the page as it streams; the
207 script is the forge's, served from the app's own host at
208 `/__forge/toolbar.js`, so an app whose CSP allows `'self'` scripts allows the
209 bar. Pages are asked of the app unencoded so they can be read; compressed
210 HTML, other statuses, `HEAD` and everything that is not `text/html` pass
211 byte for byte. Turn it off with `"toolbar": false` at the top level of
212 `forge.json`.
213
201214 ## How an app is declared
202215
203216 The repository says how to run itself, in `forge.json` at its root:
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` (top level of `forge.json`): `false` keeps the forge's bar out of the app's pages. */
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 = 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: toolbar ?? true,
169175 });
170176 }
171177
src/apps/proxy.ts +73
@@ -34,6 +34,13 @@ 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_JS,
39 TOOLBAR_PATH,
40 carriesToolbar,
41 toolbarTag,
42 withToolbar,
43 } from "./toolbar.ts";
3744
3845 export interface AppTarget {
3946 readonly app: AppRecord;
@@ -527,6 +534,15 @@ export async function proxyApp(
527534 });
528535 }
529536 }
537 // The bar's script is the forge's own, static, and the same everywhere.
538 if (url.pathname === TOOLBAR_PATH && request.method === "GET") {
539 return new Response(TOOLBAR_JS, {
540 headers: {
541 "content-type": "text/javascript; charset=utf-8",
542 "cache-control": "public, max-age=3600",
543 },
544 });
545 }
530546 // An environment asleep wakes for the request that wants it, and the
531547 // request waits the second that takes rather than seeing a closed door.
532548 if (runtime.envStatus(target.app, target.env)?.state === "asleep")
@@ -543,6 +559,13 @@ export async function proxyApp(
543559 const headers = new Headers(request.headers);
544560 for (const name of HOP_BY_HOP) headers.delete(name);
545561 for (const name of IDENTITY_HEADERS) headers.delete(name);
562 // A page the bar is to join is read as it comes, so it is asked for plain.
563 if (
564 request.method === "GET" &&
565 (request.headers.get("accept") ?? "").includes("text/html") &&
566 runtime.toolbarOn(target.app, target.env)
567 )
568 headers.set("accept-encoding", "identity");
546569 headers.set("x-forwarded-host", request.headers.get("host") ?? "");
547570 headers.set("x-forwarded-proto", url.protocol.replace(":", ""));
548571 for (const [name, value] of Object.entries(
@@ -586,6 +609,37 @@ export async function proxyApp(
586609 // without the app having to say so.
587610 if (isHtml(out) && reportUrl(runtime, target) !== undefined)
588611 out.append("link", REPORT_LINK);
612 if (
613 !target.nested &&
614 response.body !== null &&
615 carriesToolbar(request.method, response.status, out) &&
616 runtime.toolbarOn(target.app, target.env)
617 ) {
618 const tag = toolbarFor(runtime, target);
619 out.delete("etag");
620 // A page of known size stays a page of known size; one that streams
621 // keeps streaming, with the tag after its last byte.
622 const length = Number(out.get("content-length") ?? "");
623 if (Number.isInteger(length) && length <= PAGE_BUFFER_MAX) {
624 const page = new Uint8Array(await response.arrayBuffer());
625 const bar = new TextEncoder().encode(tag);
626 const whole = new Uint8Array(page.length + bar.length);
627 whole.set(page);
628 whole.set(bar, page.length);
629 out.set("content-length", String(whole.length));
630 return new Response(whole, {
631 status: response.status,
632 statusText: response.statusText,
633 headers: out,
634 });
635 }
636 out.delete("content-length");
637 return new Response(withToolbar(response.body, tag), {
638 status: response.status,
639 statusText: response.statusText,
640 headers: out,
641 });
642 }
589643 const eventStream =
590644 response.body !== null &&
591645 (response.headers.get("content-type") ?? "")
@@ -601,6 +655,25 @@ export async function proxyApp(
601655 );
602656 }
603657
658 /** The largest page of announced size read whole to add the bar to. */
659 const PAGE_BUFFER_MAX = 4 * 1024 * 1024;
660
661 /** The bar's tag for this environment: app, and the pull a preview shows. */
662 function toolbarFor(runtime: AppsRuntime, target: AppTarget): string {
663 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
664 const pull =
665 number === undefined
666 ? undefined
667 : getIssue(runtime.app.db, target.app.repoId, Number(number));
668 return toolbarTag({
669 app: target.app.slug,
670 env: target.env,
671 // A sealed pull's title is for those who may see it; the bar names the number only.
672 title: pull?.sealed === true ? undefined : pull?.title,
673 home: new URL("/", runtime.options.forgeUrl).toString(),
674 });
675 }
676
604677 /**
605678 * An event stream, passed through untouched while it keeps the environment
606679 * busy: held from its first byte until it ends, fails, or the browser
src/apps/runtime.ts +5
@@ -435,6 +435,11 @@ export class AppsRuntime {
435435 return this.describe(state);
436436 }
437437
438 /** Whether the app's manifest lets the forge's bar into its pages. */
439 toolbarOn(record: AppRecord, env: EnvName): boolean {
440 return this.envs.get(key(record.id, env))?.live?.manifest.toolbar !== false;
441 }
442
438443 /** Every environment of an app, production first. */
439444 status(record: AppRecord): EnvStatus[] {
440445 const out: EnvStatus[] = [];
src/apps/toolbar.ts added +120
@@ -0,0 +1,120 @@
1 /**
2 * The forge's bar inside an app: a script tag appended to the app's HTML
3 * pages, and the script it points at. The script is the forge's, served from
4 * the app's own host at `/__forge/toolbar.js`, so an app that allows its own
5 * scripts allows the bar. It draws a collapsed pill in a shadow root, so
6 * neither side's CSS reaches the other, and says where the visitor is.
7 * Actions (comment, tell, make it yours) are #810's; the panel has room.
8 */
9
10 /** What the bar says; plain data, escaped where it is written. */
11 export interface ToolbarInfo {
12 readonly app: string;
13 /** `production`, or `pull-N`. */
14 readonly env: string;
15 /** The title of the pull a preview shows. */
16 readonly title?: string | undefined;
17 /** Where "home" goes: the forge's feed. */
18 readonly home: string;
19 }
20
21 export const TOOLBAR_PATH = "/__forge/toolbar.js";
22
23 const TITLE_MAX = 120;
24
25 const attr = (s: string): string =>
26 s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
27
28 /** The tag that loads the bar, with its facts as attributes. */
29 export function toolbarTag(info: ToolbarInfo): string {
30 const pull = /^pull-(\d+)$/.exec(info.env)?.[1];
31 const title = (info.title ?? "").replace(/\s+/g, " ").slice(0, TITLE_MAX);
32 return (
33 `<script src="${TOOLBAR_PATH}" defer data-forge-toolbar` +
34 ` data-app="${attr(info.app)}"` +
35 (pull === undefined ? "" : ` data-pull="${pull}" data-title="${attr(title)}"`) +
36 ` data-home="${attr(info.home)}"></script>`
37 );
38 }
39
40 /**
41 * The body with the tag appended once it ends. Chunks pass as they come —
42 * nothing is held — and a browser reads a script after `</html>` as the
43 * end of the body.
44 */
45 export function withToolbar(
46 body: ReadableStream<Uint8Array>,
47 tag: string,
48 ): ReadableStream<Uint8Array> {
49 const bytes = new TextEncoder().encode(tag);
50 return body.pipeThrough(
51 new TransformStream<Uint8Array, Uint8Array>({
52 flush(controller) {
53 controller.enqueue(bytes);
54 },
55 }),
56 );
57 }
58
59 /**
60 * Whether a response may carry the bar: a whole, plain HTML page. Encoded
61 * bodies, partial content, empty statuses and head requests pass untouched.
62 */
63 export function carriesToolbar(
64 method: string,
65 status: number,
66 headers: Headers,
67 ): boolean {
68 return (
69 method === "GET" &&
70 status === 200 &&
71 (headers.get("content-type") ?? "").toLowerCase().startsWith("text/html") &&
72 !headers.has("content-encoding")
73 );
74 }
75
76 /** The script. Under 6 KB; no dependencies; reads its facts from its tag. */
77 export const TOOLBAR_JS = `(()=>{
78 const s=document.querySelector("script[data-forge-toolbar]");
79 if(!s||document.getElementById("forge-toolbar"))return;
80 const d=s.dataset,pull=d.pull,host=document.createElement("div");
81 host.id="forge-toolbar";
82 host.style.cssText="all:initial;position:fixed;right:max(8px,env(safe-area-inset-right));bottom:max(8px,env(safe-area-inset-bottom));z-index:2147483647";
83 const r=host.attachShadow({mode:"closed"});
84 const st=document.createElement("style");
85 st.textContent=\`
86 *{box-sizing:border-box}
87 :host{font:14px/1.4 system-ui,sans-serif;color-scheme:light dark}
88 button,a{font:inherit;color:inherit}
89 .pill{display:block;width:44px;height:44px;border-radius:22px;border:1px solid #8886;background:Canvas;color:CanvasText;cursor:pointer;font-weight:700;box-shadow:0 1px 6px #0004}
90 .pill:focus-visible,a:focus-visible{outline:2px solid Highlight;outline-offset:2px}
91 .panel{position:absolute;right:0;bottom:52px;width:min(18rem,calc(100vw - 16px));padding:12px 14px;border:1px solid #8886;border-radius:10px;background:Canvas;color:CanvasText;box-shadow:0 2px 12px #0004}
92 .panel[hidden]{display:none}
93 p{margin:0 0 4px}
94 .dim{opacity:.7}
95 .t{overflow-wrap:anywhere}
96 nav{display:flex;gap:12px;margin-top:10px}
97 a{text-decoration:underline}
98 \`;
99 const pill=document.createElement("button");
100 pill.className="pill";pill.type="button";pill.textContent="F";
101 pill.setAttribute("aria-label","Forge toolbar");pill.setAttribute("aria-expanded","false");
102 const panel=document.createElement("div");
103 panel.className="panel";panel.hidden=true;
104 const line=(cls,text)=>{const p=document.createElement("p");p.className=cls;p.textContent=text;panel.append(p)};
105 line("",d.app);
106 line("dim",pull?"Preview of pull #"+pull:"Production");
107 if(d.title)line("dim t",d.title);
108 const nav=document.createElement("nav");
109 nav.setAttribute("data-room","actions");
110 const home=document.createElement("a");
111 home.textContent="Home";
112 try{const u=new URL(d.home);if(u.protocol==="https:"||u.protocol==="http:")home.href=u.href}catch{}
113 nav.append(home);panel.append(nav);
114 const toggle=(open)=>{panel.hidden=!open;pill.setAttribute("aria-expanded",String(open))};
115 pill.onclick=()=>toggle(panel.hidden);
116 addEventListener("keydown",e=>{if(e.key==="Escape"&&!panel.hidden){toggle(false);pill.focus()}});
117 r.append(st,pill,panel);
118 document.body.append(host);
119 })();
120 `;
test/apps-toolbar.test.ts added +214
@@ -0,0 +1,214 @@
1 /**
2 * The forge's bar in an app (#609): an app's HTML pages end with the bar's
3 * tag, served from the app's own host; anything that is not a plain HTML
4 * page passes byte for byte; `"toolbar": false` in forge.json keeps it out.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { AppsRuntime } from "../src/apps/runtime.ts";
13 import { parseManifest } from "../src/apps/manifest.ts";
14 import {
15 TOOLBAR_JS,
16 carriesToolbar,
17 toolbarTag,
18 } from "../src/apps/toolbar.ts";
19 import { newApp } from "../src/actions/apps.ts";
20 import { commitToBranch } from "../src/actions/repos.ts";
21 import type { Repo } from "../src/core/repos.ts";
22 import { listRuns, type Run } from "../src/core/runs.ts";
23 import { createUser, type User } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25
26 const SERVER = `export const server = Bun.serve({
27 port: Number(process.env.PORT ?? "0"),
28 fetch(request) {
29 const path = new URL(request.url).pathname;
30 if (path === "/data.json")
31 return Response.json({ n: 1 }, { headers: { "x-enc": request.headers.get("accept-encoding") ?? "" } });
32 return new Response("<!doctype html><title>t</title><h1>hello</h1>", {
33 headers: { "content-type": "text/html; charset=utf-8" },
34 });
35 },
36 });
37 `;
38 const SERVER_TEST = `import { expect, test } from "bun:test";
39 process.env.PORT = "0";
40 const { server } = await import("./server.ts");
41 test("serves", async () => {
42 expect((await fetch(\`http://\${server.hostname}:\${server.port}/\`)).status).toBe(200);
43 });
44 `;
45 const forgeJson = (extra: string) =>
46 `{${extra}"app":{"run":"bun run src/server.ts","install":"","health":"/"}}`;
47
48 describe("the toolbar's pieces", () => {
49 test("the tag carries escaped facts; the script is small", () => {
50 const tag = toolbarTag({
51 app: "notes",
52 env: "pull-7",
53 title: 'x"><script>alert(1)</script>',
54 home: "https://forge.test/",
55 });
56 expect(tag).toContain('data-pull="7"');
57 expect(tag).not.toContain("<script>alert");
58 expect(tag).toContain("&#34;&#62;");
59 expect(toolbarTag({ app: "n", env: "production", home: "/" })).not.toContain(
60 "data-pull",
61 );
62 expect(Buffer.byteLength(TOOLBAR_JS)).toBeLessThan(6 * 1024);
63 expect(TOOLBAR_JS).not.toContain("eval(");
64 });
65
66 test("only whole plain HTML pages carry it", () => {
67 const html = new Headers({ "content-type": "text/html; charset=utf-8" });
68 expect(carriesToolbar("GET", 200, html)).toBe(true);
69 expect(carriesToolbar("HEAD", 200, html)).toBe(false);
70 expect(carriesToolbar("GET", 404, html)).toBe(false);
71 expect(carriesToolbar("GET", 206, html)).toBe(false);
72 expect(
73 carriesToolbar(
74 "GET",
75 200,
76 new Headers({ "content-type": "text/html", "content-encoding": "gzip" }),
77 ),
78 ).toBe(false);
79 expect(
80 carriesToolbar("GET", 200, new Headers({ "content-type": "application/json" })),
81 ).toBe(false);
82 });
83
84 test("forge.json can turn it off, and only with a boolean", () => {
85 const run = `"app":{"run":"bun run x.ts"}`;
86 const on = parseManifest(`{${run}}`, undefined);
87 expect(on.ok && on.value.toolbar).toBe(true);
88 const off = parseManifest(`{"toolbar":false,${run}}`, undefined);
89 expect(off.ok && off.value.toolbar).toBe(false);
90 expect(parseManifest(`{"toolbar":"no",${run}}`, undefined).ok).toBe(false);
91 });
92 });
93
94 describe("the toolbar through the proxy", () => {
95 let dataDir: string;
96 let app: App;
97 let servers: Servers;
98 let runtime: AppsRuntime;
99 let alice: User;
100 const DOMAIN = "apps.test";
101 const repos = new Map<string, Repo>();
102
103 const at = (slug: string, path: string, headers: Record<string, string> = {}) =>
104 fetch(`${servers.url}${path}`, {
105 headers: { host: `${slug}.${DOMAIN}`, ...headers },
106 redirect: "manual",
107 });
108
109 async function settled(repo: Repo, commitOid?: string): Promise<Run> {
110 const deadline = Date.now() + 90_000;
111 while (Date.now() < deadline) {
112 const run = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(
113 (r) =>
114 r.env === "production" &&
115 (commitOid === undefined || r.commitOid === commitOid),
116 );
117 if (run && ["ok", "failed", "cancelled"].includes(run.state)) return run;
118 await Bun.sleep(100);
119 }
120 throw new Error("run did not settle in time");
121 }
122
123 async function deploy(name: string, extra: string): Promise<void> {
124 const made = await newApp(app, alice, {
125 name,
126 description: "A page",
127 visibility: "public",
128 });
129 if (!made.ok) throw new Error(String(made.error));
130 const repo = made.value.repo;
131 repos.set(name, repo);
132 await settled(repo);
133 const committed = await commitToBranch(app, alice, repo, {
134 message: "Serve a page",
135 files: [
136 { path: "src/server.ts", content: SERVER },
137 { path: "src/server.test.ts", content: SERVER_TEST },
138 { path: "forge.json", content: forgeJson(extra) },
139 { path: "src/audit.test.ts", content: null },
140 { path: "src/openapi.test.ts", content: null },
141 { path: "src/security.test.ts", content: null },
142 ],
143 });
144 if (!committed.ok) throw new Error(String(committed.error));
145 const run = await settled(repo, committed.value.commitOid);
146 if (run.state !== "ok") throw new Error(`deploy failed: ${run.summary}`);
147 }
148
149 beforeAll(async () => {
150 dataDir = await mkdtemp(join(tmpdir(), "forge-apps-toolbar-"));
151 app = createApp({ dataDir, port: 0 });
152 servers = await serve(app);
153 runtime = new AppsRuntime(app, {
154 domain: DOMAIN,
155 scheme: "http",
156 publicPort: servers.port,
157 forgeUrl: servers.url,
158 concurrency: 2,
159 });
160 await runtime.start();
161 const created = await createUser(app.db, {
162 trusted: true,
163 username: "alice",
164 email: "[email protected]",
165 password: "a-good-passphrase",
166 adminIfFirst: true,
167 });
168 if (!created.ok) throw new Error(created.error);
169 alice = created.value;
170 await deploy("shown", "");
171 await deploy("quiet", '"toolbar":false,');
172 }, 240_000);
173
174 afterAll(async () => {
175 await runtime.stop();
176 servers.stop();
177 app.close();
178 await rm(dataDir, { recursive: true, force: true });
179 });
180
181 test("an HTML page ends with the bar's tag, and the script is served from the app's host", async () => {
182 const page = await at("shown", "/", { accept: "text/html" });
183 const body = await page.text();
184 expect(body).toStartWith("<!doctype html><title>t</title><h1>hello</h1>");
185 expect(body).toContain('<script src="/__forge/toolbar.js" defer');
186 expect(body).toContain('data-app="shown"');
187 // The length announced is the length of the page with the bar.
188 expect(Number(page.headers.get("content-length"))).toBe(
189 Buffer.byteLength(body),
190 );
191 const js = await at("shown", "/__forge/toolbar.js");
192 expect(js.status).toBe(200);
193 expect(js.headers.get("content-type")).toContain("javascript");
194 expect(js.headers.get("cache-control")).toContain("max-age");
195 expect(await js.text()).toBe(TOOLBAR_JS);
196 });
197
198 test("a response that is not HTML is the app's, byte for byte", async () => {
199 const res = await at("shown", "/data.json", { accept: "application/json" });
200 expect(await res.text()).toBe('{"n":1}');
201 expect(res.headers.get("content-type")).toContain("application/json");
202 // The app's encoding is the app's: only a page asked for as HTML is read plain.
203 const encoded = await at("shown", "/data.json", {
204 accept: "application/json",
205 "accept-encoding": "gzip",
206 });
207 expect(encoded.headers.get("x-enc")).toBe("gzip");
208 });
209
210 test("toolbar: false keeps the page as the app wrote it", async () => {
211 const page = await at("quiet", "/", { accept: "text/html" });
212 expect(await page.text()).toBe("<!doctype html><title>t</title><h1>hello</h1>");
213 });
214 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs