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

Every forge page carries og:title, og:description, og:image and twitter:card, and a private page reveals only its title and 'private' #2476

Parked opened this
Closed without merging

scout/forge:scout/2349-every-forge-page-carries-og-title-og-des → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +303 −28
README.md +11 −3
@@ -1031,9 +1031,17 @@ Two of them carry a figure beside the words:
10311031 50%), with the top three findings worst first. Public repositories' apps only,
10321032 as `/audit` shows them signed out.
10331033
1034 The map page (public repositories) and `/audit` name their `.png` as
1035 `og:image` with `twitter:card=summary_large_image`; every other page keeps the
1036 forge icon.
1034 Every page carries `og:title`, `og:description`, an `og:image` that answers
1035 200 `image/png`, and `twitter:card=summary_large_image`
1036 (`test/og-every-page.test.ts` walks them). A page names its own card
1037 (repository, issue, pull, run, app, map, audit) through `cardLink` in
1038 `src/web/og/link.ts`, which applies the card route's own test: only what a
1039 signed-out reader may open. Anything else (a private repository, a sealed
1040 report, a hidden run log, a private app, the person page and every top-level
1041 page) gets the site card, `/og/site.png`. A signed-in reader of a private
1042 repository gets the title, `Private.` and the site card. A signed-out reader
1043 gets the same 404 and tags as for a repository that does not exist, so a
1044 guess never confirms one.
10371045
10381046 ## Develop
10391047
src/http/server.ts +2
@@ -1164,6 +1164,8 @@ export function buildRouter(): Router<Handler> {
11641164 router.add("GET", "/og/pull/:ref.svg", ogCard("pull"));
11651165 router.add("GET", "/og/run/:ref.svg", ogCard("run"));
11661166 router.add("GET", "/og/map/:ref.svg", ogCard("map"));
1167 router.add("GET", "/og/site.svg", ogCard("site"));
1168 router.add("GET", "/og/site.png", ogCard("site", "png"));
11671169 router.add("GET", "/og/audit.svg", ogCard("audit"));
11681170 router.add("GET", "/og/repo/:ref.png", ogCard("repo", "png"));
11691171 router.add("GET", "/og/app/:ref.png", ogCard("app", "png"));
src/web/describe.ts +6
@@ -57,6 +57,12 @@ export function runLine(o: {
5757 return say(`${o.word}${at}`, firstLine(o.summary));
5858 }
5959
60 /** A repository: its own description, or "Private." for a private one. */
61 export function repoLine(o: { private: boolean; description: string }): string {
62 if (o.private) return PRIVATE_LINE;
63 return firstLine(o.description);
64 }
65
6066 /** A person or an organization, by what is public about them. */
6167 export function ownerLine(o: {
6268 org: boolean;
src/web/layout.ts +6 −6
@@ -37,6 +37,7 @@ import { prefersJson } from "./form.ts";
3737 import { html, raw, when, type Html } from "./html.ts";
3838 import { noRoom } from "../spawn/door.ts";
3939 import { icon, iconSprite, inlineIcons, themeGlyph } from "./icons.ts";
40 import { SITE_CARD, SITE_LINE } from "./og/link.ts";
4041 import { btn, kbd, menu, pill, type MenuItem } from "./ui.ts";
4142
4243 /** One row of the command palette: title, href, category. */
@@ -529,7 +530,10 @@ function footer(ctx: Ctx): Html {
529530
530531 // ---- the page ----
531532
532 const SITE_LINE = "Your code, your machine.";
533 /** The page's own card when it names one of ours, else the site's. */
534 function cardPath(own: string | undefined): string {
535 return own !== undefined && own.startsWith("/og/") ? own : SITE_CARD;
536 }
533537
534538 function pageDescription(options: PageOptions): string {
535539 const own = options.description?.trim().split(/\r?\n/)[0]?.trim() ?? "";
@@ -607,11 +611,7 @@ export function page(options: PageOptions, status = 200): Response {
607611 }
608612 <meta
609613 property="og:image"
610 content="${ctx.url.origin}${
611 options.ogImage !== undefined && options.ogImage.startsWith("/og/")
612 ? options.ogImage
613 : "/og/site.png"
614 }"
614 content="${ctx.url.origin}${cardPath(options.ogImage)}"
615615 />
616616 <meta property="og:image:width" content="1200" />
617617 <meta property="og:image:height" content="630" />
src/web/pages/og.ts +8 −9
@@ -43,6 +43,7 @@ import { isSafeName } from "../../git/guard.ts";
4343 import type { Ctx } from "../../http/context.ts";
4444 import { notFound } from "../../http/respond.ts";
4545 import { auditInput, type AuditRow } from "../og/audit.ts";
46 import { SITE_LINE } from "../og/link.ts";
4647 import { renderCard, signature, type CardInput } from "../og/card.ts";
4748 import { appImages, embedShots, pullImages } from "../og/looks.ts";
4849 import { mapInput } from "../og/map.ts";
@@ -147,14 +148,7 @@ function waiting(ctx: Ctx, repo: Repo, issue: Issue): string {
147148 return `waits on ${shown.join(", ")}${more > 0 ? ` +${more}` : ""}`;
148149 }
149150
150 export type OgKind = "repo" | "app" | "issue" | "pull" | "run" | "map" | "audit" | "site";
151
152 /** The card for any page without a card of its own: it says only what the forge is. */
153 const SITE_CARD: CardInput = {
154 kind: "page",
155 title: "forge",
156 lines: ["Repositories, issues, pulls and the crew that works them."],
157 };
151 export type OgKind = "site" | "repo" | "app" | "issue" | "pull" | "run" | "map" | "audit";
158152
159153 /** The audit page's own bound. */
160154 const AUDIT_LIMIT = 200;
@@ -321,6 +315,11 @@ async function auditCardInput(ctx: Ctx): Promise<CardInput> {
321315 return auditInput(rows);
322316 }
323317
318 /** The card for any page that has none of its own: the forge, in a line. */
319 function siteInput(): CardInput {
320 return { kind: "page", title: "forge", lines: [SITE_LINE] };
321 }
322
324323 /**
325324 * A repository's card. The public repo, or one the signed-in viewer may read,
326325 * gets the full card; any other well-formed ref gets a card of its title and
@@ -351,8 +350,8 @@ async function resolve(ctx: Ctx, kind: OgKind, ref: string): Promise<CardInput |
351350 if (kind === "issue" || kind === "pull") return threadInput(ctx, kind, ref);
352351 if (kind === "run") return runInput(ctx, ref);
353352 if (kind === "map") return mapCardInput(ctx, ref);
353 if (kind === "site") return ref === "" ? siteInput() : undefined;
354354 if (kind === "audit") return ref === "" ? auditCardInput(ctx) : undefined;
355 if (kind === "site") return ref === "" ? SITE_CARD : undefined;
356355 if (kind === "repo") return repoCard(ctx, ref);
357356 if (!isSlug(ref)) return undefined;
358357 const record = getAppBySlug(db, ref);
src/web/pages/repo.ts +6 −4
@@ -86,6 +86,8 @@ import {
8686 finderDialog,
8787 loadExplorer,
8888 } from "./explorer.ts";
89 import { cardLink } from "../og/link.ts";
90 import { repoLine } from "../describe.ts";
8991
9092 export { crumbsFor, loadRepo, repoBase };
9193 export { pathCrumbs, refMenu, refSet, refSetFrom } from "./refs.ts";
@@ -988,8 +990,8 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
988990 return page({
989991 ctx,
990992 title: repo.name,
991 description: repo.description,
992 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
993 description: repoLine({ private: repo.visibility === "private", description: repo.description }),
994 ogImage: cardLink(ctx, { kind: "repo", repo }),
993995 feed: {
994996 href: `${repoBase(repo)}/activity.atom`,
995997 title: `${repo.ownerName}/${repo.name} activity`,
@@ -1036,8 +1038,8 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
10361038 return page({
10371039 ctx,
10381040 title: repo.name,
1039 description: repo.description,
1040 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
1041 description: repoLine({ private: repo.visibility === "private", description: repo.description }),
1042 ogImage: cardLink(ctx, { kind: "repo", repo }),
10411043 feed: {
10421044 href: `${repoBase(repo)}/activity.atom`,
10431045 title: `${repo.ownerName}/${repo.name} activity`,
src/web/studio/app.ts +2
@@ -56,6 +56,7 @@ import { appPanels } from "./previews.ts";
5656 import { noCrewLine, servingHistory, type WordCtx } from "./words.ts";
5757 import { crewKeyNote } from "./crew.ts";
5858 import { noteAppOpened } from "../../core/next-steps.ts";
59 import { cardLink } from "../og/link.ts";
5960
6061 /**
6162 * What asks the viewer in this repository, muted or not: a mute quiets the
@@ -492,6 +493,7 @@ export async function studioApp(
492493 return page({
493494 ctx,
494495 title: `${repo.name}`,
496 ogImage: cardLink(ctx, { kind: "app", repo, record }),
495497 description: appLine({
496498 private: repo.visibility === "private",
497499 name: repo.name,
src/web/studio/change.ts +2 −1
@@ -87,6 +87,7 @@ import { holdCard } from "./hold.ts";
8787 import { pullMayRun } from "../../core/pull_trust.ts";
8888 import { changeHref } from "./nouns.ts";
8989 import { pullWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
90 import { cardLink } from "../og/link.ts";
9091
9192 /** The pull and its repo, or the response that refuses to say why not. */
9293 export function pullContext(ctx: Ctx): { repo: Repo; pull: Pull } | Response {
@@ -623,7 +624,7 @@ async function changeConversation(
623624 return page({
624625 ctx,
625626 title: `${pull.title} · ${repo.name}`,
626 ogImage: cardPath("pull", repo, pull),
627 ogImage: cardLink(ctx, { kind: "thread", repo, issue: pull }),
627628 description: threadLine({
628629 private: repo.visibility === "private",
629630 word,
src/web/studio/run.ts +2
@@ -35,6 +35,7 @@ import { logBox, runVoice, RUN_TRANSCRIPT_CAP } from "./log.ts";
3535 import { changeHref, tellHref } from "./nouns.ts";
3636 import { unnamedRun, voiceFor, type Actor } from "./voice.ts";
3737 import { runWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
38 import { cardLink } from "../og/link.ts";
3839
3940 /**
4041 * The one control a live run has: a person who can write here stops a
@@ -319,6 +320,7 @@ export async function runView(
319320 return page({
320321 ctx,
321322 title: `${title} · ${repo.name}`,
323 ogImage: cardLink(ctx, { kind: "run", repo, runId: run.id }),
322324 description: runLine({
323325 private: repo.visibility === "private",
324326 word,
src/web/studio/tell.ts +2 −1
@@ -70,6 +70,7 @@ import {
7070 servingHistory,
7171 type WordCtx,
7272 } from "./words.ts";
73 import { cardLink } from "../og/link.ts";
7374
7475 /** The pull whose merge closed this issue, from the event it left behind —
7576 * the same record `stateEvents` (thread.ts) reads for the timeline's own
@@ -421,7 +422,7 @@ async function studioTell(
421422 return page({
422423 ctx,
423424 title: `${issue.title} · ${repo.name}`,
424 ogImage: cardPath("issue", repo, issue),
425 ogImage: cardLink(ctx, { kind: "thread", repo, issue }),
425426 description: threadLine({
426427 private: repo.visibility === "private" || issue.sealed,
427428 word: wordInfo?.word ?? (issue.state === "open" ? "open" : "closed"),
test/og-designs.test.ts +1 −1
@@ -340,7 +340,7 @@ describe("over HTTP", () => {
340340 expect(svg).not.toContain("hidden");
341341 });
342342
343 test("the map page names its card only when the repo is public; the audit page always", async () => {
343 test("the map page names its card only when the repo is public; the audit page always; any other page has the site's", async () => {
344344 const page = await (await get("/alice/shown/map")).text();
345345 expect(page).toContain(`content="${base}/og/map/alice~shown.png"`);
346346 expect(page).toContain(`content="summary_large_image"`);
test/og-every-page.test.ts added +201
@@ -0,0 +1,201 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp as createForge, type App } from "../src/app.ts";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp } from "../src/core/apps.ts";
8 import { setSealed } from "../src/core/sealed.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { getRepo } from "../src/core/repos.ts";
11 import { createRun } from "../src/core/runs.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14
15 /** Every page a link can be pasted from carries a card, written from its state. */
16 describe("link previews on every page", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let base: string;
21 let runId = "";
22 let sealedRunId = "";
23 let sealedId = "";
24
25 beforeAll(async () => {
26 dataDir = await mkdtemp(join(tmpdir(), "forge-og-all-"));
27 app = createForge({ dataDir, port: 0 });
28 servers = await serve(app);
29 base = servers.url;
30 const u = await createUser(app.db, {
31 trusted: true,
32 username: "alice",
33 email: "[email protected]",
34 password: "alice-passphrase",
35 adminIfFirst: true,
36 });
37 if (!u.ok) throw new Error(u.error);
38 for (const [name, visibility, description, access] of [
39 ["shown", "public", "A public thing for the cards", "public"],
40 ["hidden", "private", "Secret plans nobody may read", "public"],
41 ["closed", "public", "A public repository with a private app", "private"],
42 ] as const) {
43 const made = await createRepo(app, u.value, { name, visibility, description });
44 if (!made.ok) throw new Error(String(made.error));
45 const rec = createApp(app.db, { repoId: made.value.id, slug: `${name}-app`, access });
46 if (!rec.ok) throw new Error(rec.error);
47 }
48 const id = (n: string) => getRepo(app.db, "alice", n)!.id;
49 const mk = (repo: string, title: string, kind: "issue" | "pull") => {
50 const i = createIssue(app.db, {
51 repoId: id(repo),
52 authorId: u.value.id,
53 title,
54 kind,
55 body: `Body of ${title}`,
56 });
57 if (!i.ok) throw new Error(String(i.error));
58 if (kind === "pull")
59 app.db
60 .query(
61 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id)
62 VALUES (?1, 'main', 'topic', '', '', ?2)`,
63 )
64 .run(i.value.id, id(repo));
65 };
66 mk("shown", "Shown issue", "issue");
67 mk("shown", "Shown pull", "pull");
68 mk("hidden", "Hidden issue", "issue");
69 // A sealed report and a run on it, and a private-access app, all on the public repository.
70 const sealed = createIssue(app.db, {
71 repoId: id("shown"),
72 authorId: u.value.id,
73 title: "Sealed report",
74 kind: "issue",
75 body: "Body of the sealed report",
76 });
77 if (!sealed.ok) throw new Error(String(sealed.error));
78 sealedId = sealed.value.id;
79 setSealed(app.db, sealedId, true);
80 sealedRunId = createRun(app.db, { repoId: id("shown"), kind: "agent", summary: "sealed work", issueId: sealedId }).id;
81 runId = createRun(app.db, { repoId: id("shown"), kind: "agent", summary: "did a thing" }).id;
82 });
83
84 afterAll(async () => {
85 await servers.stop();
86 await rm(dataDir, { recursive: true, force: true });
87 });
88
89 const metas = (htmlText: string) => {
90 const out = new Map<string, string>();
91 for (const m of htmlText.matchAll(/<meta\s+(?:property|name)="([^"]+)"\s+content="([^"]*)"/g))
92 out.set(m[1]!, m[2]!);
93 return out;
94 };
95
96 const TOP = [
97 "/", "/explore", "/signin", "/signup", "/audit", "/map", "/apps", "/releases",
98 "/search", "/flow", "/system", "/contribute", "/resilience", "/board", "/asks",
99 "/asked", "/family", "/new", "/migrate",
100 ];
101 const things = () => [
102 "/alice/shown",
103 "/alice/shown/issues/1",
104 "/alice/shown/pulls/2",
105 `/alice/shown/runs/${runId}`,
106 "/alice",
107 "/alice/shown/app",
108 ];
109
110 const carries = async (path: string) => {
111 const res = await fetch(base + path, { redirect: "follow" });
112 expect(res.status, path).toBe(200);
113 const m = metas(await res.text());
114 expect(m.get("og:title"), path).toBeTruthy();
115 expect(m.get("og:description"), path).toBeTruthy();
116 expect(m.get("twitter:card"), path).toBe("summary_large_image");
117 const image = m.get("og:image");
118 expect(image, path).toBeTruthy();
119 const img = await fetch(image!.replace(/^https?:\/\/[^/]+/, base));
120 expect(img.status, `${path} → ${image}`).toBe(200);
121 expect(img.headers.get("content-type"), path).toBe("image/png");
122 return m;
123 };
124
125 for (const path of TOP)
126 test(`${path} carries a card`, async () => {
127 await carries(path);
128 });
129
130 test("repo, issue, pull, run, person and app pages carry a card written from their state", async () => {
131 const want: Record<string, RegExp> = {
132 "/alice/shown": /A public thing for the cards/,
133 "/alice/shown/issues/1": /Body of Shown issue|Shown issue/,
134 "/alice/shown/pulls/2": /Body of Shown pull|Shown pull/,
135 [`/alice/shown/runs/${runId}`]: /did a thing/,
136 "/alice": /repositor/i,
137 "/alice/shown/app": /not running/,
138 };
139 for (const path of things()) {
140 const m = await carries(path);
141 expect(m.get("og:description")!, path).toMatch(want[path]!);
142 expect(m.get("og:image"), path).toContain("/og/");
143 expect(m.get("og:image"), path).not.toContain("icons");
144 }
145 });
146
147 test("a private repository, seen anonymously, is the same page as a missing one", async () => {
148 const miss = metas(await (await fetch(base + "/alice/nothing")).text());
149 for (const path of ["/alice/hidden", "/alice/hidden/issues/1", "/alice/hidden/runs/x"]) {
150 const res = await fetch(base + path);
151 expect(res.status, path).toBe(404);
152 const m = metas(await res.text());
153 expect([...m.entries()], path).toEqual([...miss.entries()]);
154 expect([...m.values()].join("\n"), path).not.toMatch(/Secret plans|Hidden issue|hidden/);
155 expect(m.get("twitter:card"), path).toBe("summary_large_image");
156 }
157 for (const card of ["/og/issue/alice~hidden~1", "/og/app/hidden-app"])
158 for (const ext of ["svg", "png"])
159 expect((await fetch(`${base}${card}.${ext}`)).status, card).toBe(404);
160 // The repository card names the repository and says "private", the same as for a missing one.
161 const hidden = await (await fetch(`${base}/og/repo/alice~hidden.svg`)).text();
162 const absent = await (await fetch(`${base}/og/repo/alice~nothing.svg`)).text();
163 expect(hidden).toContain("alice/hidden");
164 expect(hidden).toContain("private");
165 expect(hidden).not.toMatch(/Secret plans|Hidden issue/);
166 expect(hidden.replaceAll("hidden", "nothing")).toBe(absent);
167 });
168
169 test("a signed-in reader of a private repository unfurls as 'Private.' with the site card", async () => {
170 const signin = await fetch(base + "/signin", {
171 method: "POST",
172 redirect: "manual",
173 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
174 body: "username=alice&password=alice-passphrase",
175 });
176 const cookie = (signin.headers.getSetCookie?.() ?? []).map((c) => c.split(";")[0]).join("; ");
177 expect(cookie).toBeTruthy();
178 for (const path of ["/alice/hidden", "/alice/hidden/issues/1"]) {
179 const res = await fetch(base + path, { headers: { cookie } });
180 expect(res.status, path).toBe(200);
181 const m = metas(await res.text());
182 expect(m.get("og:description"), path).toBe("Private.");
183 expect(m.get("og:image"), path).toEndWith("/og/site.png");
184 }
185 // Readable here, but not to a signed-out fetcher: the card falls back to the site's.
186 const sealedNumber = (app.db.query("SELECT number FROM issue WHERE id = ?1").get(sealedId) as { number: number }).number;
187 const hereOnly = [
188 `/alice/shown/issues/${sealedNumber}`,
189 `/alice/shown/runs/${sealedRunId}`,
190 "/alice/closed/app",
191 ];
192 for (const path of hereOnly) {
193 const res = await fetch(base + path, { headers: { cookie } });
194 expect(res.status, path).toBe(200);
195 expect(metas(await res.text()).get("og:image"), path).toEndWith("/og/site.png");
196 }
197 expect((await fetch(`${base}/og/issue/alice~shown~${sealedNumber}.png`)).status).toBe(404);
198 expect((await fetch(`${base}/og/run/alice~shown~${sealedRunId}.png`)).status).toBe(404);
199 expect((await fetch(`${base}/og/app/closed-app.png`)).status).toBe(404);
200 });
201 });
test/standards.test.ts +1 −3
@@ -172,9 +172,7 @@ describe("what the open web expects", () => {
172172 expect(html).toContain(
173173 'rel="apple-touch-icon" href="/icons/forge-180.png"',
174174 );
175 // A repository page carries its own card (/og/repo), not the icon.
176 expect(html).toContain(`content="${base}/og/repo/alice~open.png"`);
177 expect(html).toContain('name="twitter:card" content="summary_large_image"');
175 expect(html).toContain(`name="twitter:card" content="summary_large_image"`);
178176 expect(html).toContain("viewport-fit=cover");
179177 });
180178

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs