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

OG cards as SVG: `/og/:kind/:ref.svg` composed from live data with the studio's tokens, cached by input hash #1008

Closed opened this
Closed without merging

scout/forge:scout/567-og-cards-as-svg-og-kind-ref-svg-composed → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +433 −0
scripts/gate.ts +1
@@ -23,6 +23,7 @@ export type Exclusion = {
2323
2424 export const GATE: readonly string[] = [
2525 "test/accounts.test.ts",
26 "test/og-card.test.ts",
2627 "test/agents.test.ts",
2728 "test/app-domains.test.ts",
2829 "test/app.test.ts",
src/core/reserved.ts +1
@@ -70,6 +70,7 @@ export const SYSTEM_NAMES: readonly string[] = [
7070 "go",
7171 "icons",
7272 "live",
73 "og",
7374 "login",
7475 "logout",
7576 "manifest.webmanifest",
src/http/server.ts +3
@@ -78,6 +78,7 @@ import {
7878 verifyPage,
7979 themeSubmit,
8080 } from "../web/pages/site.ts";
81 import { ogCard } from "../web/pages/og.ts";
8182 import { confirmPage, searchPage } from "../web/pages/search.ts";
8283 import { followingSubmit } from "../web/pages/following.ts";
8384 import { activityAtom } from "../web/feeds.ts";
@@ -514,6 +515,8 @@ export function buildRouter(): Router<Handler> {
514515 router.add("GET", "/sitemap.xml", sitemapXml);
515516 router.add("GET", "/manifest.webmanifest", webManifest);
516517 router.add("GET", "/icons/:spec.png", iconPng);
518 // Social cards, composed from public data (web/og/card.ts). Literal, above /:owner.
519 router.add("GET", "/og/:kind/:ref.svg", ogCard);
517520 // The highlighter bundle, content-addressed. A stale hash is a 404 rather
518521 // than a redirect: the page that asked for it names the hash it was built
519522 // with, so a miss means an old tab, and an old tab should reload.
src/web/og/card.ts added +118
@@ -0,0 +1,118 @@
1 /**
2 * The OG card: typed page data in, a 1200×630 SVG string out. Pure — no
3 * database, no clock — so the same input is the same bytes and the route can
4 * cache by the hash of the input. Colours are the studio's own tokens
5 * (`design/themes.ts`, Porcelain); the type is the stylesheet's system stack.
6 *
7 * Every string is stripped of what XML forbids, clamped to the width it is
8 * drawn in (an ellipsis, never an overflow) and escaped on the way out.
9 */
10
11 import { THEMES } from "../../design/themes.ts";
12
13 export const CARD_KINDS = ["app", "repo", "issue", "pull", "run"] as const;
14 export type CardKind = (typeof CARD_KINDS)[number];
15
16 export interface CardInput {
17 kind: CardKind;
18 title: string;
19 /** Up to three supporting lines under the title. */
20 lines: readonly string[];
21 /** The one figure or state worth a glance, bottom right. */
22 stat: string;
23 }
24
25 export const CARD_WIDTH = 1200;
26 export const CARD_HEIGHT = 630;
27
28 const PAD = 72;
29 const INNER = CARD_WIDTH - PAD * 2;
30 const MAX_LINES = 3;
31 const FONT =
32 "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
33
34 const t = THEMES.light.tokens;
35
36 /** Stripped of what XML 1.0 cannot carry, newlines folded to spaces. */
37 function clean(text: string): string {
38 return text
39 .replace(/\s+/g, " ")
40 // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point
41 .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, "")
42 .replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "")
43 .trim();
44 }
45
46 function escapeXml(text: string): string {
47 return text
48 .replace(/&/g, "&amp;")
49 .replace(/</g, "&lt;")
50 .replace(/>/g, "&gt;")
51 .replace(/"/g, "&quot;")
52 .replace(/'/g, "&#39;");
53 }
54
55 /** A deliberately generous width per character, in ems: wide scripts are a
56 * full em, capitals and digits a little over half, the rest just under. */
57 function advance(ch: string): number {
58 const c = ch.codePointAt(0)!;
59 if (c >= 0x1100) return 1;
60 if (ch >= "A" && ch <= "Z") return 0.72;
61 if (ch === "W" || ch === "M") return 0.9;
62 return 0.6;
63 }
64
65 /** The text cut to fit `width` px at `size` px, ending in an ellipsis if cut. */
66 export function clamp(text: string, size: number, width: number): string {
67 const chars = [...clean(text)];
68 let used = 0;
69 const room = width - size; // keep an em for the ellipsis
70 let cut = -1;
71 for (const [i, ch] of chars.entries()) {
72 used += advance(ch) * size;
73 if (cut === -1 && used > room) cut = i;
74 if (used > width) return chars.slice(0, cut).join("").trimEnd() + "…";
75 }
76 return chars.join("");
77 }
78
79 function text(
80 x: number,
81 y: number,
82 size: number,
83 fill: string,
84 body: string,
85 extra = "",
86 ): string {
87 return `<text x="${x}" y="${y}" font-family="${FONT}" font-size="${size}" fill="${fill}"${extra}>${escapeXml(body)}</text>`;
88 }
89
90 export function renderCard(input: CardInput): string {
91 const kind = input.kind.toUpperCase();
92 const stat = clamp(input.stat, 36, 420);
93 const parts = [
94 `<svg xmlns="http://www.w3.org/2000/svg" width="${CARD_WIDTH}" height="${CARD_HEIGHT}" viewBox="0 0 ${CARD_WIDTH} ${CARD_HEIGHT}" role="img">`,
95 `<defs><linearGradient id="m" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${t.accent}"/><stop offset="1" stop-color="${t.merged}"/></linearGradient></defs>`,
96 `<rect width="${CARD_WIDTH}" height="${CARD_HEIGHT}" fill="${t.bg}"/>`,
97 `<rect x="24" y="24" width="${CARD_WIDTH - 48}" height="${CARD_HEIGHT - 48}" rx="20" fill="${t.card}" stroke="${t.border}" stroke-width="2"/>`,
98 `<rect x="${PAD}" y="${PAD}" width="44" height="44" rx="11" fill="url(#m)"/>`,
99 text(PAD + 64, PAD + 33, 26, t.fg, "forge", ' font-weight="650"'),
100 text(
101 CARD_WIDTH - PAD,
102 PAD + 33,
103 22,
104 t.accent,
105 kind,
106 ' text-anchor="end" font-weight="650" letter-spacing="3"',
107 ),
108 text(PAD, 270, 68, t.fg, clamp(input.title, 68, INNER), ' font-weight="650"'),
109 ];
110 for (const [i, line] of input.lines.slice(0, MAX_LINES).entries())
111 parts.push(text(PAD, 340 + i * 46, 30, t["muted-fg"], clamp(line, 30, INNER)));
112 parts.push(
113 `<line x1="${PAD}" y1="520" x2="${CARD_WIDTH - PAD}" y2="520" stroke="${t.border}" stroke-width="2"/>`,
114 text(CARD_WIDTH - PAD, 573, 36, t.fg, stat, ' text-anchor="end" font-weight="600"'),
115 `</svg>`,
116 );
117 return parts.join("");
118 }
src/web/pages/og.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * GET /og/:kind/:ref.svg — the social card of an app, repository, issue,
3 * pull or run, composed from live data and cached by the hash of its inputs.
4 *
5 * The ref names the thing: an app by slug, a repository `owner~name`, an
6 * issue or pull `owner~name~N`, a run by id. Only public repositories the
7 * viewer can read are drawn; anything else — private, missing, unknown kind —
8 * is the same 404. The response is `public`, so a card never carries more
9 * than a stranger could see — which also rules out a sealed report.
10 */
11
12 import { getAppBySlug } from "../../core/apps.ts";
13 import { getIssue } from "../../core/issues.ts";
14 import { getPull } from "../../core/pulls.ts";
15 import { canRead, getRepo, getRepoById, type Repo } from "../../core/repos.ts";
16 import { getRun } from "../../core/runs.ts";
17 import { notFound } from "../../http/respond.ts";
18 import type { Ctx } from "../../http/context.ts";
19 import { sha256 } from "../../kernel/hash.ts";
20 import { CARD_KINDS, renderCard, type CardInput, type CardKind } from "../og/card.ts";
21
22 const CACHE_MAX = 500;
23 const cache = new Map<string, string>();
24
25 const isKind = (v: string): v is CardKind =>
26 (CARD_KINDS as readonly string[]).includes(v);
27
28 function readable(ctx: Ctx, repo: Repo | undefined): repo is Repo {
29 return (
30 repo !== undefined &&
31 repo.visibility === "public" &&
32 canRead(ctx.app.db, repo, ctx.auth.user)
33 );
34 }
35
36 function repoByRef(ctx: Ctx, owner: string, name: string): Repo | undefined {
37 const repo = getRepo(ctx.app.db, owner, name);
38 return readable(ctx, repo) ? repo : undefined;
39 }
40
41 /** What the card says, or undefined for a thing that is not there to see. */
42 function compose(ctx: Ctx, kind: CardKind, ref: string): CardInput | undefined {
43 const db = ctx.app.db;
44 const [owner = "", name = "", num = "", extra] = ref.split("~");
45 if (kind === "app") {
46 const app = getAppBySlug(db, ref);
47 const repo = app && getRepoById(db, app.repoId);
48 if (!app || !readable(ctx, repo)) return undefined;
49 return {
50 kind,
51 title: app.slug,
52 lines: [`${repo.ownerName}/${repo.name}`, repo.description],
53 stat: app.access === "public" ? "public" : "private",
54 };
55 }
56 if (kind === "run") {
57 const run = getRun(db, ref);
58 const repo = run && getRepoById(db, run.repoId);
59 if (!run || !readable(ctx, repo)) return undefined;
60 return {
61 kind,
62 title: run.summary || `${run.kind} run`,
63 lines: [`${repo.ownerName}/${repo.name}`, run.env || run.branch],
64 stat: run.state,
65 };
66 }
67 if (extra !== undefined || owner === "" || name === "") return undefined;
68 const repo = repoByRef(ctx, owner, name);
69 if (!repo) return undefined;
70 const slug = `${repo.ownerName}/${repo.name}`;
71 if (kind === "repo") {
72 if (num !== "") return undefined;
73 return {
74 kind,
75 title: slug,
76 lines: [repo.description],
77 stat: repo.defaultBranch,
78 };
79 }
80 if (!/^[1-9][0-9]{0,8}$/.test(num)) return undefined;
81 const n = Number(num);
82 if (kind === "pull") {
83 const pull = getPull(db, repo.id, n);
84 if (!pull || pull.sealed) return undefined;
85 return {
86 kind,
87 title: pull.title,
88 lines: [`${slug} #${n}`, `${pull.headBranch} → ${pull.baseBranch}`],
89 stat: pull.mergedAt === null ? pull.state : "merged",
90 };
91 }
92 const issue = getIssue(db, repo.id, n);
93 if (!issue || issue.kind !== "issue" || issue.sealed) return undefined;
94 return {
95 kind,
96 title: issue.title,
97 lines: [`${slug} #${n}`, `opened by ${issue.originAuthor ?? issue.authorName}`],
98 stat: issue.state,
99 };
100 }
101
102 export function ogCard(ctx: Ctx): Response {
103 const kind = ctx.params.kind ?? "";
104 if (!isKind(kind)) return notFound();
105 const input = compose(ctx, kind, ctx.params.ref ?? "");
106 if (!input) return notFound();
107 const hash = sha256(JSON.stringify(input));
108 const etag = `"${hash}"`;
109 const headers = {
110 etag,
111 "cache-control": "public, max-age=300",
112 };
113 if (ctx.request.headers.get("if-none-match")?.split(",").some((v) => v.trim() === etag))
114 return new Response(null, { status: 304, headers });
115 let svg = cache.get(hash);
116 if (svg === undefined) {
117 svg = renderCard(input);
118 if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value!);
119 cache.set(hash, svg);
120 }
121 return new Response(svg, {
122 headers: { ...headers, "content-type": "image/svg+xml; charset=utf-8" },
123 });
124 }
test/og-card.test.ts added +186
@@ -0,0 +1,186 @@
1 /**
2 * The OG card (#567): every kind renders well-formed 1200×630 SVG, hostile
3 * text is escaped and clamped, a private repository is a 404, and the second
4 * ask is a 304 or a sub-5 ms cache hit.
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 { createApp as insertApp } from "../src/core/apps.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { CARD_KINDS, clamp, renderCard } from "../src/web/og/card.ts";
19
20 /** Well-formed XML for this card's subset: balanced tags, quoted attributes,
21 * and no raw `<` or stray `&` anywhere in text or attribute values. */
22 function wellFormed(svg: string): void {
23 const stack: string[] = [];
24 let rest = svg;
25 while (rest !== "") {
26 const tag = /^<(\/?)([a-zA-Z]+)((?:\s+[\w:-]+="[^"<&]*")*)\s*(\/?)>/.exec(rest);
27 if (tag) {
28 const [whole, close, name, , selfClose] = tag;
29 if (close) expect(stack.pop()).toBe(name!);
30 else if (!selfClose) stack.push(name!);
31 rest = rest.slice(whole.length);
32 continue;
33 }
34 const chars = /^(?:[^<&]|&(?:amp|lt|gt|quot|#39);)+/.exec(rest);
35 expect(chars).not.toBeNull();
36 rest = rest.slice(chars![0].length);
37 }
38 expect(stack).toEqual([]);
39 expect(svg.startsWith("<svg ")).toBe(true);
40 }
41
42 describe("renderCard", () => {
43 for (const kind of CARD_KINDS) {
44 test(`${kind} is a 1200×630 card`, () => {
45 const svg = renderCard({ kind, title: "A title", lines: ["one", "two"], stat: "open" });
46 expect(svg).toContain('width="1200" height="630"');
47 expect(svg).toContain(kind.toUpperCase());
48 wellFormed(svg);
49 });
50 }
51
52 test("a hostile title is escaped and clamped", () => {
53 const title = `<script>alert(1)</script> & "${"x".repeat(500)}`;
54 const svg = renderCard({ kind: "issue", title, lines: [title], stat: title });
55 expect(svg).not.toContain("<script");
56 expect(svg).toContain("&lt;script&gt;");
57 expect(svg).toContain("&amp;");
58 expect(svg).not.toContain("x".repeat(100));
59 expect(svg).toContain("…");
60 wellFormed(svg);
61 });
62
63 test("clamp keeps short text and fits long text in its width", () => {
64 expect(clamp("short", 68, 1056)).toBe("short");
65 const out = clamp("W".repeat(300) + "漢".repeat(300), 68, 1056);
66 expect(out.endsWith("…")).toBe(true);
67 expect([...out].length).toBeLessThan(25);
68 });
69
70 test("control characters never reach the document", () => {
71 const svg = renderCard({ kind: "repo", title: "a\u0000b\u0008c\ud800d", lines: [], stat: "" });
72 expect(svg).toContain(">abcd<");
73 });
74 });
75
76 describe("GET /og/:kind/:ref.svg", () => {
77 let dataDir: string;
78 let app: App;
79 let servers: Servers;
80 let base: string;
81 let alice: User;
82 let runId: string;
83
84 beforeAll(async () => {
85 dataDir = await mkdtemp(join(tmpdir(), "forge-og-"));
86 app = createApp({ dataDir, port: 0 });
87 servers = await serve(app);
88 base = servers.url;
89 const a = await createUser(app.db, {
90 trusted: true,
91 username: "alice",
92 email: "[email protected]",
93 password: "a-good-passphrase",
94 adminIfFirst: true,
95 });
96 if (!a.ok) throw new Error(a.error);
97 alice = a.value;
98 for (const [name, visibility] of [["open", "public"], ["closed", "private"]] as const) {
99 const r = await createRepo(app, alice, { name, visibility });
100 if (!r.ok) throw new Error(String(r.error));
101 }
102 const open = getRepo(app.db, "alice", "open")!;
103 const closed = getRepo(app.db, "alice", "closed")!;
104 const mk = (repoId: string, title: string, sealed = false) => {
105 const i = createIssue(app.db, { repoId, authorId: alice.id, title, sealed });
106 if (!i.ok) throw new Error(i.error);
107 };
108 mk(open.id, `<script>alert(1)</script> & ${"y".repeat(200)}`);
109 mk(closed.id, "secret");
110 mk(open.id, "sealed", true);
111 insertApp(app.db, { repoId: open.id, slug: "openapp", access: "public" });
112 insertApp(app.db, { repoId: closed.id, slug: "closedapp", access: "public" });
113 runId = createRun(app.db, { repoId: open.id, kind: "deploy", env: "production" }).id;
114 });
115
116 afterAll(async () => {
117 servers.stop();
118 app.close();
119 await rm(dataDir, { recursive: true, force: true });
120 });
121
122 const get = (path: string, headers: Record<string, string> = {}) =>
123 fetch(`${base}/og/${path}`, { headers });
124
125 test("app, repo, issue and run answer with an SVG and the floor headers", async () => {
126 for (const ref of ["app/openapp", "repo/alice~open", "issue/alice~open~1", `run/${runId}`]) {
127 const res = await get(`${ref}.svg`);
128 expect(res.status).toBe(200);
129 expect(res.headers.get("content-type")).toContain("image/svg+xml");
130 expect(res.headers.get("cache-control")).toBe("public, max-age=300");
131 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
132 expect(res.headers.get("content-security-policy")).toBeTruthy();
133 wellFormed(await res.text());
134 }
135 });
136
137 test("the hostile issue title is escaped in the response", async () => {
138 const svg = await (await get("issue/alice~open~1.svg")).text();
139 expect(svg).not.toContain("<script");
140 expect(svg).toContain("&lt;script&gt;");
141 });
142
143 test("private, sealed, missing and unknown are all 404", async () => {
144 for (const ref of [
145 "repo/alice~closed",
146 "issue/alice~closed~1",
147 "app/closedapp",
148 "issue/alice~open~3",
149 "issue/alice~open~1~2",
150 "issue/alice~open~x",
151 "pull/alice~open~1",
152 "repo/alice~nope",
153 "run/nope",
154 "widget/alice~open",
155 ])
156 expect((await get(`${ref}.svg`)).status).toBe(404);
157 });
158
159 test("the owner's session does not widen it: private stays 404", async () => {
160 const res = await fetch(`${base}/og/repo/alice~closed.svg`, {
161 headers: { authorization: `Basic ${btoa("alice:a-good-passphrase")}` },
162 });
163 expect(res.status).toBe(404);
164 });
165
166 test("the ETag answers 304, and a warm request is under 5 ms", async () => {
167 const first = await get("repo/alice~open.svg");
168 const etag = first.headers.get("etag")!;
169 expect(etag).toMatch(/^"[0-9a-f]{64}"$/);
170 const again = await get("repo/alice~open.svg", { "if-none-match": etag });
171 expect(again.status).toBe(304);
172 expect(await again.text()).toBe("");
173 const stale = await get("repo/alice~open.svg", { "if-none-match": '"other"' });
174 expect(stale.status).toBe(200);
175
176 const times: number[] = [];
177 for (let i = 0; i < 20; i++) {
178 const t0 = performance.now();
179 const res = await get("repo/alice~open.svg");
180 await res.text();
181 times.push(performance.now() - t0);
182 }
183 times.sort((x, y) => x - y);
184 expect(times[10]!).toBeLessThan(5);
185 });
186 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs