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

Meta tags on every page: og/twitter tags with a description written from the page's live state, private-safe #1230

Closed opened this
Closed without merging

scout/forge:scout/1053-meta-tags-on-every-page-og-twitter-tags → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +198 −3
scripts/gate.ts +1
@@ -178,6 +178,7 @@ export const GATE: readonly string[] = [
178178 "test/mail-caps.test.ts",
179179 "test/make-it-yours.test.ts",
180180 "test/map.test.ts",
181 "test/meta-tags.test.ts",
181182 "test/pillars.test.ts",
182183 "test/milestones.test.ts",
183184 "test/mcp.test.ts",
src/web/layout.ts +27 −3
@@ -56,6 +56,13 @@ export interface PageOptions {
5656 * an issue's first line. Absent, the forge's own line stands in.
5757 */
5858 description?: string;
59 /**
60 * The page is about something not everyone may read (a private repository,
61 * a sealed report). A link unfurled in a chat is fetched by whoever the chat
62 * runs, so the preview is its name and the word "private" and nothing the
63 * page knows: no title of an issue, no description, no state.
64 */
65 private?: { name: string };
5966 /**
6067 * The shell without its column width: a page whose content earns a wide
6168 * monitor (the code browser, a tree beside a file). The topbar and footer
@@ -498,6 +505,16 @@ function footer(ctx: Ctx): Html {
498505
499506 const SITE_LINE = "Your code, your machine.";
500507
508 /** What a link preview may say: a private page gives its name and no more. */
509 function preview(options: PageOptions): { title: string; description: string } {
510 if (options.private !== undefined)
511 return {
512 title: options.private.name,
513 description: `${options.private.name} is private.`,
514 };
515 return { title: options.title, description: pageDescription(options) };
516 }
517
501518 function pageDescription(options: PageOptions): string {
502519 const own = options.description?.trim().split(/\r?\n/)[0]?.trim() ?? "";
503520 const line = own === "" ? SITE_LINE : own;
@@ -528,6 +545,7 @@ export function page(options: PageOptions, status = 200): Response {
528545 const theme = ctx.theme ?? options.theme;
529546 const flash = readFlash(ctx.request);
530547 const links = pageLinks(ctx);
548 const share = preview(options);
531549 const scriptJs = options.scriptJs
532550 ? `${shellJs}\n${options.scriptJs}`
533551 : shellJs;
@@ -559,11 +577,11 @@ export function page(options: PageOptions, status = 200): Response {
559577 content="width=device-width, initial-scale=1, viewport-fit=cover"
560578 />
561579 <title>${options.title} · forge</title>
562 <meta name="description" content="${pageDescription(options)}" />
580 <meta name="description" content="${share.description}" />
563581 <meta property="og:site_name" content="forge" />
564582 <meta property="og:type" content="website" />
565 <meta property="og:title" content="${options.title}" />
566 <meta property="og:description" content="${pageDescription(options)}" />
583 <meta property="og:title" content="${share.title}" />
584 <meta property="og:description" content="${share.description}" />
567585 ${
568586 // Only a page that exists has a canonical address. An error page
569587 // never echoes the path that was asked for: two dead links must be
@@ -580,6 +598,12 @@ export function page(options: PageOptions, status = 200): Response {
580598 content="${ctx.url.origin}/icons/forge-512.png"
581599 />
582600 <meta name="twitter:card" content="summary" />
601 <meta name="twitter:title" content="${share.title}" />
602 <meta name="twitter:description" content="${share.description}" />
603 <meta
604 name="twitter:image"
605 content="${ctx.url.origin}/icons/forge-512.png"
606 />
583607 <link rel="manifest" href="/manifest.webmanifest" />
584608 ${links.map(
585609 (l) =>
src/web/pages/repo.ts +3
@@ -51,6 +51,7 @@ import { getAppByRepo } from "../../core/apps.ts";
5151 import { field, readForm } from "../form.ts";
5252 import { html, when, type Html } from "../html.ts";
5353 import { flashTo, fragment, page, redirect } from "../layout.ts";
54 import { privacyOf } from "../preview.ts";
5455 import { renderMarkdown } from "../markdown.ts";
5556 import { browseBase, localScope, type RepoScope } from "../scope.ts";
5657 import { repoForkOf } from "../../core/origins.ts";
@@ -959,6 +960,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
959960 ctx,
960961 title: repo.name,
961962 description: repo.description,
963 ...privacyOf(repo),
962964 feed: {
963965 href: `${repoBase(repo)}/activity.atom`,
964966 title: `${repo.ownerName}/${repo.name} activity`,
@@ -1006,6 +1008,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
10061008 ctx,
10071009 title: repo.name,
10081010 description: repo.description,
1011 ...privacyOf(repo),
10091012 feed: {
10101013 href: `${repoBase(repo)}/activity.atom`,
10111014 title: `${repo.ownerName}/${repo.name} activity`,
src/web/preview.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * What a page says about itself to a link preview: the one sentence each page
3 * writes from its live state, and the rule that a private page writes none.
4 */
5
6 import type { Issue } from "../core/issues.ts";
7 import type { Pull } from "../core/pulls.ts";
8 import type { Repo } from "../core/repos.ts";
9
10 /** `PageOptions.private` for a page about this repository (and, if given, a sealed report in it). */
11 export function privacyOf(
12 repo: Repo,
13 issue?: Pick<Issue, "sealed">,
14 ): { private: { name: string } } | Record<string, never> {
15 return repo.visibility === "private" || issue?.sealed === true
16 ? { private: { name: repo.name } }
17 : {};
18 }
19
20 const firstLine = (text: string): string =>
21 text.trim().split(/\r?\n/)[0]?.trim() ?? "";
22
23 /** "Open issue #4 in alice/app: the first line of what was said." */
24 export function threadSentence(repo: Repo, thread: Issue | Pull): string {
25 const pull = "mergedAt" in thread;
26 const state =
27 pull && (thread as Pull).mergedAt !== null ? "merged" : thread.state;
28 const lead = `${state[0]!.toUpperCase()}${state.slice(1)} ${pull ? "change" : "issue"} #${thread.number} in ${repo.ownerName}/${repo.name}`;
29 const said = firstLine(thread.body);
30 return said === "" ? `${lead}.` : `${lead}: ${said}`;
31 }
32
33 /** An app's page: its description, else what it is. */
34 export function appSentence(repo: Repo, open: { changes: number }): string {
35 const own = firstLine(repo.description);
36 const n = open.changes >= 10 ? "10+" : String(open.changes);
37 const live = `${n} open ${open.changes === 1 ? "change" : "changes"}`;
38 return own === "" ? `${repo.ownerName}/${repo.name}: ${live}.` : `${own} (${live})`;
39 }
src/web/studio/app.ts +3
@@ -32,6 +32,7 @@ import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
3232 import { appTailJs, liveRegionsJs } from "../client.ts";
3333 import { html, when, type Html } from "../html.ts";
3434 import { page } from "../layout.ts";
35 import { appSentence, privacyOf } from "../preview.ts";
3536 import { liveClientJs, liveMount } from "../live.ts";
3637 import { followingCard, followingOf } from "../pages/following.ts";
3738 import {
@@ -471,6 +472,8 @@ export async function studioApp(
471472 return page({
472473 ctx,
473474 title: `${repo.name}`,
475 description: appSentence(repo, { changes: openPulls.length }),
476 ...privacyOf(repo),
474477 crumbs: crumbsFor(repo),
475478 palette: repoPalette(ctx, repo),
476479 body,
src/web/studio/change.ts +3
@@ -40,6 +40,7 @@ import {
4040 import { html, when, type Html } from "../html.ts";
4141 import type { IconName as Glyph } from "../icons.ts";
4242 import { page, redirect } from "../layout.ts";
43 import { privacyOf, threadSentence } from "../preview.ts";
4344 import { renderMarkdown } from "../markdown.ts";
4445 import { liveClientJs, liveMount } from "../live.ts";
4546 import {
@@ -531,6 +532,8 @@ async function changeConversation(
531532 return page({
532533 ctx,
533534 title: `${pull.title} · ${repo.name}`,
535 description: threadSentence(repo, pull),
536 ...privacyOf(repo, pull),
534537 crumbs: crumbsFor(repo),
535538 palette: repoPalette(ctx, repo),
536539 body,
src/web/studio/tell.ts +3
@@ -27,6 +27,7 @@ import type { Ctx } from "../../http/context.ts";
2727 import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
2828 import { html, when, type Html } from "../html.ts";
2929 import { page } from "../layout.ts";
30 import { privacyOf, threadSentence } from "../preview.ts";
3031 import { liveClientJs, liveMount } from "../live.ts";
3132 import {
3233 avatar,
@@ -392,6 +393,8 @@ async function studioTell(
392393 return page({
393394 ctx,
394395 title: `${issue.title} · ${repo.name}`,
396 description: threadSentence(repo, issue),
397 ...privacyOf(repo, issue),
395398 crumbs: crumbsFor(repo),
396399 palette: repoPalette(ctx, repo),
397400 body,
test/meta-tags.test.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * Every page carries og/twitter tags; each says one sentence from the page's
3 * live state; a private page previews as its name and the word "private" and
4 * an anonymous fetch of one leaks nothing.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
15
16 const PASSWORD = "a-good-passphrase";
17 const meta = (html: string, key: string): string | undefined =>
18 new RegExp(`<meta\\s+(?:property|name)="${key}"\\s+content="([^"]*)"`).exec(html)?.[1];
19
20 describe("link previews", () => {
21 let dataDir: string;
22 let app: App;
23 let http: ForgeHttp;
24 const base = "http://localhost";
25 let cookie = "";
26
27 beforeAll(async () => {
28 dataDir = await mkdtemp(join(tmpdir(), "forge-meta-"));
29 app = createApp({ dataDir, port: 0 });
30 http = forgeHttp(app);
31 const made = await createUser(app.db, {
32 trusted: true,
33 username: "alice",
34 email: "[email protected]",
35 password: PASSWORD,
36 adminIfFirst: true,
37 });
38 if (!made.ok) throw new Error(made.error);
39 const alice: User = made.value;
40 const open = await createRepo(app, alice, {
41 name: "open",
42 visibility: "public",
43 description: "A public thing",
44 });
45 const shut = await createRepo(app, alice, {
46 name: "shut",
47 visibility: "private",
48 description: "SECRET-DESCRIPTION",
49 });
50 if (!open.ok || !shut.ok) throw new Error("repos");
51 const a = openIssue(app, alice, open.value, {
52 title: "Public bug",
53 body: "It breaks on Tuesdays\nmore",
54 });
55 const b = openIssue(app, alice, shut.value, {
56 title: "SECRET-TITLE",
57 body: "SECRET-BODY",
58 });
59 if (!a.ok || !b.ok) throw new Error("issues");
60 const res = await http.handle(
61 new Request(`${base}/signin`, {
62 method: "POST",
63 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
64 redirect: "manual",
65 }),
66 );
67 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
68 });
69
70 afterAll(async () => {
71 http.close();
72 app.close();
73 await rm(dataDir, { recursive: true, force: true });
74 });
75
76 const get = (path: string, withCookie = false) =>
77 http.handle(
78 new Request(`${base}${path}`, { headers: withCookie ? { cookie } : {} }),
79 );
80
81 test("a page emits og and twitter tags, its description from its data", async () => {
82 const html = await get("/alice/open").then((r) => r.text());
83 for (const k of ["og:title", "og:description", "og:image", "og:url", "twitter:card", "twitter:title", "twitter:description", "twitter:image"])
84 expect(meta(html, k)).toBeDefined();
85 expect(meta(html, "og:description")).toBe("A public thing");
86 expect(meta(html, "twitter:description")).toBe("A public thing");
87 });
88
89 test("an issue's preview is written from its live state", async () => {
90 const html = await get("/alice/open/issues/1").then((r) => r.text());
91 expect(meta(html, "og:description")).toBe(
92 "Open issue #1 in alice/open: It breaks on Tuesdays",
93 );
94 });
95
96 test("an anonymous fetch of a private repository leaks nothing", async () => {
97 for (const path of ["/alice/shut", "/alice/shut/issues/1"]) {
98 const res = await get(path);
99 const text = await res.text();
100 expect(res.status).toBe(404);
101 expect(text).not.toContain("SECRET");
102 // Indistinguishable from a repository that does not exist.
103 const gone = await get(path.replace("shut", "nope")).then((r) => r.text());
104 for (const k of ["og:title", "og:description", "twitter:title", "twitter:description"])
105 expect(meta(text, k)).toBe(meta(gone, k));
106 }
107 });
108
109 test("a private page previews as its name and 'private' only", async () => {
110 for (const path of ["/alice/shut", "/alice/shut/issues/1"]) {
111 const html = await get(path, true).then((r) => r.text());
112 for (const k of ["og:title", "twitter:title"]) expect(meta(html, k)).toBe("shut");
113 for (const k of ["og:description", "twitter:description", "description"])
114 expect(meta(html, k)).toBe("shut is private.");
115 const head = html.slice(0, html.indexOf("</head>"));
116 expect(head.replace(/<title>.*?<\/title>/, "")).not.toContain("SECRET");
117 }
118 });
119 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs