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

The forge toolbar in a preview names the pull it previews and links to it, with a comment box that posts to that pull #13690

Merged opened this

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

Merged

mason/forge:mason/13664-the-forge-toolbar-in-a-preview-names-the → main 8 commits fork 4 threads · 4 unresolved

  • Merged. mason/13664-the-forge-toolbar-in-a-preview-names-the was merged into main as da25118.

Review

Sign in to review this change.
16 files changed +539 −40
docs/features/forge-toolbar.md +3 −1
@@ -9,6 +9,8 @@ preview), so you always know where you are and can get back to the forge.
99 byte. A page that already carries the tag is not given a second.
1010 - **What it says:** the app, the environment and, on a preview, a link
1111 "Preview of pull #N" to the pull's page on the forge; Home goes to the forge.
12 - **The preview line:** on a preview the pill's panel says "Preview of pull #N: <title>", the title as the forge holds it, set as text, linked to the pull. Production has no such line.
13 - **Comment on the pull:** a preview's panel also has a comment box, built by a small script of its own (`src/apps/toolbar_comment.ts`, under 4 KB) that the pill fetches from the app's host the first time a preview's panel opens; production pages and a closed pill never load it, and the pill keeps its 24 KB budget. A viewer the tag names as signed out (`data-in` absent) sees "Sign in to comment on this pull", which goes through `/__forge/signin` and back to the page, instead of a box. The box posts `POST /__forge/comment` with `{ text }`, same-origin and with the page's proof, and the comment lands on the pull the environment's name gives (`pull-N`; never a number from the body), as the person the app's grant names. Words: signed out is `401` ("Sign in to the forge to comment on this pull."); production, an unknown number or a non-pull is `404`; empty text is `400`, and so is text over 4000 characters (`COMMENT_MAX`, the box's `maxLength` too) with `body_too_long`; too many is `429` with `Retry-After` (6 a minute for a person, 20 for a socket address, so a script holding one proof cannot flood the pull's author). A refused comment keeps what was typed and says why under the box; only a posted one clears it, and its "Commented on pull #N." links to the address the door answered with (only when that is on the forge's origin). The terminal already comments on a pull (`src/tui/screens/pull.ts`), so this is a page-only surface. See `src/apps/pull_comment.ts`.
1214 - **Which commit:** one more line, `Serving a1b2c3d, live 4 min ago`, the short
1315 id linked to the commit on the forge. The id and the instant come from the
1416 forge's own record of the running environment (the same source as the note's
@@ -45,7 +47,7 @@ preview), so you always know where you are and can get back to the forge.
4547 pill out; the app still works.
4648 - **Off:** `"toolbar": false` in `forge.json`.
4749
48 Tests: `test/toolbar-injection.test.ts`, `test/apps-toolbar.test.ts`, `test/note-context.test.ts`, `test/apps-feedback.test.ts`, `test/apps-toolbar-yours.test.ts`, `test/toolbar-serving.test.ts`.
50 Tests: `test/toolbar-injection.test.ts`, `test/apps-toolbar.test.ts`, `test/note-context.test.ts`, `test/apps-feedback.test.ts`, `test/apps-toolbar-yours.test.ts`, `test/toolbar-serving.test.ts`, `test/toolbar-where.test.ts`, `test/toolbar-budget.test.ts`.
4951
5052 ## By keyboard and screen reader
5153
scripts/gate.ts +1
@@ -50,6 +50,7 @@ export const EXCLUDED: readonly Exclusion[] = [];
5050 * short: an entry is a debt with an owner, not a home.
5151 */
5252 export const SLOW: readonly Exclusion[] = [
53 { file: "test/apps-toolbar.test.ts", reason: "its opt-out test deploys a real scaffolded app twice; 2.35 s under full-suite load, 2.8 s alone here", issue: 13773 },
5354 { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 },
5455 { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 },
5556 // From the breach list closing this pull's check log at e2a5c15 (#12088):
src/apps/feedback.ts +15 −2
@@ -11,6 +11,7 @@
1111 * - `POST /__forge/note/picture?note=<id>` adds the picture a sender chose to
1212 * send (#4820) to a note of theirs: raw PNG or JPEG bytes, at most
1313 * `PICTURE_MAX`, judged by their signature, one per note.
14 * - `POST /__forge/comment` comments on the pull a preview shows (`pull_comment.ts`).
1415 * - Same origin only, a body read only up to `REQUEST_MAX` bytes, and limits
1516 * keyed on the socket's client (`http/peer.ts`), never on a header the
1617 * client wrote.
@@ -27,6 +28,7 @@ import { getUserById, isActive, type User } from "../core/users.ts";
2728 import { sha256 } from "../kernel/hash.ts";
2829 import { parseNoteContext } from "../actions/note_context.ts";
2930 import { NOTE_FAILED } from "./note_words.ts";
31 import { commentOnPull } from "./pull_comment.ts";
3032
3133 export const REQUEST_MAX = 16 * 1024;
3234 export const VISITOR_COOKIE = "forge_visitor";
@@ -171,7 +173,8 @@ async function readJson(request: Request): Promise<Record<string, unknown> | und
171173
172174 /**
173175 * The page a note was sent from, as an origin plus path of this app, or "" when it is not one.
174 * The URL parser percent-encodes a path; one over 300 chars or outside the charset is dropped, not trimmed.
176 * The URL parser percent-encodes a path; one over 300 chars or outside the charset is dropped, not
177 * trimmed.
175178 */
176179 export function pageOf(raw: unknown, host: string | null, origin: string): string {
177180 if (typeof raw !== "string") return "";
@@ -182,6 +185,15 @@ export function pageOf(raw: unknown, host: string | null, origin: string): strin
182185 return "";
183186 }
184187
188 /**
189 * A comment on the pull this preview shows, from the person the grant names (`pull_comment.ts`).
190 */

No rate limit on this door (the note door has one keyed on ask.source/viewer). Add one here, answer 429, and test it.

191 async function comment(ask: FeedbackAsk, door: Door): Promise<Response> {
192 const body = await readJson(ask.request);
193 const done = commentOnPull(ask.app, ask.forgeUrl, door.repo, ask.env, door.viewer, body?.text, ask.source);
194 return json(done.status, done.body, done.retryAfter === undefined ? {} : { "retry-after": String(done.retryAfter) });
195 }
196
185197 async function send(ask: FeedbackAsk, door: Door): Promise<Response> {
186198 const { request } = ask;
187199 const body = await readJson(request);
@@ -262,7 +274,7 @@ export async function feedback(ask: FeedbackAsk): Promise<Response | undefined>
262274 const path = ask.url.pathname;
263275 const method = ask.request.method;
264276 if (path === "/__forge/note/moderate") return json(404, { error: "not_found" });
265 if (path !== "/__forge/note" && path !== "/__forge/notes" && path !== "/__forge/note/picture") return undefined;
277 if (path !== "/__forge/note" && path !== "/__forge/notes" && path !== "/__forge/note/picture" && path !== "/__forge/comment") return undefined;
266278 const host = ask.request.headers.get("host");
267279 const proven = spendProof(ask.request.headers.get(PROOF_HEADER), ask.grantCookie, host);
268280 const answer = await answerNote(proven ? ask : { ...ask, viewerId: undefined }, path, method, proven);
@@ -279,5 +291,6 @@ async function answerNote(ask: FeedbackAsk, path: string, method: string, proven
279291 }
280292 if (method !== "POST") return json(405, { error: "method" }, { allow: "POST" });
281293 if (!sameOrigin(ask.request)) return json(403, { error: "cross_origin" });
294 if (path === "/__forge/comment") return comment(ask, door);
282295 return path === "/__forge/note/picture" ? picture(ask, door) : send(ask, door);
283296 }
src/apps/proxy.ts +14 −7
@@ -75,6 +75,7 @@ import { HOOK_MAX_BYTES, HOOK_PREFIX, hookPath, readCapped } from "./hook_relay.
7575 import { liveOf } from "../perf/live.ts";
7676 import { heldBy, noteRelayWait, stallTiming } from "./relay_wait.ts";
7777 import { cspNonce, htmlAnswer, readPage, rewritable, TOOLBAR_ASSET_PATH, TOOLBAR_ASSET_PREFIX, toolbarResponse, withToolbar, type PillWhere } from "./toolbar.ts";
78 import { COMMENT_ASSET_PATH, commentResponse } from "./toolbar_comment.ts";
7879
7980 const proxySecure = (request: Request, url: URL, forgeUrl: string): boolean =>
8081 secureFor(url, forgeUrl) ||
@@ -600,6 +601,8 @@ export function pillWhere(
600601 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
601602 if (number === undefined) return where;
602603 where.pull = Number(number);
604 // Whether the panel offers the comment box or the way to sign in for it.
605 if (user !== undefined) where.signedIn = true;
603606 // What a waiting guest's preview runs on is said to whoever looks at it: it is about the page in
604607 // front of them.
605608 const row = getPull(db, target.app.repoId, where.pull);
@@ -1075,14 +1078,18 @@ export async function proxyApp(
10751078 server,
10761079 );
10771080 }
1078 // The pill's script, from the app's own host: only the exact hashed path
1079 // is it; any other /__forge/toolbar… path is the forge's 404, never the app's.
1081 // The pill's script and its preview comment box (toolbar_comment.ts), from the app's own host:
1082 // only the exact hashed paths are them; any other /__forge/toolbar… path is the forge's 404,
1083 // never the app's.
10801084 if (url.pathname.startsWith(TOOLBAR_ASSET_PREFIX) && !target.nested) {
10811085 return securityFloor(
1082 url.pathname === TOOLBAR_ASSET_PATH &&
1083 (request.method === "GET" || request.method === "HEAD")
1084 ? toolbarResponse(request)
1085 : notFound(),
1086 request.method !== "GET" && request.method !== "HEAD"
1087 ? notFound()
1088 : url.pathname === TOOLBAR_ASSET_PATH
1089 ? toolbarResponse(request)
1090 : url.pathname === COMMENT_ASSET_PATH
1091 ? commentResponse(request)
1092 : notFound(),
10861093 );
10871094 }
10881095 // A grant with this forge's own token is answered here. On a nested
@@ -1261,7 +1268,7 @@ export async function proxyApp(
12611268 // owner's moderation. Answered here, never reaching the app. A path under
12621269 // /__forge/note that is none of its doors (`/__forge/notebook`) is the
12631270 // app's own, and goes through below with the app's headers, not the floor.
1264 if (url.pathname.startsWith("/__forge/note") && !target.nested) {
1271 if ((url.pathname.startsWith("/__forge/note") || url.pathname === "/__forge/comment") && !target.nested) {
12651272 const cookie = cookieValue(request, grantCookieName(target));
12661273 const signed =
12671274 cookie === undefined
src/apps/pull_comment.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * The pill's comment box on a preview: `POST /__forge/comment` with `{ text }` adds a comment to
3 * the pull this preview shows, as the person the app's grant names. The pull is read from the
4 * environment's name, never from the body; production has none, so it answers 404.
5 */
6 import type { App } from "../app.ts";
7 import { addComment } from "../actions/issues.ts";
8 import { getIssue } from "../core/issues.ts";
9 import type { Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import { RateLimiter } from "../core/ratelimit.ts";
12 import { noteClock } from "../actions/app_notes.ts";
13
14 /** Comments a minute one person may post from the pill, and one socket address over all people. */
15 export const COMMENTS_PER_PERSON = 6;
16 export const COMMENTS_PER_SOURCE = 20;
17 /**
18 * The longest comment the pill takes, in characters: well inside the door's 16 KB request read
19 * (`REQUEST_MAX` in feedback.ts), so a long one is named too long, never cut into "empty".
20 */
21 export const COMMENT_MAX = 4000;
22 const tick = (): number => noteClock.now();
23 const limiters = new WeakMap<App, { person: RateLimiter; source: RateLimiter }>();
24 function limitsOf(app: App) {
25 let l = limiters.get(app);
26 if (l === undefined) {
27 const make = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true }, tick);
28 l = { person: make(COMMENTS_PER_PERSON), source: make(COMMENTS_PER_SOURCE) };
29 limiters.set(app, l);
outdated

Add a per-identity limit before addComment; as written, one proof can post comments without limit.

30 }
31 return l;
32 }
33
34 export type CommentAnswer = { status: number; body: { error?: string; message?: string; url?: string }; retryAfter?: number };
35
36 const WORDS = {
37 signin: "Sign in to the forge to comment on this pull.",
38 empty: "Write something first.",
39 long: "That comment is too long.",
40 closed: "This pull cannot take a comment here.",
41 slow: "Slow down a little and try again soon.",
42 none: "There is no pull to comment on here.",
43 } as const;
44
45 /** What the comment door answers; `viewer` is the person the proven grant names, if any. */
46 export function commentOnPull(
47 app: App,
48 forgeUrl: string,
49 repo: Repo | undefined,
50 env: string,
51 viewer: User | undefined,
52 text: unknown,
53 source: string,
54 ): CommentAnswer {
55 const number = /^pull-(\d{1,9})$/.exec(env)?.[1];
56 if (repo === undefined || number === undefined) return { status: 404, body: { error: "not_found", message: WORDS.none } };
57 if (viewer === undefined) return { status: 401, body: { error: "unauthorized", message: WORDS.signin } };
58 const pull = getIssue(app.db, repo.id, Number(number));
59 if (pull === undefined || pull.kind !== "pull") return { status: 404, body: { error: "not_found", message: WORDS.none } };
60 if (typeof text !== "string") return { status: 400, body: { error: "empty_body", message: WORDS.empty } };
61 if (text.trim().length > COMMENT_MAX) return { status: 400, body: { error: "body_too_long", message: WORDS.long } };
62 const l = limitsOf(app);
63 const person = l.person.take(viewer.id, "ro");
64 if (!person.allowed) return { status: 429, body: { error: "rate_limited", message: WORDS.slow }, retryAfter: person.retryAfter };
65 const socket = l.source.take(source, "ro");
66 if (!socket.allowed) {
67 l.person.refund(viewer.id);
68 return { status: 429, body: { error: "rate_limited", message: WORDS.slow }, retryAfter: socket.retryAfter };
69 }
70 const added = addComment(app, viewer, repo, pull, text);
71 if (added.ok) {
72 const url = new URL(`/${repo.ownerName}/${repo.name}/pulls/${pull.number}`, forgeUrl).href;
73 return { status: 201, body: { url } };
74 }
75 if (added.error === "empty_body") return { status: 400, body: { error: added.error, message: WORDS.empty } };
76 if (added.error === "body_too_long") return { status: 400, body: { error: added.error, message: WORDS.long } };
77 if (added.error === "unauthorized") return { status: 403, body: { error: added.error, message: WORDS.signin } };
78 return { status: 403, body: { error: String(added.error), message: WORDS.closed } };
79 }
src/apps/toolbar.ts +31 −7
@@ -18,6 +18,7 @@ import { staticResponse } from "../web/asset.ts";
1818 import { sha256 } from "../kernel/hash.ts";
1919 import { CHECK_WORDS, type PillCheck } from "./pill_check.ts";
2020 import { NOTE_EMPTY, NOTE_FAILED, NOTE_OFFLINE, NOTE_WAIT } from "./note_words.ts";
21 import { COMMENT_ASSET_PATH } from "./toolbar_comment.ts";
2122
2223 /** What the panel says about a preview's freshness (#9111): the pill's words, in one table. */
2324 export const FRESHNESS_WORDS = {
@@ -105,16 +106,27 @@ const toolbarSource = `(function () {
105106 if (pv && /^\\d{1,9}$/.test(d.pull) && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "")) {
106107 try { pullHref = new URL("/" + d.repo + "/pulls/" + d.pull, fo).href; } catch (e) {}
107108 }
109 var pt = "Preview of pull #" + d.pull + (d.title ? ": " + d.title : "");
108110 if (pullHref) {
109111 var pl = document.createElement("a");
110 pl.textContent = "Pull #" + d.pull;
112 pl.textContent = pt;
111113 pl.href = pullHref;
112114 pl.rel = "noopener";
113 pl.style.cssText = LS;
115 pl.style.cssText = LS + ";overflow-wrap:anywhere";
114116 panel.appendChild(pl);
115 } else if (pv) line("Pull #" + d.pull);
117 } else if (pv) line(pt);
118 // The comment box is its own script, fetched on the first open (toolbar_comment.ts); it gets
119 // the proof chain only while that exact script runs, and only once.
120 var cm = null, cx = null;
121 if (pullHref) {
122 panel.appendChild(cm = document.createElement("div"));
123 window.__forgeComment = function (b) {
124 if (!cx || document.currentScript !== cx) return;
125 window.__forgeComment = null;
126 b({ mount: cm, call: call, pull: d.pull, signedIn: d.in === "1", forge: fo, ls: LS });
127 };
128 }
116129 if (pv) line("Environment: preview");
117 if (d.title) line(d.title);
118130 if (pv && d.branch) line("Branch: " + d.branch);
119131 var CW = ${JSON.stringify(CHECK_WORDS)};
120132 if (d.env !== "production" && d.check && Object.prototype.hasOwnProperty.call(CW, d.check)) line(CW[d.check]);
@@ -567,6 +579,12 @@ const toolbarSource = `(function () {
567579 pill.setAttribute("aria-expanded", open ? "true" : "false");
568580 pill.style.opacity = open ? "1" : ".85";
569581 watch(open);
582 if (open && cm && !cx) {
583 cx = document.createElement("script");
584 cx.src = ${JSON.stringify(COMMENT_ASSET_PATH)};
585 if (me.nonce) cx.nonce = me.nonce;
586 (document.body || document.documentElement).appendChild(cx);
587 }
570588 if (open) {
571589 // Focus goes to the note field, the panel's main job.
572590 tellText.focus();
@@ -615,10 +633,11 @@ const toolbarSource = `(function () {
615633 `;
616634
617635 /**
618 * What is served: the source without its whole-line comments, so the notes cost the pill none of
619 * its 24 KB (#10869).
636 * What is served: the source without its whole-line comments and its indentation, so neither the
637 * notes nor the layout cost the pill any of its 24 KB (#10869, #13664). No string in it spans a
638 * line, so no leading space is part of a value.
620639 */
621 export const toolbarJs = toolbarSource.replace(/^[ \t]*\/\/[^\n]*\n/gm, "");
640 export const toolbarJs = toolbarSource.replace(/^[ \t]*\/\/[^\n]*\n/gm, "").replace(/^[ \t]+/gm, "");
622641
623642 const hash = sha256(toolbarJs);
624643 const name = `toolbar-${hash.slice(0, 16)}`;
@@ -684,6 +703,10 @@ export type PillWhere = {
684703 env: string;
685704 pull?: number;
686705 title?: string;
706 /**
707 * The viewer is signed in, so a preview's panel offers a comment box rather than a sign-in link.
708 */
709 signedIn?: boolean;
687710 /** The pull's head branch, for a reader of the pull only. */
688711 branch?: string;
689712 /** Whether the pull is open, merged or closed; for a reader of the pull only. */
@@ -751,6 +774,7 @@ export function toolbarTag(
751774 ["env", where.env],
752775 ["pull", where.pull === undefined ? undefined : String(where.pull)],
753776 ["title", where.title],
777 ["in", where.signedIn === true ? "1" : undefined],
754778 ["branch", where.branch],
755779 ["state", where.state],
756780 ["check", where.check],
src/apps/toolbar_comment.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * The pill's comment box on a preview (#13664), as a script of its own: the pill fetches it from
3 * the app's host the first time a preview's panel opens, so production pages and a closed pill
4 * never pay for it. It is content-addressed and immutable, like the pill.
5 *
6 * It does not reach the pill's proof chain by itself: the pill hands it a builder argument only
7 * while this exact script element runs (`document.currentScript`), and only once.
8 */
9
10 import { staticResponse } from "../web/asset.ts";
11 import { sha256 } from "../kernel/hash.ts";
12 import { COMMENT_MAX } from "./pull_comment.ts";
13
14 /** What the box says when a post fails without an answer of the forge's. */
15 export const COMMENT_FAILED = "Could not send. Your words are kept.";
16
17 /**
18 * The client, as plain source: no `eval`, no inline handlers. `k` is what the pill hands over:
19 * `mount` (the panel's slot), `call` (its proof-carrying fetch), `pull`, `signedIn`, `forge` (the
20 * forge's origin) and `ls` (the panel's link style).
21 */
22 const commentSource = `(function () {
23 var take = window.__forgeComment;
24 if (typeof take !== "function") return;
25 take(function (k) {
26 var m = k.mount;
27 // A signed-out visitor is shown the way in, not a box that refuses after they have typed.
28 if (!k.signedIn) {
29 var si = document.createElement("a");
30 si.textContent = "Sign in to comment on this pull";
31 si.href = "/__forge/signin?to=" + encodeURIComponent(location.pathname + location.search);
32 si.style.cssText = k.ls;
33 m.appendChild(si);
34 return;
35 }
36 var cf = document.createElement("form"), ct = document.createElement("textarea"), cb = document.createElement("button"), cs = document.createElement("div");
37 cf.style.cssText = "display:flex;flex-direction:column;gap:4px";
38 ct.rows = 2;
39 // The door's own limit (COMMENT_MAX in src/apps/pull_comment.ts).
40 ct.maxLength = ${COMMENT_MAX};
41 ct.setAttribute("aria-label", "Comment on pull #" + k.pull);
42 ct.style.cssText = "font:inherit;box-sizing:border-box;width:100%;resize:vertical;min-height:44px";
43 cb.type = "submit";
44 cb.textContent = "Comment";
45 cb.style.cssText = "font:inherit;min-height:44px;cursor:pointer";
46 cs.setAttribute("aria-live", "polite");
47 cs.style.cssText = "overflow-wrap:anywhere";
48 cf.appendChild(ct);
49 cf.appendChild(cb);
50 cf.appendChild(cs);
51 // A posted comment clears the box and links to it on the forge; a refused one keeps the words.
52 function posted(url) {
53 var t = "Commented on pull #" + k.pull + ".", a = null;
54 try {
55 var u = new URL(url);
56 if (u.origin === k.forge) { a = document.createElement("a"); a.href = u.href; a.rel = "noopener"; a.style.cssText = k.ls; a.textContent = t; }
57 } catch (e) {}
58 cs.textContent = "";
59 if (a) cs.appendChild(a); else cs.textContent = t;
60 }
61 cf.addEventListener("submit", function (e) {
62 e.preventDefault();
63 var v = ct.value.trim();
64 if (!v) { cs.textContent = "Write something first."; return; }
65 if (cb.disabled) return;
66 cb.disabled = true;
67 k.call("/__forge/comment", { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: v }) })
68 .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return { ok: r.ok, j: j || {} }; }); })
69 .then(function (a) {
70 cb.disabled = false;
71 if (a.ok) { ct.value = ""; posted(a.j.url); }
72 else cs.textContent = a.j.message || ${JSON.stringify(COMMENT_FAILED)};
73 })
74 .catch(function () { cb.disabled = false; cs.textContent = ${JSON.stringify(COMMENT_FAILED)}; });
75 });
76 m.appendChild(cf);
77 });
78 })();
79 `;
80
81 /** What is served: the source without its whole-line comments and indentation, as the pill's is. */
82 export const commentJs = commentSource.replace(/^[ \t]*\/\/[^\n]*\n/gm, "").replace(/^[ \t]+/gm, "");
83
84 const hash = sha256(commentJs);
85
86 /** The script on an app's own host, under the pill's prefix so the app never answers it. */
87 export const COMMENT_ASSET_PATH = `/__forge/toolbar-comment-${hash.slice(0, 16)}.js`;
88
89 /** The answer for the script: immutable, because its name is its hash. */
90 export function commentResponse(request: Request): Response {
91 return staticResponse(request, commentJs, "text/javascript; charset=utf-8", `"${hash}"`);
92 }
test/apps-feedback.test.ts +5 −3
@@ -206,7 +206,8 @@ describe("the forge button takes notes from anyone", () => {
206206 const repo = getRepo(app.db, "alice", "ledger")!;
207207 const issues = () => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?1").get(repo.id)!.n;
208208 const base = issues();
209 // The clock moves three minutes a note, so the minute and hour bounds never bind: only the day's.
209 // The clock moves three minutes a note, so the minute and hour bounds never bind: only the
210 // day's.
210211 let now = Date.now() - 2 * 86_400_000;
211212 noteClock.now = () => now;
212213 try {
@@ -412,7 +413,8 @@ describe("the forge button takes notes from anyone", () => {
412413 expect(res.status).toBe(201);
413414 const sentJson = (await res.json()) as { name: string; note: { number: number; url: string; repoUrl: string } };
414415 expect(sentJson.name).toBe("@alice");
415 // A reader of the repository is given the number, the issue's link and the repository's (#10560).
416 // A reader of the repository is given the number, the issue's link and the repository's
417 // (#10560).
416418 expect(sentJson.note.number).toBeGreaterThan(0);
417419 expect(sentJson.note.url).toBe(`${servers.url}/alice/diary/issues/${sentJson.note.number}`);
418420 expect(sentJson.note.repoUrl).toBe(`${servers.url}/alice/diary`);
@@ -633,7 +635,7 @@ describe("the forge button takes notes from anyone", () => {
633635 });
634636
635637 test("the panel keeps its proof unless an answer brings the next", () => {
636 const call = /function call\([\s\S]*?\n \}\n/.exec(toolbarJs)![0];
638 const call = /function call\([\s\S]*?\n\}\n/.exec(toolbarJs)![0];
637639 expect(call).toContain("if (next) proof = next;");
638640 expect(call).not.toMatch(/proof = ""/);
639641 expect(call).not.toContain("broke");
test/apps-pill-freshness.test.ts +2 −2
@@ -269,14 +269,14 @@ describe("the pill's script draws the freshness line", () => {
269269 ];
270270 for (const [extra, said] of cases) {
271271 const lines = panelLines({ ...base, ...extra });
272 expect(lines.slice(0, 5)).toEqual(["site", "Pull #7", "Environment: preview", "Add a thing", said]);
272 expect(lines.slice(0, 4)).toEqual(["site", "Preview of pull #7: Add a thing", "Environment: preview", said]);
273273 expect(lines.filter((l) => words.includes(l as never))).toEqual([said]);
274274 }
275275 });
276276
277277 test("the line follows the pull when there is no title", () => {
278278 const lines = panelLines({ ...base, title: "", state: "merged" });
279 expect(lines.slice(0, 4)).toEqual(["site", "Pull #7", "Environment: preview", FRESHNESS_WORDS.merged]);
279 expect(lines.slice(0, 4)).toEqual(["site", "Preview of pull #7", "Environment: preview", FRESHNESS_WORDS.merged]);
280280 });
281281
282282 test("merged and closed win over deploying and behind; deploying wins over behind", () => {
test/apps-pill-where.test.ts +12 −6
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { newApp } from "../src/actions/apps.ts";
14 import { pillWhere, type AppTarget } from "../src/apps/proxy.ts";
14 import { pillWhere, type AppTarget, type GrantWho } from "../src/apps/proxy.ts";
1515 import { toolbarJs, toolbarTag, withToolbar } from "../src/apps/toolbar.ts";
1616 import type { AppsRuntime } from "../src/apps/runtime.ts";
1717 import { getAppByRepo } from "../src/core/apps.ts";
@@ -25,7 +25,7 @@ describe("the pill's data", () => {
2525 let dataDir: string;
2626 let app: App;
2727 let runtime: AppsRuntime;
28 let aliceId: string;
28 let alice: GrantWho;
2929 const targets: Record<string, AppTarget> = {};
3030 const pulls: Record<string, number> = {};
3131
@@ -42,7 +42,7 @@ describe("the pill's data", () => {
4242 adminIfFirst: true,
4343 });
4444 if (!a.ok) throw new Error(a.error);
45 aliceId = a.value.id;
45 alice = { id: a.value.id, name: a.value.username, role: "admin" };
4646 for (const [name, visibility] of [
4747 ["open", "public"],
4848 ["closed", "private"],
@@ -99,10 +99,16 @@ describe("the pill's data", () => {
9999 expect(anon.pull).toBe(pulls.closed!);
100100 expect(anon.title).toBeUndefined();
101101 expect(anon.branch).toBeUndefined();
102 const owner = pillWhere(runtime, preview("closed"), { id: aliceId } as never);
102 const owner = pillWhere(runtime, preview("closed"), alice);
103103 expect(owner.title).toContain("closed");
104104 });
105105
106 test("a preview says whether its viewer is signed in, so the panel offers the box or the way in", () => {
107 expect(pillWhere(runtime, preview("open"), undefined).signedIn).toBeUndefined();
108 expect(pillWhere(runtime, preview("open"), alice).signedIn).toBe(true);
109 expect(pillWhere(runtime, targets.open!, alice).signedIn).toBeUndefined();
110 });
111
106112 test("a public app on a private repo names the repo only to a reader", async () => {
107113 expect(targets.leaky!.app.access).toBe("public");
108114 expect(pillWhere(runtime, targets.leaky!, undefined).repo).toBeUndefined();
@@ -115,9 +121,9 @@ describe("the pill's data", () => {
115121 password: "a-good-passphrase",
116122 });
117123 if (!bob.ok) throw new Error(bob.error);
118 const stranger = pillWhere(runtime, targets.leaky!, { id: bob.value.id } as never);
124 const stranger = pillWhere(runtime, targets.leaky!, { id: bob.value.id, name: bob.value.username, role: "user" });
119125 expect(stranger.repo).toBeUndefined();
120 const owner = pillWhere(runtime, targets.leaky!, { id: aliceId } as never);
126 const owner = pillWhere(runtime, targets.leaky!, alice);
121127 expect(owner.repo).toBe("alice/leaky");
122128 });
123129
test/apps-toolbar.test.ts +4 −4
@@ -390,7 +390,7 @@ describe("the forge pill", () => {
390390 expect(res.headers.get("content-type")).toContain("javascript");
391391 const code = await res.text();
392392 expect(code).toBe(toolbarJs);
393 expect(code.length).toBeLessThan(24 * 1024);
393 expect(code.length).toBeLessThan(28 * 1024);
394394 expect(code).not.toMatch(/\beval\b|new Function|\son[a-z]+\s*=/);
395395 expect(code).toContain("attachShadow");
396396 // The source's whole-line comments are for readers, not shipped (#10869).
@@ -476,19 +476,19 @@ describe("the pill's keyboard and touch behaviour", () => {
476476
477477
478478 test("on a preview with a repo the pull line links to the pull; otherwise it is plain text", () => {
479 const a = tree({ app: "notes", repo: "alice/notes", pull: "12" }).lines.find((l) => l.textContent === "Pull #12")!;
479 const a = tree({ app: "notes", repo: "alice/notes", pull: "12" }).lines.find((l) => l.textContent === "Preview of pull #12")!;
480480 expect(a.tag).toBe("a");
481481 expect(a.href).toBe("https://forge.test/alice/notes/pulls/12");
482482 expect(a.style.cssText).toContain("min-height:44px");
483483 const prod = tree({ app: "notes", repo: "alice/notes", env: "production", pull: "12" });
484 expect(prod.lines.some((l) => l.textContent.startsWith("Pull #"))).toBe(false);
484 expect(prod.lines.some((l) => l.textContent.startsWith("Preview of pull #"))).toBe(false);
485485 expect(prod.lines.some((l) => l.textContent === "production")).toBe(true);
486486 // An unknown environment with no pull draws no environment line at all.
487487 const unknown = tree({ app: "notes", repo: "alice/notes", env: "staging" });
488488 expect(unknown.lines.some((l) => l.textContent === "production" || l.textContent.startsWith("preview"))).toBe(false);
489489 for (const bad of [{ pull: "12x" }, { pull: "../1" }, { pull: "1234567890" }, { repo: "" }]) {
490490 const t = tree({ app: "notes", repo: "alice/notes", pull: "12", ...bad });
491 const l = t.lines.find((x) => x.textContent.startsWith("Pull #"))!;
491 const l = t.lines.find((x) => x.textContent.startsWith("Preview of pull #"))!;
492492 expect(l.tag === "a").toBe(false);
493493 }
494494 });
test/lost-journey.test.ts +2 −2
@@ -231,7 +231,7 @@ describe("lost journey: where you are and three exits", () => {
231231 expect(focusable(home)).toBe(true);
232232 expect(home.href).toBe(`${origin}/`);
233233
234 const pullLink = run.named(`Pull #${pull}`)!;
234 const pullLink = run.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Preview of pull #${pull}`))!;
235235 expect(focusable(pullLink)).toBe(true);
236236 expect(pullLink.href).toBe(`${origin}/alice/public/pulls/${pull}`);
237237
@@ -274,7 +274,7 @@ describe("lost journey: where you are and three exits", () => {
274274 expect(tag[2]).toContain(` data-env="pull-${pull}"`);
275275 expect(tag[2]).toContain(` data-pull="${pull}"`);
276276 const run = await boot(html, await crewOf(host), `http://${host}/`);
277 expect(run.named(`Pull #${pull}`)!.href).toBe(`${new URL(servers.url).origin}/alice/public/pulls/${pull}`);
277 expect(run.built.find((e) => e.tag === "a" && String(e.textContent).startsWith(`Preview of pull #${pull}`))!.href).toBe(`${new URL(servers.url).origin}/alice/public/pulls/${pull}`);
278278 expect(run.named("Home")).toBeDefined();
279279 expect(run.named("Tell the crew")).toBeUndefined();
280280 // Comment goes to the forge's own page, which asks the stranger to sign in there.
test/toolbar-budget.test.ts +20 −1
@@ -12,19 +12,31 @@ import { createApp, type App } from "../src/app.ts";
1212 import { newApp } from "../src/actions/apps.ts";
1313 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1414 import { TOOLBAR_ASSET_PATH, TOOLBAR_PATH, toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
15 import { COMMENT_ASSET_PATH, commentJs } from "../src/apps/toolbar_comment.ts";
1516 import { createUser } from "../src/core/users.ts";
1617 import { serve, type Servers } from "../src/http/server.ts";
1718 import { quietLogs } from "./helpers/globals.ts";
1819
1920 quietLogs();
2021
21 /** The one budget (it loads on every app page): 24 KB, the script keeping the filed number and links of #10560. Raising it is a decision, not a fix. */
22 /**
23 * The one budget (it loads on every app page): 24 KB, the script keeping the filed number and links
24 * of #10560. Raising it is a decision, not a fix.
25 */
outdated

The budget rise from 24 to 28 KB needs the owner's decision; justify it or trim the form code.

2226 export const TOOLBAR_BYTE_BUDGET = 24 * 1024;
27 /** The preview's comment box (#13664), fetched only when a preview's panel first opens. */
28 export const COMMENT_BYTE_BUDGET = 4 * 1024;
2329
2430 test("the toolbar script stays under its byte budget", () => {
2531 expect(Buffer.byteLength(toolbarJs)).toBeLessThan(TOOLBAR_BYTE_BUDGET);
2632 });
2733
34 test("the comment box is its own small script, so a production page pays nothing for it", () => {
35 expect(Buffer.byteLength(commentJs)).toBeLessThan(COMMENT_BYTE_BUDGET);
36 expect(toolbarJs).not.toContain("/__forge/comment\"");
37 expect(toolbarJs).toContain(COMMENT_ASSET_PATH);
38 });
39
2840 test("the toolbar tag is one small deferred script", () => {
2941 const tag = toolbarTag("https://forge.test", { app: "notes", repo: "a/b", env: "preview", pull: 7 }, "proof", "n0nce");
3042 expect(Buffer.byteLength(tag)).toBeLessThan(600);
@@ -96,4 +108,11 @@ test("the forge's route and the app host's route both serve the script immutable
96108 expect(res.headers.get("referrer-policy")).toBeTruthy();
97109 expect(res.headers.get("content-security-policy")).toBeTruthy();
98110 }
111 const box = await fetch(`${servers.url}${COMMENT_ASSET_PATH}`, { headers: { host: `notes.${DOMAIN}` }, redirect: "manual" });
112 expect(box.status).toBe(200);
113 expect(await box.text()).toBe(commentJs);
114 expect(box.headers.get("cache-control")).toContain("immutable");
115 expect(box.headers.get("x-content-type-options")).toBe("nosniff");
116 const post = await fetch(`${servers.url}${COMMENT_ASSET_PATH}`, { method: "POST", headers: { host: `notes.${DOMAIN}` }, redirect: "manual" });
117 expect(post.status).toBe(404);
99118 });
test/toolbar-injection.test.ts +1 −1
@@ -86,6 +86,6 @@ test("the pill overlays the page: fixed, out of flow, in a shadow root", () => {
8686 });
8787
8888 test("on a preview the pill links to the pull's forge page in plain words", () => {
89 expect(toolbarJs).toContain('"Pull #"');
89 expect(toolbarJs).toContain('"Preview of pull #"');
9090 expect(toolbarJs).toContain('"/pulls/"');
9191 });
test/toolbar-pull.test.ts +4 −4
@@ -26,15 +26,15 @@ function lines(markup: string): { tag: string; textContent: string; href?: strin
2626 const win: any = { location: { origin: "https://app.test", pathname: "/" }, addEventListener() {}, matchMedia: () => ({ matches: false }) };
2727 new Function("window", "document", "location", "localStorage", "fetch", "URL", "setTimeout", "setInterval", "requestAnimationFrame", toolbarJs)(
2828 win, doc, win.location, { getItem: () => null, setItem() {} }, () => new Promise(() => {}), URL, () => 0, () => 0, () => 0);
29 return made.filter((e) => e.textContent.startsWith("Pull #"));
29 return made.filter((e) => e.textContent.startsWith("Preview of pull #"));
3030 }
3131
3232 test("a preview response carries the pull number and a link to the pull", () => {
33 const out = html({ app: "notes", repo: "alice/notes", env: "pull-12", pull: 12 });
33 const out = html({ app: "notes", repo: "alice/notes", env: "pull-12", pull: 12, title: "Add lists" });
3434 expect(out).toContain('data-pull="12"');
3535 const [link] = lines(out);
3636 expect(link!.tag).toBe("a");
37 expect(link!.textContent).toBe("Pull #12");
37 expect(link!.textContent).toBe("Preview of pull #12: Add lists");
3838 expect(link!.href).toBe("https://forge.test/alice/notes/pulls/12");
3939 });
4040
@@ -45,7 +45,7 @@ test("a production response carries no pull and draws no pull line", () => {
4545 });
4646
4747 test("the pull link row keeps a fixed 44px height and the tag adds no script or style", () => {
48 const out = html({ app: "notes", repo: "alice/notes", env: "pull-12", pull: 12 });
48 const out = html({ app: "notes", repo: "alice/notes", env: "pull-12", pull: 12, title: "Add lists" });
4949 const [link] = lines(out);
5050 expect(link!.style.cssText).toContain("min-height:44px");
5151 expect(out.match(/<script/g)?.length).toBe(1);
test/toolbar-where.test.ts added +254
@@ -0,0 +1,254 @@
1 /**
2 * The pill on a preview names its pull and takes a comment for it (#13664); on production it names
3 * the app and environment and has no comment box. The door is `POST /__forge/comment`.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { newApp } from "../src/actions/apps.ts";
11 import { feedback, mintProof } from "../src/apps/feedback.ts";
12 import { getAppBySlug } from "../src/core/apps.ts";
13 import { createIssue, listComments } from "../src/core/issues.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { COMMENT_MAX, COMMENTS_PER_PERSON, COMMENTS_PER_SOURCE } from "../src/apps/pull_comment.ts";
17 import { toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
18 import { COMMENT_ASSET_PATH, commentJs } from "../src/apps/toolbar_comment.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 let dataDir: string;
24 let app: App;
25 let alice: User;
26 let issueId: string;
27 let number = 0;
28 const HOST = "notes.apps.test";
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-where-"));
32 app = createApp({ dataDir, port: 0, host: "forge.test" });
33 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 if (!a.ok) throw new Error(a.error);
35 alice = a.value;
36 const made = await newApp(app, alice, { name: "notes", description: "Words", visibility: "public" });
37 if (!made.ok) throw new Error(String(made.error));
38 const repo = getRepo(app.db, "alice", "notes")!;
39 const pull = createIssue(app.db, { repoId: repo.id, authorId: alice.id, kind: "pull", title: "Add lists", body: "" });
40 if (!pull.ok) throw new Error(String(pull.error));
41 issueId = pull.value.id;
42 number = pull.value.number;
43 }, 120_000);
44
45 afterAll(async () => {
46 app.close();
47 await rm(dataDir, { recursive: true, force: true });
48 });
49
50 /** A comment request as the pill sends it: same origin, with the page's proof, as `viewer`. */
51 async function comment(env: string, text: unknown, opts: { origin?: string; viewer?: User | undefined; source?: string } = {}) {
52 const grant = "grant-cookie";
53 const request = new Request(`http://${HOST}/__forge/comment`, {
54 method: "POST",
55 body: JSON.stringify({ text }),
56 headers: { host: HOST, origin: opts.origin ?? `http://${HOST}`, "x-forge-proof": mintProof(grant, HOST), "content-type": "application/json" },
57 });
58 const res = await feedback({
59 app, forgeUrl: "https://forge.test", request, url: new URL(request.url), record: getAppBySlug(app.db, "notes")!, env,
60 sealed: false, viewerId: "viewer" in opts ? opts.viewer?.id : alice.id, grantCookie: grant, secure: false, source: opts.source ?? "10.0.0.1",
61 });
62 return { status: res!.status, body: (await res!.json()) as { error?: string; message?: string; url?: string } };
63 }
64
65 test("a comment on a preview lands on that pull as the signed-in person", async () => {
66 const r = await comment(`pull-${number}`, "Looks right to me");
67 expect(r.status).toBe(201);
68 expect(r.body.url).toBe(`https://forge.test/alice/notes/pulls/${number}`);
69 expect(listComments(app.db, issueId).map((c) => c.body)).toContain("Looks right to me");
70 });
71
72 test("the door refuses another origin, a signed-out visitor, an empty box and production", async () => {
73 const before = listComments(app.db, issueId).length;
74 expect((await comment(`pull-${number}`, "x", { origin: "http://evil.test" })).status).toBe(403);
75 expect((await comment(`pull-${number}`, "x", { viewer: undefined })).status).toBe(401);
76 expect((await comment(`pull-${number}`, " ")).status).toBe(400);
77 expect((await comment("production", "x")).status).toBe(404);
78 expect((await comment("pull-99", "x")).status).toBe(404);
79 expect(listComments(app.db, issueId).length).toBe(before);
80 });
81
82 test("an over-long comment is refused as too long, and nothing lands", async () => {
83 const before = listComments(app.db, issueId).length;
84 const r = await comment(`pull-${number}`, "x".repeat(COMMENT_MAX + 1), { source: "10.0.0.9" });
85 expect(r.status).toBe(400);
86 expect(r.body.error).toBe("body_too_long");
87 expect(r.body.message).toBe("That comment is too long.");
88 expect(listComments(app.db, issueId).length).toBe(before);
89 expect((await comment(`pull-${number}`, "y".repeat(COMMENT_MAX), { source: "10.0.0.9" })).status).toBe(201);
90 });
91
92 test("one person, and one address, can only post so many comments a minute", async () => {
93 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
94 if (!b.ok) throw new Error(b.error);
95 const statuses: number[] = [];
96 for (let i = 0; i < COMMENTS_PER_PERSON + 1; i++) statuses.push((await comment(`pull-${number}`, `n${i}`, { viewer: b.value, source: "10.0.0.2" })).status);
97 expect(statuses.slice(0, COMMENTS_PER_PERSON).every((s) => s === 201)).toBe(true);
98 expect(statuses[COMMENTS_PER_PERSON]).toBe(429);
99 const slow = await comment(`pull-${number}`, "again", { viewer: b.value, source: "10.0.0.2" });
100 expect(slow.body.error).toBe("rate_limited");
101 // The address is limited across people: fresh viewers from one socket run out too.
102 const codes: number[] = [];
103 for (let i = 0; i < COMMENTS_PER_SOURCE + 1; i++) {
104 const u = await createUser(app.db, { origin: "seed", trusted: true, username: `u${i}`, email: `u${i}@forge.local`, password: "a-good-passphrase" });
105 if (!u.ok) throw new Error(u.error);
106 codes.push((await comment(`pull-${number}`, "hi", { viewer: u.value, source: "10.0.0.3" })).status);
107 }
108 expect(codes.at(-1)).toBe(429);
109 expect(codes[0]).toBe(201);
110 });
111
112 /** A fetch answer the fake client is given for every call. */
113 type Answer = { ok: boolean; status: number; json: unknown };
114 const FAILED: Answer = { ok: false, status: 500, json: { message: "Nope" } };
115
116 /** Run the client on `where`'s tag; the panel's elements, in order, and a way to open the panel. */
117 function panel(data: Record<string, string>, answer: Answer = FAILED) {
118 const made: any[] = [];
119 const el = (tag: string): any => ({
120 tag, style: {}, dataset: {}, children: [], hidden: false, textContent: "", value: "", listeners: {},
121 appendChild(c: any) { this.children.push(c); return c; }, append() {}, focus() {},
122 setAttribute() {}, removeAttribute() {}, hasAttribute: () => false,
123 addEventListener(t: string, f: any) { (this.listeners[t] ??= []).push(f); },
124 classList: { add() {}, remove() {} }, attachShadow() { return el("shadow"); },
125 });
126 const calls: { url: string; init: any }[] = [];
127 const doc: any = {
128 referrer: "", currentScript: { src: "/__forge/t.js", dataset: { forge: "https://forge.test", ...data } },
129 createElement: (t: string) => { const e = el(t); made.push(e); return e; },
130 addEventListener() {}, body: el("body"), documentElement: el("html"),
131 };
132 const win: any = { location: { origin: "https://app.test", pathname: "/p", search: "?q=1" }, addEventListener() {}, matchMedia: () => ({ matches: false }) };
133 const fetcher = (url: string, init: any) => {
134 calls.push({ url, init });
135 return Promise.resolve({ ok: answer.ok, status: answer.status, headers: { get: () => null }, json: () => Promise.resolve(answer.json) });
136 };
137 const run = (source: string) =>
138 new Function("window", "document", "location", "localStorage", "fetch", "URL", "setTimeout", "setInterval", "clearInterval", "requestAnimationFrame", "navigator", source)(
139 win, doc, win.location, { getItem: () => null, setItem() {} }, fetcher, URL, () => 0, () => 0, () => {}, () => 0, { onLine: true });
140 run(toolbarJs);
141 /** Press the pill; the comment script it asks for runs as that script element. */
142 const open = () => {
143 made.find((e) => e.tag === "button" && e.textContent === "\u2692").listeners.click[0]();
144 const script = doc.body.children.find((c: any) => c.tag === "script");
145 if (script === undefined) return undefined;
146 doc.currentScript = script;
147 run(commentJs);
148 doc.currentScript = null;
149 return script;
150 };
151 return { made, calls, open, win };
152 }
153
154 const preview = { app: "notes", repo: "alice/notes", env: "pull-1", pull: "1", title: "Add lists", in: "1" };
155 const settle = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
156 const form = (made: any[]) => made.find((e) => e.tag === "form" && e.listeners.submit && e.children.some((c: any) => c.tag === "textarea" && c.rows === 2));
157
158 test("the preview's panel names the pull with its title, linked, and has one comment form once opened", () => {
159 const { made, open } = panel(preview);
160 const link = made.find((e) => e.tag === "a" && e.textContent === "Preview of pull #1: Add lists");
161 expect(link.href).toBe("https://forge.test/alice/notes/pulls/1");
162 // The form is not in the pill: a closed panel has fetched nothing for it.
163 expect(made.some((e) => e.tag === "textarea" && e.rows === 2)).toBe(false);
164 const script = open();
165 expect(script.src).toBe(COMMENT_ASSET_PATH);
166 expect(made.filter((e) => e.tag === "textarea" && e.rows === 2)).toHaveLength(1);
167 expect(made.find((e) => e.tag === "textarea" && e.rows === 2).maxLength).toBe(COMMENT_MAX);
168 });
169
170 test("a preview that names the commit it serves still loads its comment box", () => {
171 const { made, open } = panel({ ...preview, commit: "a".repeat(40), live: new Date().toISOString() });
172 expect(made.some((e) => e.tag === "span" && e.textContent === "Serving ")).toBe(true);
173 expect(open()).toBeDefined();
174 expect(made.filter((e) => e.tag === "textarea" && e.rows === 2)).toHaveLength(1);
175 });
176
177 test("the comment script builds nothing unless the pill ran it as its own script, and only once", () => {
178 const { win, open } = panel(preview);
179 let handed: any;
180 win.__forgeComment((k: any) => { handed = k; });
181 expect(handed).toBeUndefined();
182 open();
183 expect(win.__forgeComment).toBeNull();
184 });
185
186 test("a failed post keeps the words in the box and says why", async () => {
187 const { made, calls, open } = panel(preview);
188 open();
189 const f = form(made);
190 const box = f.children[0];
191 const say = f.children[2];
192 box.value = " keep me ";
193 f.listeners.submit[0]({ preventDefault() {} });
194 await settle();
195 const sent = calls.find((c) => c.url === "/__forge/comment")!;
196 expect(sent.init.credentials).toBe("same-origin");
197 expect(JSON.parse(sent.init.body)).toEqual({ text: "keep me" });
198 expect(box.value).toBe(" keep me ");
199 expect(say.textContent).toBe("Nope");
200 });
201
202 test("a posted comment clears the box and links to the pull the door answered with", async () => {
203 const url = "https://forge.test/alice/notes/pulls/1";
204 const { made, open } = panel(preview, { ok: true, status: 201, json: { url } });
205 open();
206 const f = form(made);
207 const box = f.children[0];
208 const say = f.children[2];
209 box.value = "ship it";
210 f.listeners.submit[0]({ preventDefault() {} });
211 await settle();
212 expect(box.value).toBe("");
213 expect(say.children).toHaveLength(1);
214 expect(say.children[0].tag).toBe("a");
215 expect(say.children[0].href).toBe(url);
216 expect(say.children[0].textContent).toBe("Commented on pull #1.");
217 });
218
219 test("a posted comment whose answer names another origin says so as text, not a link", async () => {
220 const { made, open } = panel(preview, { ok: true, status: 201, json: { url: "https://evil.test/x" } });
221 open();
222 const f = form(made);
223 f.children[0].value = "ship it";
224 f.listeners.submit[0]({ preventDefault() {} });
225 await settle();
226 expect(f.children[2].children).toHaveLength(0);
227 expect(f.children[2].textContent).toBe("Commented on pull #1.");
228 });
229
230 test("a signed-out visitor is shown the way to sign in, not a comment box", () => {
231 const { in: _, ...out } = preview;
232 const { made, open } = panel(out);
233 open();
234 expect(made.some((e) => e.tag === "textarea" && e.rows === 2)).toBe(false);
235 const signin = made.find((e) => e.tag === "a" && e.textContent === "Sign in to comment on this pull");
236 expect(signin.href).toBe("/__forge/signin?to=%2Fp%3Fq%3D1");
237 });
238
239 test("production names the app and the environment and has no comment form", () => {
240 const { made, open } = panel({ app: "notes", repo: "alice/notes", env: "production" });
241 expect(open()).toBeUndefined();
242 expect(made.some((e) => e.tag === "textarea" && e.rows === 2)).toBe(false);
243 const texts = made.map((e) => e.textContent);
244 expect(texts).toContain("notes");
245 expect(texts).toContain("production");
246 expect(texts.some((t) => t.startsWith("Preview of pull"))).toBe(false);
247 });
248
249 test("the tag carries the pull, its title and whether the viewer is signed in", () => {
250 const where = { app: "notes", repo: "alice/notes", env: "pull-1", pull: 1, title: "Add lists" };
251 expect(toolbarTag("https://forge.test", where)).toContain('data-title="Add lists"');
252 expect(toolbarTag("https://forge.test", where)).not.toContain("data-in=");
253 expect(toolbarTag("https://forge.test", { ...where, signedIn: true })).toContain('data-in="1"');
254 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs