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 #1638
scout/forge:scout/1590-get-og-app-ref-svg-and-og-repo-ref-svg-s → main 1 commit fork
5 files
changed +171
−0
scripts/gate.ts +1
| @@ -40,6 +40,7 @@ export const GATE: readonly string[] = [ | ||
| 40 | 40 | "test/tui-onyou.test.ts", |
| 41 | 41 | "test/claim-link.test.ts", |
| 42 | 42 | "test/og-card.test.ts", |
| 43 | "test/og-route.test.ts", | |
| 43 | 44 | "test/health.test.ts", |
| 44 | 45 | "test/client-address.test.ts", |
| 45 | 46 | "test/client-list.test.ts", |
src/core/reserved.ts +1
| @@ -75,6 +75,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 75 | 75 | "manifest.webmanifest", |
| 76 | 76 | "map", |
| 77 | 77 | "mcp", |
| 78 | "og", | |
| 78 | 79 | "contract", |
| 79 | 80 | "migrate", |
| 80 | 81 | "mode", |
src/http/server.ts +3
| @@ -184,6 +184,7 @@ import { | ||
| 184 | 184 | tellSubmit, |
| 185 | 185 | } from "../web/studio/actions.ts"; |
| 186 | 186 | import { everydayCreate, everydayKeep, everydaySwitch } from "../web/pages/everyday.ts"; |
| 187 | import { ogCard } from "../web/pages/og.ts"; | |
| 187 | 188 | import { claimFragmentPage, claimSubmit } from "../web/pages/claim.ts"; |
| 188 | 189 | import { forgeLinkSubmit, forgesPage } from "../web/pages/forges.ts"; |
| 189 | 190 | import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts"; |
| @@ -630,6 +631,8 @@ export function buildRouter(): Router<Handler> { | ||
| 630 | 631 | headers: { "cache-control": "no-store" }, |
| 631 | 632 | }); |
| 632 | 633 | }); |
| 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); | |
| 633 | 636 | router.add("GET", "/runs/:id", runRedirect); |
| 634 | 637 | router.add("GET", "/settings", accountPage); |
| 635 | 638 | router.add("POST", "/settings", accountUpdate); |
src/web/pages/og.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 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 | "cache-control": "public, max-age=300", | |
| 25 | "x-content-type-options": "nosniff", | |
| 26 | "referrer-policy": "same-origin", | |
| 27 | "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'", | |
| 28 | }; | |
| 29 | ||
| 30 | function cardFor(ctx: Ctx, kind: string, ref: string): CardInput | undefined { | |
| 31 | const { db } = ctx.app; | |
| 32 | const viewer = ctx.auth.user; | |
| 33 | if (kind === "repo") { | |
| 34 | const [owner, name, ...extra] = ref.split("~"); | |
| 35 | if (!owner || !name || extra.length || !isSafeName(owner) || !isSafeName(name)) | |
| 36 | return undefined; | |
| 37 | const repo = getRepo(db, owner, name); | |
| 38 | if (!repo || !canRead(db, repo, viewer)) return undefined; | |
| 39 | const n = countsForRepos(db, [repo.id]).get(repo.id); | |
| 40 | return { | |
| 41 | kind: "repo", | |
| 42 | title: `${repo.ownerName}/${repo.name}`, | |
| 43 | lines: [repo.description], | |
| 44 | stat: `${n?.openIssues ?? 0} open issues · ${n?.openPulls ?? 0} open pulls`, | |
| 45 | }; | |
| 46 | } | |
| 47 | if (kind === "app") { | |
| 48 | if (!/^[a-z0-9][a-z0-9-]{0,62}$/i.test(ref)) return undefined; | |
| 49 | const app = getAppBySlug(db, ref); | |
| 50 | const repo = app && getRepoById(db, app.repoId); | |
| 51 | if (!app || !repo || !canRead(db, repo, viewer)) return undefined; | |
| 52 | return { | |
| 53 | kind: "app", | |
| 54 | title: app.slug, | |
| 55 | lines: [repo.description, `${repo.ownerName}/${repo.name}`], | |
| 56 | stat: app.access === "public" ? "open to anyone" : "sign-in required", | |
| 57 | }; | |
| 58 | } | |
| 59 | return undefined; | |
| 60 | } | |
| 61 | ||
| 62 | export function ogCard(ctx: Ctx): Response { | |
| 63 | const kind = ctx.params.kind ?? ""; | |
| 64 | const input = cardFor(ctx, kind, ctx.params.ref ?? ""); | |
| 65 | if (!input) return notFound(); | |
| 66 | const hash = new Bun.CryptoHasher("sha256").update(JSON.stringify(input)).digest("hex"); | |
| 67 | const etag = `"${hash}"`; | |
| 68 | const sent = ctx.request.headers.get("if-none-match") ?? ""; | |
| 69 | if (sent.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) | |
| 70 | return new Response(null, { status: 304, headers: { ...HEADERS, etag } }); | |
| 71 | let svg = cache.get(hash); | |
| 72 | if (svg === undefined) { | |
| 73 | svg = renderCard(input); | |
| 74 | if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value!); | |
| 75 | cache.set(hash, svg); | |
| 76 | } | |
| 77 | return new Response(svg, { headers: { ...HEADERS, etag } }); | |
| 78 | } |
test/og-route.test.ts added +88
| @@ -0,0 +1,88 @@ | ||
| 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 { createUser } from "../src/core/users.ts"; | |
| 9 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 10 | ||
| 11 | describe("og route", () => { | |
| 12 | let dir: string; | |
| 13 | let app: App; | |
| 14 | let servers: Servers; | |
| 15 | let base: string; | |
| 16 | const get = (path: string, headers: Record<string, string> = {}) => | |
| 17 | fetch(`${base}${path}`, { headers }); | |
| 18 | ||
| 19 | beforeAll(async () => { | |
| 20 | dir = await mkdtemp(join(tmpdir(), "forge-og-route-")); | |
| 21 | app = createApp({ dataDir: dir, port: 0 }); | |
| 22 | const alice = await createUser(app.db, { | |
| 23 | trusted: true, | |
| 24 | username: "alice", | |
| 25 | email: "[email protected]", | |
| 26 | password: "alice-passphrase", | |
| 27 | }); | |
| 28 | if (!alice.ok) throw new Error("user"); | |
| 29 | for (const [name, visibility] of [["open", "public"], ["secret", "private"]] as const) { | |
| 30 | const made = await createRepo(app, alice.value, { name, visibility, description: "A <b>bakery</b>" }); | |
| 31 | if (!made.ok) throw new Error("repo"); | |
| 32 | makeApp(app.db, { repoId: made.value.id, slug: name, access: "public" }); | |
| 33 | } | |
| 34 | servers = await serve(app); | |
| 35 | base = servers.url; | |
| 36 | }); | |
| 37 | afterAll(async () => { | |
| 38 | servers.stop(); | |
| 39 | await rm(dir, { recursive: true, force: true }); | |
| 40 | }); | |
| 41 | ||
| 42 | test("repo and app cards answer 200 with the security headers", async () => { | |
| 43 | for (const path of ["/og/repo/alice~open.svg", "/og/app/open.svg"]) { | |
| 44 | const res = await get(path); | |
| 45 | expect(res.status).toBe(200); | |
| 46 | expect(res.headers.get("content-type")).toStartWith("image/svg+xml"); | |
| 47 | expect(res.headers.get("cache-control")).toBe("public, max-age=300"); | |
| 48 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 49 | expect(res.headers.get("referrer-policy")).toBeTruthy(); | |
| 50 | expect(res.headers.get("content-security-policy")).toContain("default-src 'none'"); | |
| 51 | const svg = await res.text(); | |
| 52 | expect(svg.startsWith("<svg ")).toBe(true); | |
| 53 | expect(svg).not.toContain("<b>"); | |
| 54 | } | |
| 55 | }); | |
| 56 | ||
| 57 | test("private, unknown kind and bad refs are 404", async () => { | |
| 58 | for (const path of [ | |
| 59 | "/og/repo/alice~secret.svg", | |
| 60 | "/og/app/secret.svg", | |
| 61 | "/og/repo/alice~nope.svg", | |
| 62 | "/og/issue/alice~open.svg", | |
| 63 | "/og/repo/alice.svg", | |
| 64 | "/og/repo/alice~open~x.svg", | |
| 65 | "/og/repo/..~open.svg", | |
| 66 | "/og/app/bad%20slug.svg", | |
| 67 | ]) { | |
| 68 | expect((await get(path)).status).toBe(404); | |
| 69 | } | |
| 70 | }); | |
| 71 | ||
| 72 | test("ETag and If-None-Match give a 304", async () => { | |
| 73 | const first = await get("/og/repo/alice~open.svg"); | |
| 74 | const etag = first.headers.get("etag")!; | |
| 75 | expect(etag).toMatch(/^"[0-9a-f]{64}"$/); | |
| 76 | const again = await get("/og/repo/alice~open.svg", { "if-none-match": etag }); | |
| 77 | expect(again.status).toBe(304); | |
| 78 | expect(again.headers.get("etag")).toBe(etag); | |
| 79 | expect((await get("/og/repo/alice~open.svg", { "if-none-match": '"x"' })).status).toBe(200); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a warm request is fast", async () => { | |
| 83 | await get("/og/app/open.svg"); | |
| 84 | const t = performance.now(); | |
| 85 | await get("/og/app/open.svg"); | |
| 86 | expect(performance.now() - t).toBeLessThan(50); | |
| 87 | }); | |
| 88 | }); |
new above
offline