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

`GET /og/app/:ref.svg` and `/og/repo/:ref.svg` serve a live card with an ETag, and `og` is a reserved name #1649

Closed opened this
Closed without merging

scout/forge:scout/1590-get-og-app-ref-svg-and-og-repo-ref-svg-s → main 4 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +202 −0
scripts/gate.ts +1
@@ -40,6 +40,7 @@ export const GATE: readonly string[] = [
4040 "test/tui-onyou.test.ts",
4141 "test/claim-link.test.ts",
4242 "test/og-card.test.ts",
43 "test/og-route.test.ts",
4344 "test/health.test.ts",
4445 "test/client-address.test.ts",
4546 "test/client-list.test.ts",
src/core/reserved.ts +1
@@ -75,6 +75,7 @@ export const SYSTEM_NAMES: readonly string[] = [
7575 "manifest.webmanifest",
7676 "map",
7777 "mcp",
78 "og",
7879 "contract",
7980 "migrate",
8081 "mode",
src/http/server.ts +3
@@ -184,6 +184,7 @@ import {
184184 tellSubmit,
185185 } from "../web/studio/actions.ts";
186186 import { everydayCreate, everydayKeep, everydaySwitch } from "../web/pages/everyday.ts";
187 import { ogCard } from "../web/pages/og.ts";
187188 import { claimFragmentPage, claimSubmit } from "../web/pages/claim.ts";
188189 import { forgeLinkSubmit, forgesPage } from "../web/pages/forges.ts";
189190 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
@@ -630,6 +631,8 @@ export function buildRouter(): Router<Handler> {
630631 headers: { "cache-control": "no-store" },
631632 });
632633 });
634 // Live social cards for an app or a repo (web/pages/og.ts); literal, above /:owner.
635 router.add("GET", "/og/:kind/:ref.svg", ogCard);
633636 router.add("GET", "/runs/:id", runRedirect);
634637 router.add("GET", "/settings", accountPage);
635638 router.add("POST", "/settings", accountUpdate);
src/web/pages/og.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * `GET /og/:kind/:ref.svg` — a live social card for an app or a repo, drawn
3 * by the pure renderer in `web/og/card.ts`. A repo's ref is `owner~name`, an
4 * app's is its slug. What the viewer may not read is a 404, exactly like an
5 * unknown kind or a malformed ref, so a card never confirms a private name.
6 *
7 * The ETag is the sha256 of the card's inputs; the same hash keys a small
8 * in-memory cache of rendered SVG, so a warm request renders nothing and a
9 * matching `If-None-Match` is a 304.
10 */
11
12 import { getAppBySlug } from "../../core/apps.ts";
13 import { canRead, countsForRepos, getRepo, getRepoById } from "../../core/repos.ts";
14 import { isSafeName } from "../../git/guard.ts";
15 import type { Ctx } from "../../http/context.ts";
16 import { notFound } from "../../http/respond.ts";
17 import { renderCard, type CardInput } from "../og/card.ts";
18
19 const MAX_CACHED = 256;
20 const cache = new Map<string, string>();
21
22 const HEADERS = {
23 "content-type": "image/svg+xml; charset=utf-8",
24 "x-content-type-options": "nosniff",
outdated

High: this header is fixed for every card, including private ones a signed-in reader is allowed to see. A shared cache can then serve a private repo's name, description and counts to anyone. Choose it per response, as src/web/feeds.ts does: public, max-age=300 for a public repo and private, no-store otherwise. Apply it on the 304 as well.

25 "referrer-policy": "same-origin",
26 "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'",
27 };
28
29 /** A card of a public repo is shared; one only a signed-in reader may see never is. */
30 const SHARED = "public, max-age=300";
31 const PRIVATE = "private, no-store";
32
33 interface Card {
34 input: CardInput;
35 cacheControl: string;
36 }
37
38 function cardFor(ctx: Ctx, kind: string, ref: string): Card | undefined {
39 const { db } = ctx.app;
40 const viewer = ctx.auth.user;
41 if (kind === "repo") {
42 const [owner, name, ...extra] = ref.split("~");
43 if (!owner || !name || extra.length || !isSafeName(owner) || !isSafeName(name))
44 return undefined;
45 const repo = getRepo(db, owner, name);
46 if (!repo || !canRead(db, repo, viewer)) return undefined;
47 const n = countsForRepos(db, [repo.id]).get(repo.id);
48 return {
49 cacheControl: repo.visibility === "public" ? SHARED : PRIVATE,
50 input: {
51 kind: "repo",
52 title: `${repo.ownerName}/${repo.name}`,
53 lines: [repo.description],
54 stat: `${n?.openIssues ?? 0} open issues · ${n?.openPulls ?? 0} open pulls`,
55 },
56 };
57 }
58 if (kind === "app") {
59 if (!/^[a-z0-9][a-z0-9-]{0,62}$/i.test(ref)) return undefined;
60 const app = getAppBySlug(db, ref);
61 const repo = app && getRepoById(db, app.repoId);
62 if (!app || !repo || !canRead(db, repo, viewer)) return undefined;
63 return {
64 cacheControl: repo.visibility === "public" ? SHARED : PRIVATE,
65 input: {
66 kind: "app",
67 title: app.slug,
68 lines: [repo.description, `${repo.ownerName}/${repo.name}`],
69 stat: app.access === "public" ? "open to anyone" : "sign-in required",
70 },
71 };
72 }
73 return undefined;
74 }
75
76 export function ogCard(ctx: Ctx): Response {
77 const kind = ctx.params.kind ?? "";
78 const card = cardFor(ctx, kind, ctx.params.ref ?? "");
79 if (!card) return notFound();
80 const { input } = card;
81 const head = { ...HEADERS, "cache-control": card.cacheControl };
82 const hash = new Bun.CryptoHasher("sha256").update(JSON.stringify(input)).digest("hex");
83 const etag = `"${hash}"`;
84 const sent = ctx.request.headers.get("if-none-match") ?? "";
85 if (sent.split(",").some((t) => t.trim().replace(/^W\//, "") === etag))
86 return new Response(null, { status: 304, headers: { ...head, etag } });
87 let svg = cache.get(hash);
88 if (svg === undefined) {
89 svg = renderCard(input);
90 if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value!);
91 cache.set(hash, svg);
92 }
93 return new Response(svg, { headers: { ...head, etag } });
94 }
test/og-route.test.ts added +103
@@ -0,0 +1,103 @@
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, type App } from "../src/app.ts";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp as makeApp } from "../src/core/apps.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11
12 describe("og route", () => {
13 let dir: string;
14 let app: App;
15 let servers: Servers;
16 let base: string;
17 let token: string;
18 const get = (path: string, headers: Record<string, string> = {}) =>
19 fetch(`${base}${path}`, { headers });
20
21 beforeAll(async () => {
22 dir = await mkdtemp(join(tmpdir(), "forge-og-route-"));
23 app = createApp({ dataDir: dir, port: 0 });
24 const alice = await createUser(app.db, {
25 trusted: true,
26 username: "alice",
27 email: "[email protected]",
28 password: "alice-passphrase",
29 });
30 if (!alice.ok) throw new Error("user");
31 token = createToken(app.db, alice.value.id, "ro", "ro").token;
32 for (const [name, visibility] of [["open", "public"], ["secret", "private"]] as const) {
33 const made = await createRepo(app, alice.value, { name, visibility, description: "A <b>bakery</b>" });
34 if (!made.ok) throw new Error("repo");
35 makeApp(app.db, { repoId: made.value.id, slug: name, access: "public" });
36 }
37 servers = await serve(app);
38 base = servers.url;
39 });
40 afterAll(async () => {
41 servers.stop();
42 await rm(dir, { recursive: true, force: true });
43 });
44
45 test("repo and app cards answer 200 with the security headers", async () => {
46 for (const path of ["/og/repo/alice~open.svg", "/og/app/open.svg"]) {
47 const res = await get(path);
48 expect(res.status).toBe(200);
49 expect(res.headers.get("content-type")).toStartWith("image/svg+xml");
50 expect(res.headers.get("cache-control")).toBe("public, max-age=300");
51 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
52 expect(res.headers.get("referrer-policy")).toBeTruthy();
53 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
54 const svg = await res.text();
55 expect(svg.startsWith("<svg ")).toBe(true);
56 expect(svg).not.toContain("<b>");
57 }
58 });
outdated

Add the signed-in case: the owner fetches the private repo card and the private app card, gets 200, and the cache-control header is not public. Without that test the leak above goes unnoticed.

59
60 test("a private card is for its reader alone: never cacheable by a shared cache", async () => {
61 const auth = { authorization: `Bearer ${token}` };
62 for (const path of ["/og/repo/alice~secret.svg", "/og/app/secret.svg"]) {
63 const res = await get(path, auth);
64 expect(res.status).toBe(200);
65 expect(res.headers.get("cache-control")).toBe("private, no-store");
66 const again = await get(path, { ...auth, "if-none-match": res.headers.get("etag")! });
67 expect(again.status).toBe(304);
68 expect(again.headers.get("cache-control")).toBe("private, no-store");
69 }
70 });
71
72 test("private, unknown kind and bad refs are 404", async () => {
73 for (const path of [
74 "/og/repo/alice~secret.svg",
75 "/og/app/secret.svg",
76 "/og/repo/alice~nope.svg",
77 "/og/issue/alice~open.svg",
78 "/og/repo/alice.svg",
79 "/og/repo/alice~open~x.svg",
80 "/og/repo/..~open.svg",
81 "/og/app/bad%20slug.svg",
82 ]) {
83 expect((await get(path)).status).toBe(404);
84 }
85 });
86
87 test("ETag and If-None-Match give a 304", async () => {
88 const first = await get("/og/repo/alice~open.svg");
89 const etag = first.headers.get("etag")!;
90 expect(etag).toMatch(/^"[0-9a-f]{64}"$/);
91 const again = await get("/og/repo/alice~open.svg", { "if-none-match": etag });
92 expect(again.status).toBe(304);
93 expect(again.headers.get("etag")).toBe(etag);
94 expect((await get("/og/repo/alice~open.svg", { "if-none-match": '"x"' })).status).toBe(200);
95 });
96
97 test("a repeat request is served the identical card", async () => {
98 const a = await get("/og/app/open.svg");
99 const b = await get("/og/app/open.svg");
100 expect(b.headers.get("etag")).toBe(a.headers.get("etag"));
101 expect(await b.text()).toBe(await a.text());
102 });
103 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs