Public: anyone can read this; the crew can change it.
The app template ships the website specification by default #2936
scout/forge:scout/2916-the-app-template-ships-the-website-speci → main 1 commit fork
1 file
changed +549
−18
src/apps/scaffold.ts +549 −18
| @@ -67,6 +67,8 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] { | ||
| 67 | 67 | { path: "src/http.ts", content: HTTP_TS }, |
| 68 | 68 | { path: "src/mcp.ts", content: MCP_TS }, |
| 69 | 69 | { path: "src/page.ts", content: PAGE_TS }, |
| 70 | { path: "src/site.ts", content: SITE_TS }, | |
| 71 | { path: "src/compress.ts", content: COMPRESS_TS }, | |
| 70 | 72 | { path: "src/tokens.ts", content: TOKENS_TS }, |
| 71 | 73 | { path: "src/openapi.ts", content: OPENAPI_TS }, |
| 72 | 74 | { path: "src/routes.ts", content: ROUTES_TS }, |
| @@ -87,6 +89,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] { | ||
| 87 | 89 | { path: "src/audit.test.ts", content: AUDIT_TEST }, |
| 88 | 90 | { path: "src/openapi.test.ts", content: OPENAPI_TEST }, |
| 89 | 91 | { path: "src/design.test.ts", content: DESIGN_TEST }, |
| 92 | { path: "src/site.test.ts", content: SITE_TEST }, | |
| 90 | 93 | ]; |
| 91 | 94 | } |
| 92 | 95 | |
| @@ -169,6 +172,8 @@ decide nothing themselves. \`AGENTS.md\` says how to add to it. | ||
| 169 | 172 | | \`src/routes.ts\` | every path, in one table, each API route described beside it | |
| 170 | 173 | | \`src/openapi.ts\` | the routes as OpenAPI; committed at \`contract/openapi.json\` | |
| 171 | 174 | | \`src/page.ts\` | the HTML, rendered on the server, with its share metadata | |
| 175 | | \`src/site.ts\` | icon, manifest, card, sitemap, llms.txt, structured data | | |
| 176 | | \`src/compress.ts\` | gzip for text responses | | |
| 172 | 177 | | \`design/tokens.json\`, \`src/tokens.ts\` | the look as data, light and dark; compiled to \`/tokens.css\` | |
| 173 | 178 | | \`src/http.ts\` | the floor: headers, body cap, files | |
| 174 | 179 | | \`src/server.ts\` | boot: open the database, serve | |
| @@ -197,9 +202,25 @@ decide nothing themselves. \`AGENTS.md\` says how to add to it. | ||
| 197 | 202 | light and dark; nothing else spells out a colour (\`bun run lint:design\`), |
| 198 | 203 | and every pair a person reads meets 4.5:1 in both themes. |
| 199 | 204 | - **The open web.** A shared link unfurls (description, Open Graph, a |
| 200 | card); \`/robots.txt\` keeps crawlers to the page, and out of previews | |
| 201 | entirely; \`/.well-known/security.txt\` sends a reporter to the forge | |
| 202 | that runs the app. | |
| 205 | large generated card at \`/og.png\`); every page names its canonical | |
| 206 | address and carries \`WebSite\` structured data; there is an icon | |
| 207 | (\`/icon.svg\`), a 180px home-screen icon and a manifest; \`/sitemap.xml\` | |
| 208 | and \`/llms.txt\` describe the site; \`/robots.txt\` keeps crawlers to the | |
| 209 | page (and names the sitemap), and out of previews entirely; | |
| 210 | \`/.well-known/security.txt\` sends a reporter to the forge that runs the | |
| 211 | app. A missing page and a failure are the app's own page, with the right | |
| 212 | status. HSTS covers subdomains and is never a preload promise. | |
| 213 | - **Reachable.** A skip link and \`<main id="main">\`, forced-colours | |
| 214 | styles, and one \`<h1>\` with no skipped level (\`src/site.test.ts\` holds | |
| 215 | all of it). | |
| 216 | - **Small on the wire.** \`src/compress.ts\` gzips text of a kilobyte or | |
| 217 | more for browsers that read gzip (never the event stream); a proxy in | |
| 218 | front that compresses sees \`content-encoding\` and leaves it alone. | |
| 219 | - **Left to the owner.** Telling AI crawlers what they may do, content | |
| 220 | signals, an agent card and \`.md\` versions of pages are decisions about | |
| 221 | who may read the site and for what; the template makes none of them. | |
| 222 | Decide, then add them (and a test) deliberately. The card and icons are | |
| 223 | flat shapes in the accent colour, not a drawn logo: swap in your own. | |
| 203 | 224 | |
| 204 | 225 | ## Who you are |
| 205 | 226 | |
| @@ -1345,7 +1366,8 @@ import { env, publicOrigin } from "./env.ts"; | ||
| 1345 | 1366 | // Scripts and styles come from this origin (inline styles allowed, inline |
| 1346 | 1367 | // scripts not), nothing frames us, browsers never guess a content type, and |
| 1347 | 1368 | // referrers stay on this site. Once served over https, always: browsers |
| 1348 | // remember for a year. Anything but production asks not to be indexed: a | |
| 1369 | // remember for a year, subdomains too (never preloaded: that is a promise | |
| 1370 | // the owner makes, not a template). Anything but production asks not to be indexed: a | |
| 1349 | 1371 | // preview is a draft, and its address goes away with its pull. |
| 1350 | 1372 | export const SECURITY: Record<string, string> = { |
| 1351 | 1373 | "content-security-policy": |
| @@ -1354,7 +1376,7 @@ export const SECURITY: Record<string, string> = { | ||
| 1354 | 1376 | "referrer-policy": "strict-origin-when-cross-origin", |
| 1355 | 1377 | "permissions-policy": "camera=(), microphone=(), geolocation=()", |
| 1356 | 1378 | ...(publicOrigin.startsWith("https:") |
| 1357 | ? { "strict-transport-security": "max-age=31536000" } | |
| 1379 | ? { "strict-transport-security": "max-age=31536000; includeSubDomains" } | |
| 1358 | 1380 | : {}), |
| 1359 | 1381 | ...(env === "production" ? {} : { "x-robots-tag": "noindex" }), |
| 1360 | 1382 | }; |
| @@ -1677,15 +1699,24 @@ import { | ||
| 1677 | 1699 | where, |
| 1678 | 1700 | } from "./env.ts"; |
| 1679 | 1701 | import { asset, escape } from "./http.ts"; |
| 1702 | import { CARD, websiteLd } from "./site.ts"; | |
| 1680 | 1703 | import { token, tokensHref } from "./tokens.ts"; |
| 1681 | 1704 | import type { Who } from "./who.ts"; |
| 1682 | 1705 | |
| 1683 | 1706 | /** |
| 1684 | 1707 | * The frame every page shares: the tokens and the look, who you are, and |
| 1685 | 1708 | * what a link to the page says when it is shared — a title, a sentence |
| 1686 | * and the address, for Open Graph and the card a chat app unfurls. | |
| 1709 | * and the address, for Open Graph and the card a chat app unfurls. A page | |
| 1710 | * that is not a place to land (an error) says \`indexable = false\`: no | |
| 1711 | * canonical address, no structured data, and a request to stay out of | |
| 1712 | * search. | |
| 1687 | 1713 | */ |
| 1688 | export function layout(body: string, who: Who, path = "/"): string { | |
| 1714 | export function layout( | |
| 1715 | body: string, | |
| 1716 | who: Who, | |
| 1717 | path = "/", | |
| 1718 | indexable = true, | |
| 1719 | ): string { | |
| 1689 | 1720 | const door = |
| 1690 | 1721 | who.role === "anon" |
| 1691 | 1722 | ? \`<a class="button button-quiet" href="/signin">Sign in</a>\` |
| @@ -1698,22 +1729,36 @@ export function layout(body: string, who: Who, path = "/"): string { | ||
| 1698 | 1729 | <meta name="color-scheme" content="light dark"> |
| 1699 | 1730 | <meta name="theme-color" content="\${token("color-bg")}" media="(prefers-color-scheme: light)"> |
| 1700 | 1731 | <meta name="theme-color" content="\${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)"> |
| 1701 | <link rel="icon" href="data:,"> | |
| 1732 | <link rel="icon" href="/icon.svg" type="image/svg+xml"> | |
| 1733 | <link rel="apple-touch-icon" href="/apple-touch-icon.png"> | |
| 1734 | <link rel="manifest" href="/manifest.webmanifest"> | |
| 1702 | 1735 | <title>\${escape(title)}</title> |
| 1703 | 1736 | <meta name="description" content="\${escape(description)}"> |
| 1737 | \${ | |
| 1738 | indexable | |
| 1739 | ? \`<link rel="canonical" href="\${escape(publicOrigin + path)}">\` | |
| 1740 | : \`<meta name="robots" content="noindex">\` | |
| 1741 | } | |
| 1704 | 1742 | <meta property="og:type" content="website"> |
| 1705 | 1743 | <meta property="og:site_name" content="\${escape(title)}"> |
| 1706 | 1744 | <meta property="og:title" content="\${escape(title)}"> |
| 1707 | 1745 | <meta property="og:description" content="\${escape(description)}"> |
| 1708 | 1746 | <meta property="og:url" content="\${escape(publicOrigin + path)}"> |
| 1709 | <meta name="twitter:card" content="summary"> | |
| 1747 | <meta property="og:image" content="\${escape(publicOrigin)}/og.png"> | |
| 1748 | <meta property="og:image:width" content="\${CARD.width}"> | |
| 1749 | <meta property="og:image:height" content="\${CARD.height}"> | |
| 1750 | <meta property="og:image:alt" content="\${escape(title)}"> | |
| 1751 | <meta name="twitter:card" content="summary_large_image"> | |
| 1752 | <meta name="twitter:image" content="\${escape(publicOrigin)}/og.png"> | |
| 1710 | 1753 | <meta name="twitter:title" content="\${escape(title)}"> |
| 1711 | 1754 | <meta name="twitter:description" content="\${escape(description)}"> |
| 1755 | \${indexable ? \`<script type="application/ld+json">\${websiteLd(title, description, publicOrigin)}</script>\` : ""} | |
| 1712 | 1756 | <link rel="stylesheet" href="\${tokensHref}"> |
| 1713 | 1757 | <link rel="stylesheet" href="\${asset("app.css")}"> |
| 1714 | 1758 | <script defer src="\${asset("beacon.js")}"></script> |
| 1715 | 1759 | <script type="module" src="\${asset("live.js")}"></script> |
| 1716 | 1760 | <body> |
| 1761 | <a class="skip" href="#main">Skip to content</a> | |
| 1717 | 1762 | <div class="page"> |
| 1718 | 1763 | <header class="head"> |
| 1719 | 1764 | <div> |
| @@ -1725,7 +1770,7 @@ export function layout(body: string, who: Who, path = "/"): string { | ||
| 1725 | 1770 | \${door} |
| 1726 | 1771 | </nav> |
| 1727 | 1772 | </header> |
| 1728 | <main>\${body}</main> | |
| 1773 | <main id="main" tabindex="-1">\${body}</main> | |
| 1729 | 1774 | <footer class="muted"> |
| 1730 | 1775 | \${ssh === undefined ? "" : \`<p>Terminal: <code>\${escape(ssh)}</code></p>\`} |
| 1731 | 1776 | <p>Also at <a href="/api/notes">/api/notes</a> (<a href="/openapi.json">described</a>) and <code>POST /mcp</code>, with the same rules.</p> |
| @@ -1737,6 +1782,26 @@ export function layout(body: string, who: Who, path = "/"): string { | ||
| 1737 | 1782 | \`; |
| 1738 | 1783 | } |
| 1739 | 1784 | |
| 1785 | /** The page for a refusal or a failure: the same frame, a plain word, a way back. */ | |
| 1786 | export function problem(status: 404 | 500, who: Who): string { | |
| 1787 | const [heading, sentence] = | |
| 1788 | status === 404 | |
| 1789 | ? ["Not found", "There is nothing at this address."] | |
| 1790 | : ["Something went wrong", "It was not you. Try again in a moment."]; | |
| 1791 | return layout( | |
| 1792 | \`<section class="card"> | |
| 1793 | <p>\${escape(sentence)}</p> | |
| 1794 | <p><a href="/">Back to \${escape(title)}</a></p> | |
| 1795 | </section>\`, | |
| 1796 | who, | |
| 1797 | "/", | |
| 1798 | false, | |
| 1799 | ).replace( | |
| 1800 | \`<h1>\${escape(title)}</h1>\`, | |
| 1801 | \`<h1>\${escape(heading)}</h1>\`, | |
| 1802 | ); | |
| 1803 | } | |
| 1804 | ||
| 1740 | 1805 | export function home(input: { |
| 1741 | 1806 | who: Who; |
| 1742 | 1807 | notes: readonly Note[]; |
| @@ -1814,7 +1879,7 @@ import { | ||
| 1814 | 1879 | type Failure, |
| 1815 | 1880 | type Result, |
| 1816 | 1881 | } from "./actions.ts"; |
| 1817 | import { commit, env, forgeUrl, startedAt, version } from "./env.ts"; | |
| 1882 | import { commit, env, forgeUrl, publicOrigin, startedAt, version } from "./env.ts"; | |
| 1818 | 1883 | import { |
| 1819 | 1884 | back, |
| 1820 | 1885 | cookie, |
| @@ -1832,6 +1897,7 @@ import { | ||
| 1832 | 1897 | import { events } from "./live.ts"; |
| 1833 | 1898 | import { rpc } from "./mcp.ts"; |
| 1834 | 1899 | import { home } from "./page.ts"; |
| 1900 | import { appleTouch, card, iconSvg, llmsTxt, manifest, sitemap } from "./site.ts"; | |
| 1835 | 1901 | import { |
| 1836 | 1902 | begin, |
| 1837 | 1903 | endSession, |
| @@ -1951,6 +2017,22 @@ const answer = <T>(result: Result<T>, status = 200): Response => | ||
| 1951 | 2017 | const done = <T>(result: Result<T>): Response => |
| 1952 | 2018 | result.ok ? back() : back(result.message); |
| 1953 | 2019 | |
| 2020 | const DAY = 86400; | |
| 2021 | ||
| 2022 | /** A generated file, with the floor and how long it may be kept. */ | |
| 2023 | const file = ( | |
| 2024 | body: string | Uint8Array, | |
| 2025 | type: string, | |
| 2026 | maxAge = 0, | |
| 2027 | ): Response => | |
| 2028 | new Response(body as BodyInit, { | |
| 2029 | headers: { | |
| 2030 | "content-type": type, | |
| 2031 | "cache-control": maxAge > 0 ? \`public, max-age=\${maxAge}\` : "no-cache", | |
| 2032 | ...SECURITY, | |
| 2033 | }, | |
| 2034 | }); | |
| 2035 | ||
| 1954 | 2036 | /** A whole number from the query, or undefined. */ |
| 1955 | 2037 | const whole = (value: string | null): number | undefined => |
| 1956 | 2038 | value !== null && /^\\d+$/.test(value) ? Number(value) : undefined; |
| @@ -2256,10 +2338,43 @@ export const routes: readonly Route[] = [ | ||
| 2256 | 2338 | handle: () => |
| 2257 | 2339 | text( |
| 2258 | 2340 | env === "production" |
| 2259 | ? "User-agent: *\\nDisallow: /api/\\nDisallow: /mcp\\nDisallow: /events\\nDisallow: /__forge/\\n" | |
| 2341 | ? \`User-agent: *\\nDisallow: /api/\\nDisallow: /mcp\\nDisallow: /events\\nDisallow: /__forge/\\n\\nSitemap: \${publicOrigin}/sitemap.xml\\n\` | |
| 2260 | 2342 | : "User-agent: *\\nDisallow: /\\n", |
| 2261 | 2343 | ), |
| 2262 | 2344 | }, |
| 2345 | { | |
| 2346 | method: "GET", | |
| 2347 | path: "/sitemap.xml", | |
| 2348 | handle: () => file(sitemap(), "application/xml; charset=utf-8"), | |
| 2349 | }, | |
| 2350 | { | |
| 2351 | method: "GET", | |
| 2352 | path: "/llms.txt", | |
| 2353 | handle: () => file(llmsTxt(), "text/plain; charset=utf-8"), | |
| 2354 | }, | |
| 2355 | // The app's face outside the page: the tab's icon, the home-screen icon | |
| 2356 | // and install manifest, and the card a shared link unfurls. Drawn from | |
| 2357 | // the tokens and the app's name, so they change when those do. | |
| 2358 | { | |
| 2359 | method: "GET", | |
| 2360 | path: "/icon.svg", | |
| 2361 | handle: () => file(iconSvg(), "image/svg+xml", DAY), | |
| 2362 | }, | |
| 2363 | { | |
| 2364 | method: "GET", | |
| 2365 | path: "/apple-touch-icon.png", | |
| 2366 | handle: () => file(appleTouch(), "image/png", DAY), | |
| 2367 | }, | |
| 2368 | { | |
| 2369 | method: "GET", | |
| 2370 | path: "/og.png", | |
| 2371 | handle: () => file(card(), "image/png", DAY), | |
| 2372 | }, | |
| 2373 | { | |
| 2374 | method: "GET", | |
| 2375 | path: "/manifest.webmanifest", | |
| 2376 | handle: () => file(manifest(), "application/manifest+json", DAY), | |
| 2377 | }, | |
| 2263 | 2378 | { |
| 2264 | 2379 | method: "GET", |
| 2265 | 2380 | path: "/.well-known/security.txt", |
| @@ -2315,6 +2430,373 @@ export function match( | ||
| 2315 | 2430 | } |
| 2316 | 2431 | `; |
| 2317 | 2432 | |
| 2433 | // What the web expects beyond the pages. | |
| 2434 | const SITE_TS = `/** | |
| 2435 | * What the web expects of a site beyond its pages, each drawn from the | |
| 2436 | * app's name and its tokens so nothing here is edited by hand: the icon, | |
| 2437 | * the home-screen icon and install manifest, the card a shared link | |
| 2438 | * unfurls, the sitemap, \`/llms.txt\` for agents that read, and the | |
| 2439 | * structured data a search engine reads from the page. Plain data in, | |
| 2440 | * a string or bytes out; \`routes.ts\` serves them. | |
| 2441 | * | |
| 2442 | * The cards are PNGs written here with \`node:zlib\`, since a link | |
| 2443 | * unfurler will not draw an SVG and a dependency to draw text is more | |
| 2444 | * than a starting point needs. They carry the app's colours and a mark, | |
| 2445 | * not its name; put a designed \`og.png\` in \`static/\` and point | |
| 2446 | * \`og:image\` at it when there is one. | |
| 2447 | */ | |
| 2448 | ||
| 2449 | import { deflateSync } from "node:zlib"; | |
| 2450 | import { description, publicOrigin, title } from "./env.ts"; | |
| 2451 | import { token } from "./tokens.ts"; | |
| 2452 | ||
| 2453 | /** The size a link card is drawn at, and what \`og:image:width\`/\`height\` say. */ | |
| 2454 | export const CARD = { width: 1200, height: 630 } as const; | |
| 2455 | ||
| 2456 | type Channels = readonly [number, number, number]; | |
| 2457 | ||
| 2458 | /** \`#rrggbb\` (the tokens' only colour form) as three bytes. */ | |
| 2459 | function channels(hex: string): Channels { | |
| 2460 | const m = /^#([0-9a-f]{6})$/i.exec(hex); | |
| 2461 | if (m === null) throw new Error(\`\${hex}: the site files need a #rrggbb token\`); | |
| 2462 | const n = parseInt(m[1]!, 16); | |
| 2463 | return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; | |
| 2464 | } | |
| 2465 | ||
| 2466 | /** The mark: the app's first letter, in the accent. */ | |
| 2467 | const letter = (): string => [...title][0]?.toUpperCase() ?? "A"; | |
| 2468 | ||
| 2469 | export const iconSvg = (): string => | |
| 2470 | \`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="\${token("color-accent")}"/><text x="32" y="45" text-anchor="middle" font-family="system-ui, sans-serif" font-size="38" font-weight="700" fill="\${token("color-accent-fg")}">\${xml(letter())}</text></svg>\\n\`; | |
| 2471 | ||
| 2472 | export const manifest = (): string => | |
| 2473 | JSON.stringify({ | |
| 2474 | name: title, | |
| 2475 | short_name: title.slice(0, 12), | |
| 2476 | description, | |
| 2477 | start_url: "/", | |
| 2478 | display: "standalone", | |
| 2479 | background_color: token("color-bg"), | |
| 2480 | theme_color: token("color-bg"), | |
| 2481 | icons: [ | |
| 2482 | { src: "/icon.svg", sizes: "any", type: "image/svg+xml" }, | |
| 2483 | { src: "/apple-touch-icon.png", sizes: "180x180", type: "image/png" }, | |
| 2484 | ], | |
| 2485 | }); | |
| 2486 | ||
| 2487 | export const sitemap = (): string => | |
| 2488 | \`<?xml version="1.0" encoding="UTF-8"?>\\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\\n <url><loc>\${xml(publicOrigin)}/</loc></url>\\n</urlset>\\n\`; | |
| 2489 | ||
| 2490 | /** \`/llms.txt\`: what the site is and where its machine-readable parts are, in the format llmstxt.org describes. */ | |
| 2491 | export const llmsTxt = (): string => | |
| 2492 | \`# \${oneLine(title)}\\n\\n> \${oneLine(description)}\\n\\n## Pages\\n\\n- [Home](\${publicOrigin}/): the notes, and who may add them\\n\\n## For programs\\n\\n- [API description](\${publicOrigin}/openapi.json): every endpoint, as OpenAPI\\n- [MCP endpoint](\${publicOrigin}/mcp): the same actions as tools, POST JSON-RPC\\n- [Health](\${publicOrigin}/healthz): whether the app is up\\n\`; | |
| 2493 | ||
| 2494 | /** The page as a \`WebSite\`, for a \`<script type="application/ld+json">\`. A \`<\` cannot close the tag: it is written \\\\u003c. */ | |
| 2495 | export const websiteLd = (name: string, about: string, origin: string): string => | |
| 2496 | JSON.stringify({ | |
| 2497 | "@context": "https://schema.org", | |
| 2498 | "@type": "WebSite", | |
| 2499 | name, | |
| 2500 | description: about, | |
| 2501 | url: \`\${origin}/\`, | |
| 2502 | }).replace(/</g, "\\\\u003c"); | |
| 2503 | ||
| 2504 | /** The 180px icon iOS puts on a home screen. */ | |
| 2505 | export const appleTouch = (): Uint8Array => cached("apple", () => draw(180, 180, "icon")); | |
| 2506 | ||
| 2507 | /** The card a shared link unfurls. */ | |
| 2508 | export const card = (): Uint8Array => cached("card", () => draw(CARD.width, CARD.height, "card")); | |
| 2509 | ||
| 2510 | const made = new Map<string, Uint8Array>(); | |
| 2511 | function cached(key: string, make: () => Uint8Array): Uint8Array { | |
| 2512 | let bytes = made.get(key); | |
| 2513 | if (bytes === undefined) made.set(key, (bytes = make())); | |
| 2514 | return bytes; | |
| 2515 | } | |
| 2516 | ||
| 2517 | const xml = (s: string): string => | |
| 2518 | s.replace(/[&<>"']/g, (c) => \`&#\${c.charCodeAt(0)};\`); | |
| 2519 | const oneLine = (s: string): string => s.replace(/\\s+/g, " ").trim(); | |
| 2520 | ||
| 2521 | /** A flat PNG: the accent, with the accent's foreground as a mark at the middle (a square frame with a block inside). */ | |
| 2522 | function draw(w: number, h: number, kind: "icon" | "card"): Uint8Array { | |
| 2523 | const bg = channels(token("color-accent")); | |
| 2524 | const fg = channels(token("color-accent-fg")); | |
| 2525 | const side = Math.round(Math.min(w, h) * (kind === "icon" ? 0.5 : 0.4)); | |
| 2526 | const x0 = Math.round((w - side) / 2); | |
| 2527 | const y0 = Math.round((h - side) / 2); | |
| 2528 | const edge = Math.max(2, Math.round(side / 10)); | |
| 2529 | const row = 1 + w * 3; | |
| 2530 | const raw = new Uint8Array(row * h); | |
| 2531 | for (let y = 0; y < h; y++) { | |
| 2532 | for (let x = 0; x < w; x++) { | |
| 2533 | const inside = x >= x0 && x < x0 + side && y >= y0 && y < y0 + side; | |
| 2534 | const ring = | |
| 2535 | inside && | |
| 2536 | (x < x0 + edge || x >= x0 + side - edge || y < y0 + edge || y >= y0 + side - edge); | |
| 2537 | const block = | |
| 2538 | inside && x >= x0 + 3 * edge && x < x0 + side - 3 * edge && y >= y0 + 3 * edge && y < y0 + side - 3 * edge; | |
| 2539 | const c = ring || block ? fg : bg; | |
| 2540 | raw.set(c, y * row + 1 + x * 3); | |
| 2541 | } | |
| 2542 | } | |
| 2543 | const header = new Uint8Array(13); | |
| 2544 | const view = new DataView(header.buffer); | |
| 2545 | view.setUint32(0, w); | |
| 2546 | view.setUint32(4, h); | |
| 2547 | header.set([8, 2, 0, 0, 0], 8); // 8-bit, truecolour, no interlace | |
| 2548 | return join([ | |
| 2549 | Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10), | |
| 2550 | chunk("IHDR", header), | |
| 2551 | chunk("IDAT", deflateSync(raw)), | |
| 2552 | chunk("IEND", new Uint8Array(0)), | |
| 2553 | ]); | |
| 2554 | } | |
| 2555 | ||
| 2556 | const TABLE = Array.from({ length: 256 }, (_, n) => { | |
| 2557 | let c = n; | |
| 2558 | for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; | |
| 2559 | return c >>> 0; | |
| 2560 | }); | |
| 2561 | function crc(bytes: Uint8Array): number { | |
| 2562 | let c = 0xffffffff; | |
| 2563 | for (const b of bytes) c = TABLE[(c ^ b) & 255]! ^ (c >>> 8); | |
| 2564 | return (c ^ 0xffffffff) >>> 0; | |
| 2565 | } | |
| 2566 | function chunk(type: string, data: Uint8Array): Uint8Array { | |
| 2567 | const body = join([new TextEncoder().encode(type), data]); | |
| 2568 | const out = new Uint8Array(8 + data.length + 4); | |
| 2569 | const view = new DataView(out.buffer); | |
| 2570 | view.setUint32(0, data.length); | |
| 2571 | out.set(body, 4); | |
| 2572 | view.setUint32(8 + data.length, crc(body)); | |
| 2573 | return out; | |
| 2574 | } | |
| 2575 | function join(parts: Uint8Array[]): Uint8Array { | |
| 2576 | const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); | |
| 2577 | let at = 0; | |
| 2578 | for (const p of parts) { | |
| 2579 | out.set(p, at); | |
| 2580 | at += p.length; | |
| 2581 | } | |
| 2582 | return out; | |
| 2583 | } | |
| 2584 | `; | |
| 2585 | ||
| 2586 | // Smaller on the wire. | |
| 2587 | const COMPRESS_TS = `/** | |
| 2588 | * Compression, in the app, so a deploy that no proxy sits in front of is | |
| 2589 | * still small on the wire. A response is gzipped when the person's browser | |
| 2590 | * said it reads gzip, the body is text (HTML, CSS, JS, JSON, XML, SVG) | |
| 2591 | * and is worth the trouble (1 KiB or more). The event stream is never | |
| 2592 | * touched — it must reach the browser as it is written — and neither is | |
| 2593 | * anything already encoded. A proxy that compresses for itself sees | |
| 2594 | * \`content-encoding\` and leaves the body alone. | |
| 2595 | */ | |
| 2596 | ||
| 2597 | /** The least body worth compressing; below it the headers outweigh the gain. */ | |
| 2598 | export const MIN_BYTES = 1024; | |
| 2599 | ||
| 2600 | const TEXTUAL = /^(text\\/(?!event-stream)|application\\/([\\w.+-]*json|xml|javascript)|image\\/svg\\+xml)/i; | |
| 2601 | ||
| 2602 | export async function compress( | |
| 2603 | request: Request, | |
| 2604 | response: Response, | |
| 2605 | ): Promise<Response> { | |
| 2606 | const type = response.headers.get("content-type") ?? ""; | |
| 2607 | if ( | |
| 2608 | request.method !== "GET" || | |
| 2609 | response.body === null || | |
| 2610 | response.headers.has("content-encoding") || | |
| 2611 | !/\\bgzip\\b/i.test(request.headers.get("accept-encoding") ?? "") || | |
| 2612 | !TEXTUAL.test(type) | |
| 2613 | ) | |
| 2614 | return response; | |
| 2615 | const headers = new Headers(response.headers); | |
| 2616 | headers.append("vary", "accept-encoding"); | |
| 2617 | const bytes = new Uint8Array(await response.arrayBuffer()); | |
| 2618 | if (bytes.length < MIN_BYTES || response.status === 206) | |
| 2619 | return new Response(bytes, { status: response.status, headers }); | |
| 2620 | headers.set("content-encoding", "gzip"); | |
| 2621 | headers.delete("content-length"); | |
| 2622 | return new Response(Bun.gzipSync(bytes), { status: response.status, headers }); | |
| 2623 | } | |
| 2624 | `; | |
| 2625 | ||
| 2626 | // The specification, held. | |
| 2627 | const SITE_TEST = `/** | |
| 2628 | * The specification a site is held to, as the template keeps it: the head | |
| 2629 | * a crawler and a chat app read, the files they ask for, the pages that | |
| 2630 | * are not the page, and the shape of the headings. A generated app | |
| 2631 | * inherits every one of these and fails its own \`bun test\` if it loses one. | |
| 2632 | */ | |
| 2633 | import { afterAll, expect, test } from "bun:test"; | |
| 2634 | import { mkdtempSync, readFileSync } from "node:fs"; | |
| 2635 | import { tmpdir } from "node:os"; | |
| 2636 | import { join } from "node:path"; | |
| 2637 | import { compress, MIN_BYTES } from "./compress.ts"; | |
| 2638 | import { env, publicOrigin, title } from "./env.ts"; | |
| 2639 | import { SECURITY } from "./http.ts"; | |
| 2640 | import { problem } from "./page.ts"; | |
| 2641 | import { CARD, websiteLd } from "./site.ts"; | |
| 2642 | import { serve } from "./server.ts"; | |
| 2643 | import { ANON } from "./who.ts"; | |
| 2644 | ||
| 2645 | const server = serve({ | |
| 2646 | port: 0, | |
| 2647 | dataDir: mkdtempSync(join(tmpdir(), "app-")), | |
| 2648 | identityKey: "a-key-only-the-forge-holds", | |
| 2649 | }); | |
| 2650 | const base = \`http://\${server.hostname}:\${server.port}\`; | |
| 2651 | afterAll(() => server.stop(true)); | |
| 2652 | const get = (path: string, headers: Record<string, string> = {}) => | |
| 2653 | fetch(base + path, { headers, redirect: "manual" }); | |
| 2654 | ||
| 2655 | /** The heading levels in a page, in order. */ | |
| 2656 | const levels = (page: string): number[] => | |
| 2657 | [...page.matchAll(/<h([1-6])[\\s>]/g)].map((m) => Number(m[1])); | |
| 2658 | ||
| 2659 | /** One h1, and no level skipped on the way down: what a screen reader's outline needs. */ | |
| 2660 | const outlineProblems = (page: string): string[] => { | |
| 2661 | const all = levels(page); | |
| 2662 | const problems: string[] = []; | |
| 2663 | if (all.filter((n) => n === 1).length !== 1) | |
| 2664 | problems.push("a page has exactly one h1"); | |
| 2665 | all.forEach((n, i) => { | |
| 2666 | if (n > (all[i - 1] ?? 0) + 1) problems.push(\`h\${n} follows h\${all[i - 1] ?? 0}\`); | |
| 2667 | }); | |
| 2668 | return problems; | |
| 2669 | }; | |
| 2670 | ||
| 2671 | test("the head says where the page lives, what it looks like and what it is", async () => { | |
| 2672 | const page = await (await get("/")).text(); | |
| 2673 | expect(page).toContain(\`<link rel="canonical" href="\${publicOrigin}/">\`); | |
| 2674 | expect(page).toContain('<link rel="icon" href="/icon.svg" type="image/svg+xml">'); | |
| 2675 | expect(page).toContain('<link rel="apple-touch-icon" href="/apple-touch-icon.png">'); | |
| 2676 | expect(page).toContain('<link rel="manifest" href="/manifest.webmanifest">'); | |
| 2677 | expect(page).not.toContain('href="data:,"'); | |
| 2678 | expect(page).toContain(\`<meta property="og:image" content="\${publicOrigin}/og.png">\`); | |
| 2679 | expect(page).toContain(\`<meta property="og:image:width" content="\${CARD.width}">\`); | |
| 2680 | expect(page).toContain('<meta name="twitter:card" content="summary_large_image">'); | |
| 2681 | const ld = /<script type="application\\/ld\\+json">(.*?)<\\/script>/s.exec(page)?.[1]; | |
| 2682 | expect(JSON.parse(ld ?? "null")).toMatchObject({ | |
| 2683 | "@type": "WebSite", | |
| 2684 | name: title, | |
| 2685 | url: \`\${publicOrigin}/\`, | |
| 2686 | }); | |
| 2687 | }); | |
| 2688 | ||
| 2689 | test("structured data cannot close its own tag", () => { | |
| 2690 | const out = websiteLd("</script><b>", "a & b", "https://x.test"); | |
| 2691 | expect(out).not.toContain("<"); | |
| 2692 | expect(JSON.parse(out).name).toBe("</script><b>"); | |
| 2693 | }); | |
| 2694 | ||
| 2695 | test("the first stop for a keyboard skips to the main landmark", async () => { | |
| 2696 | const page = await (await get("/")).text(); | |
| 2697 | expect(page.indexOf('<a class="skip" href="#main">')).toBeLessThan(page.indexOf("<header")); | |
| 2698 | expect(page).toContain('<main id="main" tabindex="-1">'); | |
| 2699 | const css = readFileSync(join(import.meta.dir, "..", "static", "app.css"), "utf8"); | |
| 2700 | expect(css).toContain("@media (forced-colors: active)"); | |
| 2701 | }); | |
| 2702 | ||
| 2703 | test("the icon, the home-screen icon, the manifest and the card are real files", async () => { | |
| 2704 | const svg = await get("/icon.svg"); | |
| 2705 | expect(svg.headers.get("content-type")).toBe("image/svg+xml"); | |
| 2706 | expect(await svg.text()).toStartWith("<svg "); | |
| 2707 | const size = async (path: string) => { | |
| 2708 | const r = await get(path); | |
| 2709 | expect(r.status).toBe(200); | |
| 2710 | expect(r.headers.get("content-type")).toBe("image/png"); | |
| 2711 | expect(r.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 2712 | const b = new Uint8Array(await r.arrayBuffer()); | |
| 2713 | expect([...b.slice(0, 8)]).toEqual([137, 80, 78, 71, 13, 10, 26, 10]); | |
| 2714 | const view = new DataView(b.buffer); | |
| 2715 | return [view.getUint32(16), view.getUint32(20)]; | |
| 2716 | }; | |
| 2717 | expect(await size("/apple-touch-icon.png")).toEqual([180, 180]); | |
| 2718 | expect(await size("/og.png")).toEqual([CARD.width, CARD.height]); | |
| 2719 | const m = await (await get("/manifest.webmanifest")).json(); | |
| 2720 | expect(m).toMatchObject({ name: title, start_url: "/" }); | |
| 2721 | expect(m.icons.map((i: { src: string }) => i.src)).toContain("/apple-touch-icon.png"); | |
| 2722 | }); | |
| 2723 | ||
| 2724 | test("sitemap.xml lists the page, robots.txt points at it where crawlers are welcome, llms.txt introduces the site", async () => { | |
| 2725 | const sitemap = await (await get("/sitemap.xml")).text(); | |
| 2726 | expect(sitemap).toContain(\`<loc>\${publicOrigin}/</loc>\`); | |
| 2727 | expect((await get("/sitemap.xml")).headers.get("content-type")).toContain("xml"); | |
| 2728 | const robots = await (await get("/robots.txt")).text(); | |
| 2729 | if (env === "production") expect(robots).toContain(\`Sitemap: \${publicOrigin}/sitemap.xml\\n\`); | |
| 2730 | else expect(robots).not.toContain("Sitemap:"); | |
| 2731 | const llms = await get("/llms.txt"); | |
| 2732 | expect(llms.headers.get("content-type")).toContain("text/plain"); | |
| 2733 | const body = await llms.text(); | |
| 2734 | expect(body).toStartWith(\`# \${title}\\n\\n> \`); | |
| 2735 | expect(body).toContain(\`(\${publicOrigin}/openapi.json)\`); | |
| 2736 | }); | |
| 2737 | ||
| 2738 | test("HSTS covers subdomains and is never a preload promise", () => { | |
| 2739 | const hsts = SECURITY["strict-transport-security"]; | |
| 2740 | if (publicOrigin.startsWith("https:")) { | |
| 2741 | expect(hsts).toContain("includeSubDomains"); | |
| 2742 | expect(hsts).not.toContain("preload"); | |
| 2743 | } else expect(hsts).toBeUndefined(); | |
| 2744 | }); | |
| 2745 | ||
| 2746 | test("a missing page is the app's own page with a 404, and a script gets the word", async () => { | |
| 2747 | const browser = await get("/no/such/page", { accept: "text/html,*/*" }); | |
| 2748 | expect(browser.status).toBe(404); | |
| 2749 | expect(browser.headers.get("content-type")).toContain("text/html"); | |
| 2750 | expect(browser.headers.get("content-security-policy")).not.toBeNull(); | |
| 2751 | const page = await browser.text(); | |
| 2752 | expect(page).toContain("<h1>Not found</h1>"); | |
| 2753 | expect(page).toContain('<meta name="robots" content="noindex">'); | |
| 2754 | expect(page).not.toContain('rel="canonical"'); | |
| 2755 | expect(outlineProblems(page)).toEqual([]); | |
| 2756 | const script = await get("/no/such/page", { accept: "application/json" }); | |
| 2757 | expect(script.status).toBe(404); | |
| 2758 | expect(await script.text()).toBe("not found"); | |
| 2759 | }); | |
| 2760 | ||
| 2761 | test("a failure is the same frame with nothing of the cause in it", () => { | |
| 2762 | const page = problem(500, ANON); | |
| 2763 | expect(page).toContain("<h1>Something went wrong</h1>"); | |
| 2764 | expect(page).toContain('<meta name="robots" content="noindex">'); | |
| 2765 | expect(outlineProblems(page)).toEqual([]); | |
| 2766 | }); | |
| 2767 | ||
| 2768 | test("the home page has one h1 and no skipped level", async () => { | |
| 2769 | expect(outlineProblems(await (await get("/")).text())).toEqual([]); | |
| 2770 | expect(outlineProblems("<h1>a</h1><h3>b</h3>")).toEqual(["h3 follows h1"]); | |
| 2771 | expect(outlineProblems("<h2>a</h2>")).toContain("a page has exactly one h1"); | |
| 2772 | }); | |
| 2773 | ||
| 2774 | test("text over a kilobyte is gzipped for a browser that reads gzip, and nothing else is touched", async () => { | |
| 2775 | const big = "x".repeat(MIN_BYTES * 2); | |
| 2776 | const ask = (encoding?: string) => | |
| 2777 | new Request("http://x.test/", encoding ? { headers: { "accept-encoding": encoding } } : {}); | |
| 2778 | const html = () => new Response(big, { headers: { "content-type": "text/html" } }); | |
| 2779 | const squeezed = await compress(ask("gzip, br"), html()); | |
| 2780 | expect(squeezed.headers.get("content-encoding")).toBe("gzip"); | |
| 2781 | expect(squeezed.headers.get("vary")).toContain("accept-encoding"); | |
| 2782 | expect(Bun.gunzipSync(new Uint8Array(await squeezed.arrayBuffer()))).toEqual(new TextEncoder().encode(big)); | |
| 2783 | // Not asked for, too small, a stream, or an image: as they were. | |
| 2784 | expect((await compress(ask(), html())).headers.get("content-encoding")).toBeNull(); | |
| 2785 | const small = new Response("tiny", { headers: { "content-type": "text/html" } }); | |
| 2786 | expect(await (await compress(ask("gzip"), small)).text()).toBe("tiny"); | |
| 2787 | const stream = new Response(big, { headers: { "content-type": "text/event-stream" } }); | |
| 2788 | expect((await compress(ask("gzip"), stream)).headers.get("content-encoding")).toBeNull(); | |
| 2789 | const png = new Response(big, { headers: { "content-type": "image/png" } }); | |
| 2790 | expect((await compress(ask("gzip"), png)).headers.get("content-encoding")).toBeNull(); | |
| 2791 | }); | |
| 2792 | ||
| 2793 | test("the server compresses the page on the way out", async () => { | |
| 2794 | const r = await get("/static/app.css", { "accept-encoding": "gzip" }); | |
| 2795 | expect(r.headers.get("vary")).toContain("accept-encoding"); | |
| 2796 | expect((await r.text()).includes(".button")).toBe(true); | |
| 2797 | }); | |
| 2798 | `; | |
| 2799 | ||
| 2318 | 2800 | // Boot. |
| 2319 | 2801 | const SERVER_TS = `/** |
| 2320 | 2802 | * The process the forge runs. \`serve\` opens the database and listens: |
| @@ -2334,11 +2816,13 @@ import { | ||
| 2334 | 2816 | title, |
| 2335 | 2817 | where, |
| 2336 | 2818 | } from "./env.ts"; |
| 2819 | import { compress } from "./compress.ts"; | |
| 2337 | 2820 | import { html, text } from "./http.ts"; |
| 2821 | import { problem } from "./page.ts"; | |
| 2338 | 2822 | import { match } from "./routes.ts"; |
| 2339 | 2823 | import { door } from "./security.ts"; |
| 2340 | 2824 | import { ensureClient, sessionWho, type Signin } from "./signin.ts"; |
| 2341 | import { who } from "./who.ts"; | |
| 2825 | import { ANON, who } from "./who.ts"; | |
| 2342 | 2826 | |
| 2343 | 2827 | export interface ServeOptions { |
| 2344 | 2828 | readonly port: number; |
| @@ -2375,12 +2859,23 @@ export function serve(options: ServeOptions) { | ||
| 2375 | 2859 | me, |
| 2376 | 2860 | server.requestIP(request)?.address ?? "?", |
| 2377 | 2861 | ); |
| 2378 | if (refused !== undefined) return head(request, refused); | |
| 2862 | if (refused !== undefined) | |
| 2863 | return head(request, await compress(request, refused)); | |
| 2379 | 2864 | const found = match( |
| 2380 | 2865 | request.method === "HEAD" ? "GET" : request.method, |
| 2381 | 2866 | url.pathname, |
| 2382 | 2867 | ); |
| 2383 | if (found === undefined) return text("not found", 404); | |
| 2868 | // A browser is shown the app's own page; a script gets the word. | |
| 2869 | if (found === undefined) | |
| 2870 | return head( | |
| 2871 | request, | |
| 2872 | await compress( | |
| 2873 | request, | |
| 2874 | (request.headers.get("accept") ?? "").includes("text/html") | |
| 2875 | ? html(problem(404, me), 404) | |
| 2876 | : text("not found", 404), | |
| 2877 | ), | |
| 2878 | ); | |
| 2384 | 2879 | const response = await found.route.handle({ |
| 2385 | 2880 | request, |
| 2386 | 2881 | url, |
| @@ -2389,7 +2884,7 @@ export function serve(options: ServeOptions) { | ||
| 2389 | 2884 | params: found.params, |
| 2390 | 2885 | signin: options.signin, |
| 2391 | 2886 | }); |
| 2392 | return head(request, response); | |
| 2887 | return head(request, await compress(request, response)); | |
| 2393 | 2888 | }, |
| 2394 | 2889 | // A bug answers with the floor and nothing else: never the runtime's |
| 2395 | 2890 | // own error page, which carries source and paths, and never without |
| @@ -2397,7 +2892,11 @@ export function serve(options: ServeOptions) { | ||
| 2397 | 2892 | error(error) { |
| 2398 | 2893 | // Inside the generated app, which has no forge log module. |
| 2399 | 2894 | console.error(error); |
| 2400 | return html("<h1>Something went wrong</h1>", 500); | |
| 2895 | try { | |
| 2896 | return html(problem(500, ANON), 500); | |
| 2897 | } catch { | |
| 2898 | return html("<h1>Something went wrong</h1>", 500); | |
| 2899 | } | |
| 2401 | 2900 | }, |
| 2402 | 2901 | }); |
| 2403 | 2902 | } |
| @@ -2600,6 +3099,23 @@ code, | ||
| 2600 | 3099 | .muted { |
| 2601 | 3100 | color: var(--color-muted); |
| 2602 | 3101 | } |
| 3102 | /* The first thing a keyboard reaches: a way past the header, seen only when focused. */ | |
| 3103 | .skip { | |
| 3104 | position: absolute; | |
| 3105 | left: var(--space-3); | |
| 3106 | top: var(--space-3); | |
| 3107 | transform: translateY(-300%); | |
| 3108 | padding: var(--space-2) var(--space-3); | |
| 3109 | background: var(--color-accent); | |
| 3110 | color: var(--color-accent-fg); | |
| 3111 | border-radius: var(--radius-md); | |
| 3112 | } | |
| 3113 | .skip:focus { | |
| 3114 | transform: none; | |
| 3115 | } | |
| 3116 | main:focus { | |
| 3117 | outline: none; | |
| 3118 | } | |
| 2603 | 3119 | .you { |
| 2604 | 3120 | color: var(--color-muted); |
| 2605 | 3121 | white-space: nowrap; |
| @@ -2742,6 +3258,21 @@ footer code { | ||
| 2742 | 3258 | visibility: hidden; |
| 2743 | 3259 | } |
| 2744 | 3260 | } |
| 3261 | /* Forced colours replace ours with the person's own; what only a background | |
| 3262 | or a shadow drew gets a border, so it is still there to see. */ | |
| 3263 | @media (forced-colors: active) { | |
| 3264 | .card, | |
| 3265 | .input, | |
| 3266 | .button, | |
| 3267 | .pill, | |
| 3268 | .toast, | |
| 3269 | .skip { | |
| 3270 | border: 1px solid CanvasText; | |
| 3271 | } | |
| 3272 | :focus-visible { | |
| 3273 | outline-color: Highlight; | |
| 3274 | } | |
| 3275 | } | |
| 2745 | 3276 | /* Motion is a courtesy: whoever asked for less gets none. */ |
| 2746 | 3277 | @media (prefers-reduced-motion: reduce) { |
| 2747 | 3278 | *, |
| @@ -3571,7 +4102,7 @@ test("a link to the page unfurls: description, Open Graph, a card", async () => | ||
| 3571 | 4102 | 'property="og:description"', |
| 3572 | 4103 | 'property="og:url"', |
| 3573 | 4104 | 'property="og:type" content="website"', |
| 3574 | 'name="twitter:card" content="summary"', | |
| 4105 | 'name="twitter:card" content="summary_large_image"', | |
| 3575 | 4106 | 'name="theme-color"', |
| 3576 | 4107 | ]) |
| 3577 | 4108 | expect([meta, page.includes(meta)]).toEqual([meta, true]); |
new above
offline