Public: anyone can read this; the crew can change it.
CI checks every page against the website specification (specification.website) #2937
torque/forge:torque/2915-ci-checks-every-page-against-the-website → main 2 commits fork 1 thread · 1 unresolved
8 files
changed +701
−303
README.md +16 −5
| @@ -314,11 +314,22 @@ never read as a pass. Spend and run bounds are proven in process only; this | ||
| 314 | 314 | pull adds the proof but does not reopen signup — the gitops gate stays for a |
| 315 | 315 | person. |
| 316 | 316 | |
| 317 | `bun scripts/smoke.ts <url> --standards` prints the website-specification | |
| 318 | report (`src/release/webspec.ts`): it fetches each path in forge.json's | |
| 319 | `app.looks` from `<url>` and prints one line per head or header finding with | |
| 320 | the specification.website section it cites. It only reports and always exits | |
| 321 | 0. `(edge)` marks a finding the edge in front of the app may own (HSTS), so | |
| 317 | **The website specification.** `src/release/webspec.ts` holds every page to | |
| 318 | [](https://specification.website/), cheapest checks | |
| 319 | first: the head (doctype, lang, charset, a zoomable viewport, one title, a | |
| 320 | description, `rel=canonical` equal to `og:url`, the theme-color pair, | |
| 321 | `color-scheme`, Open Graph with an image that loads, an icon and a manifest | |
| 322 | that load), the headers (a script policy with no eval or bare inline, | |
| 323 | nosniff, frame-ancestors, Referrer-Policy, Permissions-Policy, HSTS over | |
| 324 | https, no X-XSS-Protection, HTML revalidated, hashed assets immutable and | |
| 325 | answering 304), the well-known files (robots naming the sitemap, a sitemap | |
| 326 | whose entries a stranger can read, an unexpired security.txt, the manifest, | |
| 327 | llms.txt, change-password) and a 404 page made for people. Each finding | |
| 328 | names its section. `test/webspec.test.ts` runs it in the gate over every | |
| 329 | look in `forge.json`, as a stranger and as the admin; | |
| 330 | `[FORGE_TOKEN=…] bun scripts/smoke.ts <url> --standards` runs the same | |
| 331 | checks against a live forge, one `FAIL standards:` line per finding. | |
| 332 | `(edge)` marks a finding the edge in front of the app may own (HSTS), so | |
| 322 | 333 | fix it there rather than in the app. Each fetch gives up after 10 seconds. |
| 323 | 334 | |
| 324 | 335 | What you asked for: `Ctrl+K`, then **Asked**, is `/asked` in the terminal — your |
scripts/smoke.ts +21 −16
| @@ -10,19 +10,23 @@ | ||
| 10 | 10 | * seen. `/sw.js` must be a 200 JavaScript response whose navigation branch |
| 11 | 11 | * never answers with `Response.error()`. |
| 12 | 12 | * |
| 13 | * `--standards` runs the website-specification report (`release/webspec.ts`) | |
| 14 | * over forge.json's `app.looks` paths, prints one line per finding with its | |
| 15 | * section, and exits 0: it reports, it does not gate. | |
| 16 | * | |
| 17 | 13 | * `--outsider` also signs up a fresh account and proves each thing a |
| 18 | 14 | * stranger must not do is refused over HTTP and MCP (`release/outsider.ts`, |
| 19 | 15 | * #663); the terminal door is proven by the gate. It makes one real account, so run it against a forge whose signup is open to it, with |
| 20 | 16 | * `FORGE_TOKEN` naming the private repositories to reach for. |
| 17 | * | |
| 18 | * `--standards` also holds the forge to the website specification's head, | |
| 19 | * headers, well-known files and error pages (`release/webspec.ts`, #2915) | |
| 20 | * on every page forge.json names as a look, as a stranger and — with | |
| 21 | * `FORGE_TOKEN` — as its holder. One line per finding, naming the section; | |
| 22 | * `(edge)` marks one the edge in front of the app may own (HSTS). Each | |
| 23 | * fetch gives up after 10 seconds. | |
| 21 | 24 | */ |
| 22 | 25 | |
| 23 | 26 | import { smoke } from "../src/release/smoke.ts"; |
| 24 | import { webspec } from "../src/release/webspec.ts"; | |
| 25 | 27 | import { outsider } from "../src/release/outsider.ts"; |
| 28 | import { webspec, type Finding } from "../src/release/webspec.ts"; | |
| 29 | import forgeJson from "../forge.json" with { type: "json" }; | |
| 26 | 30 | export * from "../src/release/smoke.ts"; |
| 27 | 31 | |
| 28 | 32 | if (import.meta.main) { |
| @@ -34,8 +38,8 @@ if (import.meta.main) { | ||
| 34 | 38 | }; |
| 35 | 39 | const withOutsider = args.includes("--outsider"); |
| 36 | 40 | if (withOutsider) args.splice(args.indexOf("--outsider"), 1); |
| 37 | const standards = args.includes("--standards"); | |
| 38 | if (standards) args.splice(args.indexOf("--standards"), 1); | |
| 41 | const withStandards = args.includes("--standards"); | |
| 42 | if (withStandards) args.splice(args.indexOf("--standards"), 1); | |
| 39 | 43 | const version = flag("--version"); |
| 40 | 44 | const wait = flag("--wait"); |
| 41 | 45 | const base = args[0]; |
| @@ -48,14 +52,6 @@ if (import.meta.main) { | ||
| 48 | 52 | console.error("--outsider needs FORGE_TOKEN naming the owner's repos: private reads, steering, the form door and MCP tells cannot be tried without it"); |
| 49 | 53 | process.exit(2); |
| 50 | 54 | } |
| 51 | if (standards) { | |
| 52 | const looks = (await Bun.file(new URL("../forge.json", import.meta.url)).json())?.app?.looks; | |
| 53 | const paths: string[] = Array.isArray(looks) ? looks.filter((p): p is string => typeof p === "string") : ["/"]; | |
| 54 | const findings = await webspec(base, paths); | |
| 55 | for (const f of findings) console.log(`${f.path} ${f.check}${f.edge ? " (edge)" : ""}: ${f.message} <${f.section}>`); | |
| 56 | console.log(`standards: ${findings.length} finding(s) over ${paths.length} path(s); report only`); | |
| 57 | process.exit(0); | |
| 58 | } | |
| 59 | 55 | const failures = await smoke(base, process.env["FORGE_TOKEN"] ?? "", { version, waitMs: seconds * 1000 }); |
| 60 | 56 | for (const f of failures) |
| 61 | 57 | console.error(`FAIL ${f.url} agent=${f.agent} status=${f.status} content-type=${f.contentType || "-"} (${f.why})`); |
| @@ -63,7 +59,16 @@ if (import.meta.main) { | ||
| 63 | 59 | ? await outsider(base, { ...(process.env["FORGE_TOKEN"] ? { ownerToken: process.env["FORGE_TOKEN"] } : {}) }) |
| 64 | 60 | : []; |
| 65 | 61 | for (const r of unrefused) console.error(`FAIL outsider: ${r.check} (${r.why})`); |
| 66 | if (failures.length || unrefused.length) process.exit(1); | |
| 62 | const findings: Finding[] = []; | |
| 63 | if (withStandards) { | |
| 64 | const paths = forgeJson.app.looks; | |
| 65 | findings.push(...(await webspec(base, { paths }))); | |
| 66 | const token = process.env["FORGE_TOKEN"]; | |
| 67 | if (token) findings.push(...(await webspec(base, { paths, headers: { authorization: `Bearer ${token}` } }))); | |
| 68 | } | |
| 69 | for (const f of findings) console.error(`FAIL standards: ${f.url} [${f.section}] ${f.why}${f.edge ? " (edge)" : ""}`); | |
| 70 | if (failures.length || unrefused.length || findings.length) process.exit(1); | |
| 71 | if (withStandards) console.log(`standards ok: head, headers, well-known files and error pages on ${forgeJson.app.looks.length} looks`); | |
| 67 | 72 | if (withOutsider) console.log("outsider suite ok for HTTP and MCP; the terminal door is proven by the gate (test/outsider-tty.test.ts)"); |
| 68 | 73 | console.log(`smoke ok: ${base}`); |
| 69 | 74 | } |
src/http/respond.ts +15 −1
| @@ -118,9 +118,21 @@ export function prefersHtml(request: Request, pathname: string): boolean { | ||
| 118 | 118 | const FLOOR_POLICY = |
| 119 | 119 | "default-src 'none'; frame-ancestors 'none'; base-uri 'none'"; |
| 120 | 120 | |
| 121 | /** | |
| 122 | * The browser features no forge page uses, refused to the page and to | |
| 123 | * anything it frames. Passkeys (`publickey-credentials-*`) and the | |
| 124 | * clipboard are left at their same-origin default: the forge uses both. | |
| 125 | */ | |
| 126 | export const PERMISSIONS_POLICY = | |
| 127 | "camera=(), microphone=(), geolocation=(), payment=(), usb=()"; | |
| 128 | ||
| 129 | /** HSTS for a forge served over https: a year, the preload list's floor. */ | |
| 130 | export const HSTS_SECONDS = 31_536_000; | |
| 131 | ||
| 121 | 132 | /** |
| 122 | 133 | * The security floor every response the forge writes leaves with: never |
| 123 | * sniffed into another type, never a referrer sent off-site, and — unless | |
| 134 | * sniffed into another type, never a referrer sent off-site, no camera, | |
| 135 | * microphone or location asked for, and — unless | |
| 124 | 136 | * the body is a document that wrote its own policy — inert. |
| 125 | 137 | * |
| 126 | 138 | * A responder that already set one of these keeps its value: `page()` has a |
| @@ -136,6 +148,8 @@ export function securityFloor(response: Response): Response { | ||
| 136 | 148 | headers.set("x-content-type-options", "nosniff"); |
| 137 | 149 | if (!headers.has("referrer-policy")) |
| 138 | 150 | headers.set("referrer-policy", "same-origin"); |
| 151 | if (!headers.has("permissions-policy")) | |
| 152 | headers.set("permissions-policy", PERMISSIONS_POLICY); | |
| 139 | 153 | // What left decides, not what was asked for: an HTML body writes the |
| 140 | 154 | // only policy that can name its own nonce, and `default-src 'none'` |
| 141 | 155 | // over a page would strip it of its stylesheet. |
src/http/server.ts +27 −4
| @@ -440,7 +440,7 @@ import { | ||
| 440 | 440 | originsPage, |
| 441 | 441 | } from "../web/pages/origins.ts"; |
| 442 | 442 | import { pushThrough } from "../origins/push-through.ts"; |
| 443 | import { notFoundPage } from "../web/chrome.ts"; | |
| 443 | import { notFoundPage, serverErrorPage } from "../web/chrome.ts"; | |
| 444 | 444 | import { targetForShortCode } from "../origins/oauth.ts"; |
| 445 | 445 | import { apiRoutes } from "./api.ts"; |
| 446 | 446 | import { inNamespace } from "../core/proposal_token.ts"; |
| @@ -1898,9 +1898,12 @@ export interface Servers { | ||
| 1898 | 1898 | /** |
| 1899 | 1899 | * What a thrown handler is answered with: the guard's words (or a generic |
| 1900 | 1900 | * "refused") and a 403 |
| 1901 | * when a database trigger refused, else a 500 that says nothing of the fault. | |
| 1901 | * when a database trigger refused, else a 500 that says nothing of the fault | |
| 1902 | * — a page for a browser, `{ error: "internal" }` for anything else. The | |
| 1903 | * page is rendered as a stranger's, like the 404: the request that broke is | |
| 1904 | * not read again to find out who sent it. | |
| 1902 | 1905 | */ |
| 1903 | function failure(app: App, error: unknown): Response { | |
| 1906 | export function failure(app: App, error: unknown, request?: Request): Response { | |
| 1904 | 1907 | const refused = refusedByDatabase(error); |
| 1905 | 1908 | if (refused !== undefined) { |
| 1906 | 1909 | const shown = shownRefusal(refused); |
| @@ -1908,6 +1911,26 @@ function failure(app: App, error: unknown): Response { | ||
| 1908 | 1911 | return securityFloor(json({ error: "refused", message: shown }, 403)); |
| 1909 | 1912 | } |
| 1910 | 1913 | app.log.error("unhandled request error", { error: String(error) }); |
| 1914 | if (request !== undefined) { | |
| 1915 | const url = publicUrl(request, app.config.url); | |
| 1916 | if (prefersHtml(request, url.pathname)) { | |
| 1917 | const themeCookie = cookieValue(request, "forge_theme") ?? ""; | |
| 1918 | try { | |
| 1919 | return securityFloor( | |
| 1920 | serverErrorPage({ | |
| 1921 | app, | |
| 1922 | request, | |
| 1923 | url, | |
| 1924 | params: {}, | |
| 1925 | auth: { user: undefined, scope: undefined, via: "none" }, | |
| 1926 | theme: isThemeName(themeCookie) ? themeCookie : undefined, | |
| 1927 | }), | |
| 1928 | ); | |
| 1929 | } catch (again) { | |
| 1930 | app.log.error("the error page broke too", { error: String(again) }); | |
| 1931 | } | |
| 1932 | } | |
| 1933 | } | |
| 1911 | 1934 | return securityFloor(json({ error: "internal" }, 500)); |
| 1912 | 1935 | } |
| 1913 | 1936 | |
| @@ -2116,7 +2139,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2116 | 2139 | else request.signal.addEventListener("abort", onAbort, { once: true }); |
| 2117 | 2140 | const work = run().then( |
| 2118 | 2141 | (response) => securityFloor(response), |
| 2119 | (error) => failure(owner, error), | |
| 2142 | (error) => failure(owner, error, request), | |
| 2120 | 2143 | ); |
| 2121 | 2144 | try { |
| 2122 | 2145 | const first = await Promise.race([work, gone.promise]); |
src/release/webspec.ts +340 −135
| @@ -1,158 +1,363 @@ | ||
| 1 | 1 | /** |
| 2 | * The website specification as a report (#2915, checks 1 and 2). `webspec()` | |
| 3 | * fetches each path of a site once and returns what the page's head and | |
| 4 | * response headers get wrong, each finding citing its specification.website | |
| 5 | * section. It reports; it never throws on a bad page and never fails a run. | |
| 6 | * The HTML is read with small regexes, one function per check. | |
| 2 | * The website specification (https://specification.website/) as a | |
| 3 | * checklist a machine runs, cheapest first (#2915): | |
| 4 | * | |
| 5 | * 1. head doctype, lang, charset, a zoomable viewport, one title, | |
| 6 | * a description, rel=canonical equal to og:url, the | |
| 7 | * theme-color pair, color-scheme, Open Graph with an image | |
| 8 | * that loads, an icon and a manifest that load | |
| 9 | * 2. headers a script policy with no eval and no bare inline, nosniff, | |
| 10 | * frame-ancestors, a referrer policy, a permissions policy, | |
| 11 | * HSTS over https, no X-XSS-Protection; HTML revalidated, | |
| 12 | * hashed assets immutable and answering 304 to their ETag | |
| 13 | * 3. well-known robots.txt naming the sitemap, a sitemap of pages that | |
| 14 | * answer a stranger, security.txt not expired, the | |
| 15 | * manifest, llms.txt, change-password | |
| 16 | * 4. errors a path nobody routes is a 404 page made for people | |
| 17 | * | |
| 18 | * Every finding names the section of the specification it comes from, so a | |
| 19 | * red line says where to read why. The same function runs in the gate | |
| 20 | * against a forge booted in-process (test/webspec.test.ts) and against a | |
| 21 | * live URL (`bun scripts/smoke.ts <url> --standards`), so what the gate | |
| 22 | * passes is what a deployed forge is held to. | |
| 23 | * | |
| 24 | * Plain text in, findings out: the page checks take a body and headers and | |
| 25 | * fetch nothing; only `webspec` touches the network. | |
| 7 | 26 | */ |
| 8 | 27 | |
| 9 | 28 | export interface Finding { |
| 10 | path: string; | |
| 11 | check: string; | |
| 12 | message: string; | |
| 13 | /** The specification.website section this finding cites. */ | |
| 14 | section: string; | |
| 15 | /** Set when the CDN or edge in front of the app may own the header. */ | |
| 16 | edge?: true; | |
| 29 | /** The URL the finding is about. */ | |
| 30 | readonly url: string; | |
| 31 | /** The specification's section, as it names it. */ | |
| 32 | readonly section: string; | |
| 33 | /** What is wrong, in a line. */ | |
| 34 | readonly why: string; | |
| 35 | /** Set when the CDN or edge in front of the app may own the fix (HSTS). */ | |
| 36 | readonly edge?: true; | |
| 17 | 37 | } |
| 18 | 38 | |
| 19 | type Fetcher = (input: string, init?: RequestInit) => Promise<Response>; | |
| 20 | type Problem = { check: string; message: string; section: string; edge?: true }; | |
| 39 | /** The sections findings cite, by the specification's own headings. */ | |
| 40 | export const SECTION = { | |
| 41 | head: "Document head", | |
| 42 | social: "Social sharing (Open Graph)", | |
| 43 | icons: "Icons and manifest", | |
| 44 | security: "Security headers", | |
| 45 | caching: "Caching", | |
| 46 | wellKnown: "Well-known files", | |
| 47 | errors: "Error pages", | |
| 48 | } as const; | |
| 21 | 49 | |
| 22 | const TIMEOUT_MS = 10000; | |
| 23 | const SPEC = "https://specification.website/"; | |
| 24 | const s = (name: string) => `${SPEC}#${name}`; | |
| 25 | ||
| 26 | const tags = (html: string, name: string): string[] => html.match(new RegExp(`<${name}\\b[^>]*>`, "gi")) ?? []; | |
| 27 | ||
| 28 | function attr(tag: string, name: string): string | undefined { | |
| 29 | const m = new RegExp(`(?:^|[\\s"'/])${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag); | |
| 30 | return m ? (m[1] ?? m[2] ?? m[3] ?? "") : undefined; | |
| 31 | } | |
| 32 | ||
| 33 | const metas = (html: string) => tags(html, "meta"); | |
| 34 | const metaBy = (html: string, key: "name" | "property", value: string) => | |
| 35 | metas(html).filter((t) => attr(t, key)?.toLowerCase() === value); | |
| 36 | const metaContent = (html: string, key: "name" | "property", value: string) => | |
| 37 | metaBy(html, key, value)[0] && (attr(metaBy(html, key, value)[0]!, "content") ?? ""); | |
| 38 | const links = (html: string, rel: string) => | |
| 39 | tags(html, "link").filter((t) => (attr(t, "rel") ?? "").toLowerCase().split(/\s+/).includes(rel)); | |
| 40 | ||
| 41 | export function headProblems(html: string): Problem[] { | |
| 42 | const out: Problem[] = []; | |
| 43 | const add = (check: string, message: string, section: string) => out.push({ check, message, section: s(section) }); | |
| 44 | if (!/^\s*<!doctype html>/i.test(html)) add("doctype", "the page does not start with <!doctype html>", "doctype"); | |
| 45 | const htmlTag = tags(html, "html")[0] ?? ""; | |
| 46 | if (!(attr(htmlTag, "lang") ?? "").trim()) add("lang", "<html> has no lang attribute", "lang"); | |
| 47 | const charset = metas(html).some( | |
| 48 | (t) => /^utf-8$/i.test(attr(t, "charset") ?? "") || (/content-type/i.test(attr(t, "http-equiv") ?? "") && /utf-8/i.test(attr(t, "content") ?? "")), | |
| 49 | ); | |
| 50 | if (!charset) add("charset", 'no <meta charset="utf-8">', "charset"); | |
| 51 | const viewport = metaContent(html, "name", "viewport"); | |
| 52 | if (viewport === undefined) add("viewport", "no viewport meta", "viewport"); | |
| 53 | else if (/maximum-scale\s*=|user-scalable\s*=\s*(no|0)/i.test(viewport)) | |
| 54 | add("viewport", "the viewport locks zoom (maximum-scale or user-scalable=no)", "viewport"); | |
| 55 | const titles = html.match(/<title\b[^>]*>/gi)?.length ?? 0; | |
| 56 | if (titles !== 1) add("title", `expected exactly one <title>, found ${titles}`, "title"); | |
| 57 | if (!(metaContent(html, "name", "description") ?? "").trim()) add("description", "no meta description", "description"); | |
| 58 | const canonical = links(html, "canonical").map((t) => attr(t, "href") ?? "")[0]; | |
| 59 | const ogUrl = metaContent(html, "property", "og:url"); | |
| 60 | if (!canonical) add("canonical", 'no <link rel="canonical">', "canonical"); | |
| 61 | else if (canonical !== ogUrl) add("canonical", `canonical (${canonical}) is not og:url (${ogUrl ?? "missing"})`, "canonical"); | |
| 62 | const themes = metaBy(html, "name", "theme-color").map((t) => attr(t, "media") ?? ""); | |
| 63 | const has = (scheme: string) => themes.some((m) => m.replace(/\s+/g, "").includes(`prefers-color-scheme:${scheme}`)); | |
| 64 | if (!has("light") || !has("dark")) add("theme-color", "theme-color needs a light and a dark variant (media=prefers-color-scheme)", "theme-color"); | |
| 65 | if (!(metaContent(html, "name", "color-scheme") ?? "").trim()) add("color-scheme", "no color-scheme meta", "color-scheme"); | |
| 66 | for (const p of ["og:title", "og:type", "og:url", "og:description", "og:image"]) | |
| 67 | if (!(metaContent(html, "property", p) ?? "").trim()) add("open-graph", `missing ${p}`, "open-graph"); | |
| 50 | /** The attributes of one start tag, names lower-cased, entities left as written. */ | |
| 51 | export function attributes(tag: string): Record<string, string> { | |
| 52 | const out: Record<string, string> = {}; | |
| 53 | const body = tag.replace(/^<\s*[a-zA-Z][\w-]*/, "").replace(/\/?>$/, ""); | |
| 54 | const re = /([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g; | |
| 55 | for (const m of body.matchAll(re)) { | |
| 56 | const name = m[1]!.toLowerCase(); | |
| 57 | if (!(name in out)) out[name] = (m[2] ?? m[3] ?? m[4] ?? "").replaceAll("&", "&"); | |
| 58 | } | |
| 68 | 59 | return out; |
| 69 | 60 | } |
| 70 | 61 | |
| 71 | /** Targets the head points at that must resolve: icons and the manifest. */ | |
| 72 | export function headTargets(html: string, pageUrl: string): { urls: string[]; bad: string[] } { | |
| 73 | const hrefs = [...links(html, "icon"), ...links(html, "apple-touch-icon"), ...links(html, "manifest")].map((t) => attr(t, "href") ?? ""); | |
| 74 | const urls: string[] = []; | |
| 75 | const bad: string[] = []; | |
| 76 | for (const h of hrefs) { | |
| 77 | try { | |
| 78 | const u = new URL(h, pageUrl).href; | |
| 79 | if (!urls.includes(u)) urls.push(u); | |
| 80 | } catch { | |
| 81 | bad.push(h); | |
| 82 | } | |
| 83 | } | |
| 84 | return { urls, bad }; | |
| 62 | /** Every start tag `name` in `html`, as attribute maps. */ | |
| 63 | function tags(html: string, name: string): Record<string, string>[] { | |
| 64 | return [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => attributes(m[0])); | |
| 85 | 65 | } |
| 86 | 66 | |
| 87 | export function headerProblems(h: Headers, https: boolean): Problem[] { | |
| 88 | const out: Problem[] = []; | |
| 89 | const add = (check: string, message: string, section: string, edge?: true) => | |
| 90 | out.push({ check, message, section: s(section), ...(edge ? { edge } : {}) }); | |
| 91 | const csp = h.get("content-security-policy"); | |
| 92 | if (!csp) add("csp", "no Content-Security-Policy", "csp"); | |
| 67 | /** The document's head: everything before `</head>`, or all of it. */ | |
| 68 | function headOf(html: string): string { | |
| 69 | const end = html.search(/<\/head\s*>/i); | |
| 70 | return end < 0 ? html : html.slice(0, end); | |
| 71 | } | |
| 72 | ||
| 73 | function metaNamed(head: string, key: "name" | "property", value: string): Record<string, string>[] { | |
| 74 | return tags(head, "meta").filter((a) => (a[key] ?? "").toLowerCase() === value); | |
| 75 | } | |
| 76 | ||
| 77 | function relHas(a: Record<string, string>, rel: string): boolean { | |
| 78 | return (a["rel"] ?? "").toLowerCase().split(/\s+/).includes(rel); | |
| 79 | } | |
| 80 | ||
| 81 | /** | |
| 82 | * What a page's head is missing. `url` is the address the page was read | |
| 83 | * from; a 200 page names it as its canonical, an error page names none. | |
| 84 | */ | |
| 85 | export function headFindings(url: string, html: string, status = 200): Finding[] { | |
| 86 | const out: Finding[] = []; | |
| 87 | const miss = (section: string, why: string) => out.push({ url, section, why }); | |
| 88 | const head = headOf(html); | |
| 89 | if (!/^\s*<!doctype html>/i.test(html)) miss(SECTION.head, "does not start with <!doctype html>"); | |
| 90 | const root = tags(html, "html")[0]; | |
| 91 | if (!root?.["lang"]) miss(SECTION.head, "<html> has no lang"); | |
| 92 | // The encoding must be declared within the first 1024 bytes (HTML §4.2.5.4). | |
| 93 | const charsetAt = html.search(/<meta\s+charset\s*=\s*["']?utf-8/i); | |
| 94 | if (charsetAt < 0 || charsetAt > 1024) miss(SECTION.head, "no <meta charset=utf-8> in the first 1024 bytes"); | |
| 95 | const viewport = metaNamed(head, "name", "viewport")[0]?.["content"] ?? ""; | |
| 96 | if (!/width\s*=\s*device-width/i.test(viewport)) miss(SECTION.head, "no viewport with width=device-width"); | |
| 97 | // Zoom to 200% is WCAG 1.4.4; a viewport that forbids it locks people out. | |
| 98 | if (/user-scalable\s*=\s*(no|0)\b/i.test(viewport)) miss(SECTION.head, "viewport forbids zoom (user-scalable=no)"); | |
| 99 | const maxScale = /maximum-scale\s*=\s*([\d.]+)/i.exec(viewport); | |
| 100 | if (maxScale && Number(maxScale[1]) < 2) miss(SECTION.head, `viewport caps zoom at maximum-scale=${maxScale[1]}`); | |
| 101 | const titles = [...head.matchAll(/<title\b[^>]*>([\s\S]*?)<\/title>/gi)]; | |
| 102 | if (titles.length !== 1) miss(SECTION.head, `${titles.length} <title> elements, wanted one`); | |
| 103 | else if (!titles[0]![1]!.trim()) miss(SECTION.head, "the <title> is empty"); | |
| 104 | if (!metaNamed(head, "name", "description")[0]?.["content"]?.trim()) miss(SECTION.head, "no meta description"); | |
| 105 | if (!metaNamed(head, "name", "color-scheme")[0]?.["content"]?.trim()) miss(SECTION.head, "no meta color-scheme"); | |
| 106 | const themes = metaNamed(head, "name", "theme-color"); | |
| 107 | if (themes.length === 0) miss(SECTION.head, "no meta theme-color"); | |
| 108 | else if (themes.some((t) => t["media"] !== undefined)) { | |
| 109 | // A theme-colour that follows the system needs both halves of the pair. | |
| 110 | for (const scheme of ["light", "dark"]) | |
| 111 | if (!themes.some((t) => (t["media"] ?? "").includes(`prefers-color-scheme: ${scheme}`))) | |
| 112 | miss(SECTION.head, `theme-color has no (prefers-color-scheme: ${scheme}) half`); | |
| 113 | } | |
| 114 | ||
| 115 | const og = (p: string) => metaNamed(head, "property", p)[0]?.["content"]; | |
| 116 | for (const p of ["og:title", "og:description", "og:type", "og:image"]) | |
| 117 | if (!og(p)?.trim()) miss(SECTION.social, `no ${p}`); | |
| 118 | const image = og("og:image"); | |
| 119 | if (image && !/^https?:\/\//.test(image)) miss(SECTION.social, "og:image is not an absolute URL"); | |
| 120 | const canonical = tags(head, "link").find((a) => relHas(a, "canonical"))?.["href"]; | |
| 121 | if (status === 200) { | |
| 122 | const ogUrl = og("og:url"); | |
| 123 | if (!canonical) miss(SECTION.head, "no <link rel=canonical>"); | |
| 124 | if (!ogUrl) miss(SECTION.social, "no og:url"); | |
| 125 | if (canonical && ogUrl && canonical !== ogUrl) miss(SECTION.head, `rel=canonical ${canonical} is not og:url ${ogUrl}`); | |
| 126 | } else if (canonical) { | |
| 127 | // An error page is not a place; naming one would index the dead link. | |
| 128 | miss(SECTION.errors, "an error page names a canonical address"); | |
| 129 | } | |
| 130 | ||
| 131 | const links = tags(head, "link"); | |
| 132 | if (!links.some((a) => relHas(a, "icon") && a["href"])) miss(SECTION.icons, "no <link rel=icon>"); | |
| 133 | if (!links.some((a) => relHas(a, "manifest") && a["href"])) miss(SECTION.icons, "no <link rel=manifest>"); | |
| 134 | return out; | |
| 135 | } | |
| 136 | ||
| 137 | /** The directives of a Content-Security-Policy, by name. */ | |
| 138 | export function cspDirectives(policy: string): Map<string, string[]> { | |
| 139 | const out = new Map<string, string[]>(); | |
| 140 | for (const part of policy.split(";")) { | |
| 141 | const [name, ...values] = part.trim().split(/\s+/); | |
| 142 | if (name && !out.has(name.toLowerCase())) out.set(name.toLowerCase(), values); | |
| 143 | } | |
| 144 | return out; | |
| 145 | } | |
| 146 | ||
| 147 | /** HSTS asks for a year at least: the preload list's floor (hstspreload.org). */ | |
| 148 | export const HSTS_MIN_SECONDS = 31_536_000; | |
| 149 | ||
| 150 | /** What a document's response headers are missing. */ | |
| 151 | export function documentHeaderFindings(url: string, headers: Headers): Finding[] { | |
| 152 | const out: Finding[] = []; | |
| 153 | const miss = (section: string, why: string) => out.push({ url, section, why }); | |
| 154 | const policy = headers.get("content-security-policy"); | |
| 155 | if (policy === null) miss(SECTION.security, "no Content-Security-Policy"); | |
| 93 | 156 | else { |
| 94 | if (/'unsafe-eval'/i.test(csp)) add("csp", "CSP allows 'unsafe-eval'", "csp"); | |
| 95 | const directives = csp.split(";").map((d) => d.trim()); | |
| 96 | const script = directives.find((d) => /^script-src(-elem)?\s/i.test(d)) ?? directives.find((d) => /^default-src\s/i.test(d)); | |
| 97 | if (script && /'unsafe-inline'/i.test(script)) add("csp", "CSP allows 'unsafe-inline' scripts", "csp"); | |
| 98 | if (!directives.some((d) => /^frame-ancestors\s/i.test(d))) add("frame-ancestors", "CSP has no frame-ancestors", "frame-ancestors"); | |
| 157 | const csp = cspDirectives(policy); | |
| 158 | const scripts = csp.get("script-src") ?? csp.get("default-src") ?? ["*"]; | |
| 159 | if (scripts.includes("'unsafe-eval'")) miss(SECTION.security, "script-src allows 'unsafe-eval'"); | |
| 160 | if (scripts.includes("'unsafe-inline'")) miss(SECTION.security, "script-src allows 'unsafe-inline'"); | |
| 161 | if (!csp.has("frame-ancestors") && headers.get("x-frame-options") === null) | |
| 162 | miss(SECTION.security, "no frame-ancestors (nor X-Frame-Options)"); | |
| 99 | 163 | } |
| 100 | if ((h.get("x-content-type-options") ?? "").toLowerCase() !== "nosniff") add("nosniff", "X-Content-Type-Options is not nosniff", "nosniff"); | |
| 101 | if (!h.get("referrer-policy")) add("referrer-policy", "no Referrer-Policy", "referrer-policy"); | |
| 102 | if (!h.get("permissions-policy")) add("permissions-policy", "no Permissions-Policy", "permissions-policy"); | |
| 103 | if (https && !h.get("strict-transport-security")) add("hsts", "no Strict-Transport-Security on an https URL", "hsts", true); | |
| 104 | if (h.has("x-xss-protection")) add("x-xss-protection", "X-XSS-Protection is set; drop it", "x-xss-protection"); | |
| 105 | if (/\bimmutable\b/i.test(h.get("cache-control") ?? "")) add("cache-html", "HTML is cached immutable; only hashed assets may be", "caching"); | |
| 164 | if ((headers.get("x-content-type-options") ?? "").toLowerCase() !== "nosniff") | |
| 165 | miss(SECTION.security, "no X-Content-Type-Options: nosniff"); | |
| 166 | const referrer = (headers.get("referrer-policy") ?? "").toLowerCase(); | |
| 167 | if (!referrer) miss(SECTION.security, "no Referrer-Policy"); | |
| 168 | else if (/unsafe-url|no-referrer-when-downgrade/.test(referrer)) miss(SECTION.security, `Referrer-Policy ${referrer} sends the full URL off-site`); | |
| 169 | if (!headers.get("permissions-policy")) miss(SECTION.security, "no Permissions-Policy"); | |
| 170 | const xss = headers.get("x-xss-protection"); | |
| 171 | // The auditor it switched on is gone, and its blocking mode was itself a leak. | |
| 172 | if (xss !== null && xss.trim() !== "0") miss(SECTION.security, `X-XSS-Protection: ${xss} (send none, or 0)`); | |
| 173 | if (new URL(url).protocol === "https:") { | |
| 174 | const hsts = headers.get("strict-transport-security") ?? ""; | |
| 175 | const age = Number(/max-age\s*=\s*"?(\d+)/i.exec(hsts)?.[1] ?? -1); | |
| 176 | if (age < HSTS_MIN_SECONDS) | |
| 177 | out.push({ url, section: SECTION.security, why: hsts ? `HSTS max-age ${age} is under a year` : "no Strict-Transport-Security over https", edge: true }); | |
| 178 | } | |
| 179 | // Markup names hashed assets; a cached page could pair with a stale sheet. | |
| 180 | const cache = (headers.get("cache-control") ?? "").toLowerCase(); | |
| 181 | if (!/no-cache|no-store|max-age=0\b/.test(cache)) miss(SECTION.caching, `HTML is cached without revalidation (cache-control: ${cache || "none"})`); | |
| 106 | 182 | return out; |
| 107 | 183 | } |
| 108 | 184 | |
| 109 | /** Fetches `paths` of `base` and reports head and header findings. */ | |
| 110 | export async function webspec(base: string, paths: string[], fetcher: Fetcher = fetch): Promise<Finding[]> { | |
| 111 | const findings: Finding[] = []; | |
| 112 | for (const path of paths) { | |
| 113 | const report = (ps: Problem[]) => { | |
| 114 | for (const p of ps) findings.push({ path, ...p }); | |
| 115 | }; | |
| 116 | let url: string; | |
| 185 | /** What a content-hashed asset's caching is missing. */ | |
| 186 | export function assetHeaderFindings(url: string, headers: Headers): Finding[] { | |
| 187 | const cache = (headers.get("cache-control") ?? "").toLowerCase(); | |
| 188 | const age = Number(/max-age=(\d+)/.exec(cache)?.[1] ?? 0); | |
| 189 | const out: Finding[] = []; | |
| 190 | if (!cache.includes("immutable") || age < 31_536_000) | |
| 191 | out.push({ url, section: SECTION.caching, why: `a hashed asset is not cached for a year as immutable (cache-control: ${cache || "none"})` }); | |
| 192 | if (!headers.get("etag") && !headers.get("last-modified")) | |
| 193 | out.push({ url, section: SECTION.caching, why: "no ETag or Last-Modified to revalidate with" }); | |
| 194 | if ((headers.get("x-content-type-options") ?? "").toLowerCase() !== "nosniff") | |
| 195 | out.push({ url, section: SECTION.security, why: "no X-Content-Type-Options: nosniff" }); | |
| 196 | return out; | |
| 197 | } | |
| 198 | ||
| 199 | /** What robots.txt is missing. */ | |
| 200 | export function robotsFindings(url: string, body: string): Finding[] { | |
| 201 | const out: Finding[] = []; | |
| 202 | if (!/^user-agent:/im.test(body)) out.push({ url, section: SECTION.wellKnown, why: "robots.txt has no User-agent line" }); | |
| 203 | if (!/^sitemap:\s*https?:\/\/\S+/im.test(body)) out.push({ url, section: SECTION.wellKnown, why: "robots.txt names no Sitemap by absolute URL" }); | |
| 204 | return out; | |
| 205 | } | |
| 206 | ||
| 207 | /** The `<loc>` URLs of a sitemap. */ | |
| 208 | export function sitemapLocs(body: string): string[] { | |
| 209 | return [...body.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((m) => m[1]!.replaceAll("&", "&")); | |
| 210 | } | |
| 211 | ||
| 212 | /** What security.txt (RFC 9116) is missing, as of `now`. */ | |
| 213 | export function securityTxtFindings(url: string, body: string, now: Date): Finding[] { | |
| 214 | const out: Finding[] = []; | |
| 215 | if (!/^contact:\s*\S+/im.test(body)) out.push({ url, section: SECTION.wellKnown, why: "security.txt has no Contact" }); | |
| 216 | const expires = /^expires:\s*(\S+)/im.exec(body)?.[1]; | |
| 217 | const at = expires === undefined ? Number.NaN : Date.parse(expires); | |
| 218 | if (Number.isNaN(at)) out.push({ url, section: SECTION.wellKnown, why: "security.txt has no valid Expires" }); | |
| 219 | else if (at <= now.getTime()) out.push({ url, section: SECTION.wellKnown, why: `security.txt expired ${expires}` }); | |
| 220 | return out; | |
| 221 | } | |
| 222 | ||
| 223 | export interface WebspecOptions { | |
| 224 | /** The page paths to read; `/` when none. */ | |
| 225 | paths?: readonly string[]; | |
| 226 | /** Headers sent with every page read (a bearer token, a cookie). */ | |
| 227 | headers?: Record<string, string>; | |
| 228 | /** The fetch to use; the global one unless a caller gives its own. */ | |
| 229 | fetch?: typeof fetch; | |
| 230 | /** Sitemap entries to read back as a stranger; the rest are only listed. */ | |
| 231 | sitemapSample?: number; | |
| 232 | /** The clock security.txt's expiry is read against. */ | |
| 233 | now?: Date; | |
| 234 | } | |
| 235 | ||
| 236 | const ACCEPT_HTML = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8"; | |
| 237 | ||
| 238 | /** Runs checks 1–4 against `base`; returns the findings (empty is green). */ | |
| 239 | export async function webspec(base: string, options: WebspecOptions = {}): Promise<Finding[]> { | |
| 240 | const root = new URL(base); | |
| 241 | if (root.protocol !== "http:" && root.protocol !== "https:") throw new Error("url must be http(s)"); | |
| 242 | const fetch = options.fetch ?? globalThis.fetch; | |
| 243 | const out: Finding[] = []; | |
| 244 | const get = async (path: string, headers: Record<string, string> = {}) => { | |
| 245 | const url = new URL(path, root).href; | |
| 117 | 246 | try { |
| 118 | url = new URL(path, base).href; | |
| 119 | } catch { | |
| 120 | report([{ check: "fetch", message: `${path} is not a URL`, section: SPEC }]); | |
| 121 | continue; | |
| 247 | const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers }); | |
| 248 | return { url, res, body: await res.text() }; | |
| 249 | } catch (error) { | |
| 250 | out.push({ url, section: "reachable", why: String(error) }); | |
| 251 | return null; | |
| 122 | 252 | } |
| 123 | let res: Response; | |
| 124 | let html: string; | |
| 125 | try { | |
| 126 | res = await fetcher(url, { headers: { accept: "text/html" }, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) }); | |
| 127 | html = await res.text(); | |
| 128 | } catch (e) { | |
| 129 | report([{ check: "fetch", message: `could not fetch ${url}: ${e instanceof Error ? e.message : String(e)}`, section: SPEC }]); | |
| 130 | continue; | |
| 253 | }; | |
| 254 | const loads = async (href: string, section: string, from: string, type: RegExp) => { | |
| 255 | const r = await get(href); | |
| 256 | if (r === null) return; | |
| 257 | const ct = r.res.headers.get("content-type") ?? ""; | |
| 258 | if (r.res.status !== 200) out.push({ url: r.url, section, why: `linked from ${from}, answers ${r.res.status}` }); | |
| 259 | else if (!type.test(ct)) out.push({ url: r.url, section, why: `linked from ${from}, served as ${ct || "nothing"}` }); | |
| 260 | }; | |
| 261 | ||
| 262 | // 1, 2 — each page, following one same-origin redirect (to sign-in). | |
| 263 | const seen = new Set<string>(); | |
| 264 | const resources = new Map<string, { section: string; from: string; type: RegExp }>(); | |
| 265 | let stylesheet: string | undefined; | |
| 266 | for (const path of options.paths ?? ["/"]) { | |
| 267 | let page = await get(path, { accept: ACCEPT_HTML, ...options.headers }); | |
| 268 | const location = page?.res.headers.get("location"); | |
| 269 | if (page && location && page.res.status >= 300 && page.res.status < 400) { | |
| 270 | const to = new URL(location, page.url); | |
| 271 | if (to.origin !== root.origin) continue; | |
| 272 | page = await get(to.pathname + to.search, { accept: ACCEPT_HTML, ...options.headers }); | |
| 131 | 273 | } |
| 132 | if (!res.ok) { | |
| 133 | report([{ check: "fetch", message: `${url} answered ${res.status}`, section: SPEC }]); | |
| 134 | continue; | |
| 135 | } | |
| 136 | report(headProblems(html)); | |
| 137 | const { urls, bad } = headTargets(html, url); | |
| 138 | for (const h of bad) report([{ check: "head-links", message: `"${h}" is not a URL`, section: s("icons") }]); | |
| 139 | for (const target of urls) { | |
| 140 | const status = await fetcher(target, { signal: AbortSignal.timeout(TIMEOUT_MS) }).then( | |
| 141 | async (r) => (await r.body?.cancel(), r.status), | |
| 142 | () => 0, | |
| 143 | ); | |
| 144 | if (status < 200 || status >= 300) report([{ check: "head-links", message: `${target} answered ${status || "nothing"}`, section: s("icons") }]); | |
| 145 | } | |
| 146 | report(headerProblems(res.headers, new URL(url).protocol === "https:")); | |
| 147 | const etag = res.headers.get("etag"); | |
| 148 | if (!etag) report([{ check: "etag", message: "no ETag on the HTML", section: s("caching") }]); | |
| 149 | else { | |
| 150 | const again = await fetcher(url, { headers: { accept: "text/html", "if-none-match": etag }, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) }).then( | |
| 151 | async (r) => (await r.body?.cancel(), r.status), | |
| 152 | () => 0, | |
| 153 | ); | |
| 154 | if (again !== 304) report([{ check: "etag", message: `If-None-Match answered ${again || "nothing"}, not 304`, section: s("caching") }]); | |
| 274 | if (page === null) continue; | |
| 275 | const key = new URL(page.url).pathname; | |
| 276 | if (seen.has(key)) continue; | |
| 277 | seen.add(key); | |
| 278 | // A 404 or 403 is a page this reader may not see, which is an answer; | |
| 279 | // a 5xx is a page that broke. | |
| 280 | if (page.res.status >= 500) out.push({ url: page.url, section: "reachable", why: `answers ${page.res.status}` }); | |
| 281 | if (page.res.status !== 200) continue; | |
| 282 | out.push(...headFindings(page.url, page.body), ...documentHeaderFindings(page.url, page.res.headers)); | |
| 283 | const head = headOf(page.body); | |
| 284 | const image = metaNamed(head, "property", "og:image")[0]?.["content"]; | |
| 285 | if (image) resources.set(image, { section: SECTION.social, from: page.url, type: /^image\// }); | |
| 286 | for (const link of tags(head, "link")) { | |
| 287 | const href = link["href"]; | |
| 288 | if (!href || href.startsWith("data:")) continue; | |
| 289 | if (relHas(link, "manifest")) resources.set(href, { section: SECTION.icons, from: page.url, type: /^application\/(manifest\+)?json/ }); | |
| 290 | else if (relHas(link, "icon") || relHas(link, "apple-touch-icon")) resources.set(href, { section: SECTION.icons, from: page.url, type: /^image\// }); | |
| 291 | else if (relHas(link, "stylesheet")) stylesheet ??= href; | |
| 155 | 292 | } |
| 156 | 293 | } |
| 157 | return findings; | |
| 294 | for (const [href, r] of resources) await loads(href, r.section, r.from, r.type); | |
| 295 | if (stylesheet !== undefined) { | |
| 296 | const sheet = await get(stylesheet); | |
| 297 | if (sheet) { | |
| 298 | out.push(...assetHeaderFindings(sheet.url, sheet.res.headers)); | |
| 299 | const etag = sheet.res.headers.get("etag"); | |
| 300 | if (etag) { | |
| 301 | const again = await get(stylesheet, { "if-none-match": etag }); | |
| 302 | if (again && again.res.status !== 304) | |
| 303 | out.push({ url: again.url, section: SECTION.caching, why: `If-None-Match with its own ETag answers ${again.res.status}, not 304` }); | |
| 304 | } | |
| 305 | } | |
| 306 | } | |
| 307 | ||
| 308 | // 3 — the well-known files. | |
| 309 | const robots = await get("/robots.txt"); | |
| 310 | if (robots) { | |
| 311 | if (robots.res.status !== 200) out.push({ url: robots.url, section: SECTION.wellKnown, why: `answers ${robots.res.status}` }); | |
| 312 | else out.push(...robotsFindings(robots.url, robots.body)); | |
| 313 | } | |
| 314 | const sitemap = await get("/sitemap.xml"); | |
| 315 | if (sitemap) { | |
| 316 | const locs = sitemapLocs(sitemap.body); | |
| 317 | if (sitemap.res.status !== 200 || locs.length === 0) out.push({ url: sitemap.url, section: SECTION.wellKnown, why: `answers ${sitemap.res.status} with ${locs.length} URLs` }); | |
| 318 | for (const loc of locs) { | |
| 319 | if (new URL(loc).origin !== root.origin) out.push({ url: sitemap.url, section: SECTION.wellKnown, why: `lists ${loc}, off this origin` }); | |
| 320 | } | |
| 321 | // A sitemap lists what a stranger may read: an entry that sends one to | |
| 322 | // sign in, or answers anything but 200, is a private URL published. | |
| 323 | for (const loc of locs.slice(0, options.sitemapSample ?? 20)) { | |
| 324 | const u = new URL(loc); | |
| 325 | if (u.origin !== root.origin) continue; | |
| 326 | const r = await get(u.pathname + u.search, { accept: ACCEPT_HTML }); | |
| 327 | if (r && r.res.status !== 200) out.push({ url: r.url, section: SECTION.wellKnown, why: `in the sitemap, answers a stranger ${r.res.status}` }); | |
| 328 | } | |
| 329 | } | |
| 330 | const security = await get("/.well-known/security.txt"); | |
| 331 | if (security) { | |
| 332 | if (security.res.status !== 200) out.push({ url: security.url, section: SECTION.wellKnown, why: `answers ${security.res.status}` }); | |
| 333 | else out.push(...securityTxtFindings(security.url, security.body, options.now ?? new Date())); | |
| 334 | } | |
| 335 | const manifest = await get("/manifest.webmanifest"); | |
| 336 | if (manifest) { | |
| 337 | let m: { name?: unknown; start_url?: unknown; icons?: unknown } = {}; | |
| 338 | try { | |
| 339 | m = JSON.parse(manifest.body) as typeof m; | |
| 340 | } catch {} | |
| 341 | if (manifest.res.status !== 200 || typeof m.name !== "string" || typeof m.start_url !== "string" || !Array.isArray(m.icons) || m.icons.length === 0) | |
| 342 | out.push({ url: manifest.url, section: SECTION.icons, why: "the manifest has no name, start_url or icons" }); | |
| 343 | else | |
| 344 | for (const icon of m.icons as { src?: unknown }[]) | |
| 345 | if (typeof icon.src === "string") await loads(icon.src, SECTION.icons, manifest.url, /^image\//); | |
| 346 | } | |
| 347 | const llms = await get("/llms.txt"); | |
| 348 | if (llms && (llms.res.status !== 200 || !llms.body.startsWith("# "))) | |
| 349 | out.push({ url: llms.url, section: SECTION.wellKnown, why: `answers ${llms.res.status}, wanted a markdown document under a # title` }); | |
| 350 | const change = await get("/.well-known/change-password"); | |
| 351 | if (change && !(change.res.status >= 300 && change.res.status < 400 && change.res.headers.get("location"))) | |
| 352 | out.push({ url: change.url, section: SECTION.wellKnown, why: `answers ${change.res.status}, wanted a redirect to where a password is changed` }); | |
| 353 | ||
| 354 | // 4 — a path nobody routes is a page for a person, not a bare status. | |
| 355 | const nowhere = await get(`/webspec-${crypto.randomUUID()}`, { accept: ACCEPT_HTML }); | |
| 356 | if (nowhere) { | |
| 357 | const type = nowhere.res.headers.get("content-type") ?? ""; | |
| 358 | if (nowhere.res.status !== 404) out.push({ url: nowhere.url, section: SECTION.errors, why: `an unrouted path answers ${nowhere.res.status}, not 404` }); | |
| 359 | else if (!type.startsWith("text/html")) out.push({ url: nowhere.url, section: SECTION.errors, why: `the 404 is ${type || "untyped"}, not a page` }); | |
| 360 | else out.push(...headFindings(nowhere.url, nowhere.body, 404), ...documentHeaderFindings(nowhere.url, nowhere.res.headers)); | |
| 361 | } | |
| 362 | return out; | |
| 158 | 363 | } |
src/web/chrome.ts +18
| @@ -84,6 +84,24 @@ export function notFoundPage(ctx: Ctx): Response { | ||
| 84 | 84 | |
| 85 | 85 | export const repoNotFound = notFoundPage; |
| 86 | 86 | |
| 87 | /** What a browser is shown when a handler broke: the fault stays in the log. */ | |
| 88 | export function serverErrorPage(ctx: Ctx): Response { | |
| 89 | return page( | |
| 90 | { | |
| 91 | ctx, | |
| 92 | title: "Something broke", | |
| 93 | body: html`<div class="page-head"><h1>500</h1></div> | |
| 94 | ${empty({ | |
| 95 | icon: "alert", | |
| 96 | title: "Something broke", | |
| 97 | note: "The forge could not answer this. It has been logged; trying again may work.", | |
| 98 | action: btn("Go home", { href: "/", variant: "primary" }), | |
| 99 | })}`, | |
| 100 | }, | |
| 101 | 500, | |
| 102 | ); | |
| 103 | } | |
| 104 | ||
| 87 | 105 | /** Send an anonymous visitor to sign in, and back where they were going. */ |
| 88 | 106 | export function signInFirst(ctx: Ctx): Response { |
| 89 | 107 | return redirect(signInHref(ctx)); |
src/web/layout.ts +17 −4
| @@ -13,7 +13,7 @@ import { listReposVisibleTo } from "../core/repos.ts"; | ||
| 13 | 13 | import type { User } from "../core/users.ts"; |
| 14 | 14 | import type { Ctx } from "../http/context.ts"; |
| 15 | 15 | import { activeEdgeToken, edgeLoginUrl, edgeLogoutUrl, edgeStrangerLogin } from "../http/edge.ts"; |
| 16 | import { json } from "../http/respond.ts"; | |
| 16 | import { HSTS_SECONDS, json, PERMISSIONS_POLICY } from "../http/respond.ts"; | |
| 17 | 17 | import { sha256 } from "../kernel/hash.ts"; |
| 18 | 18 | import { secret } from "../kernel/id.ts"; |
| 19 | 19 | import { runningLine } from "../kernel/version.ts"; |
| @@ -590,9 +590,13 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 590 | 590 | // the same bytes, or the difference tells a guesser something. |
| 591 | 591 | status === 200 |
| 592 | 592 | ? html`<meta |
| 593 | property="og:url" | |
| 594 | content="${ctx.url.origin}${ctx.url.pathname}" | |
| 595 | />` | |
| 593 | property="og:url" | |
| 594 | content="${ctx.url.origin}${ctx.url.pathname}" | |
| 595 | /> | |
| 596 | <link | |
| 597 | rel="canonical" | |
| 598 | href="${ctx.url.origin}${ctx.url.pathname}" | |
| 599 | />` | |
| 596 | 600 | : null |
| 597 | 601 | } |
| 598 | 602 | <meta |
| @@ -630,6 +634,10 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 630 | 634 | />`, |
| 631 | 635 | )} |
| 632 | 636 | ${when(options.refresh, refreshMeta)} |
| 637 | <meta | |
| 638 | name="color-scheme" | |
| 639 | content="${theme ? THEMES[theme].appearance : "light dark"}" | |
| 640 | /> | |
| 633 | 641 | ${theme |
| 634 | 642 | ? html`<meta name="theme-color" content="${metaThemeColor(theme)}" />` |
| 635 | 643 | : html`<meta |
| @@ -684,11 +692,16 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 684 | 692 | "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}${options.turnstile ? ` ${TURNSTILE_ORIGIN}` : ""}; connect-src 'self'${options.turnstile ? ` ${TURNSTILE_ORIGIN}` : ""}; ${options.turnstile ? `frame-src ${TURNSTILE_ORIGIN}; ` : ""}worker-src 'self'; manifest-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`, |
| 685 | 693 | "referrer-policy": "same-origin", |
| 686 | 694 | "x-content-type-options": "nosniff", |
| 695 | "permissions-policy": PERMISSIONS_POLICY, | |
| 687 | 696 | // Markup is revalidated every time; only the hashed assets it names are |
| 688 | 697 | // cached, so no cache can pair new HTML with an old stylesheet. |
| 689 | 698 | "cache-control": "no-cache", |
| 690 | 699 | link: linkHeader(links), |
| 691 | 700 | }); |
| 701 | // Over https a browser is told to stay there for a year; over plain http | |
| 702 | // (a laptop, a test) the header means nothing and is not sent. | |
| 703 | if (ctx.url.protocol === "https:") | |
| 704 | headers.set("strict-transport-security", `max-age=${HSTS_SECONDS}`); | |
| 692 | 705 | // A flash is shown exactly once: rendering it is also what clears it. |
| 693 | 706 | if (flash) headers.append("set-cookie", clearFlashCookie(ctx.url)); |
| 694 | 707 | return new Response(doc.text, { status, headers }); |
test/webspec.test.ts +247 −138
| @@ -1,145 +1,254 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { webspec } from "../src/release/webspec.ts"; | |
| 1 | /** | |
| 2 | * The website specification's checks 1–4 (`release/webspec.ts`) hold for | |
| 3 | * every page forge.json names as a look, as a stranger and as the admin, | |
| 4 | * and each check catches the fault it names — a check that cannot fail is | |
| 5 | * not a check (#2915). | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import forgeJson from "../forge.json" with { type: "json" }; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { HSTS_SECONDS, PERMISSIONS_POLICY } from "../src/http/respond.ts"; | |
| 16 | import { failure, serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { | |
| 18 | assetHeaderFindings, | |
| 19 | attributes, | |
| 20 | documentHeaderFindings, | |
| 21 | headFindings, | |
| 22 | robotsFindings, | |
| 23 | securityTxtFindings, | |
| 24 | webspec, | |
| 25 | type Finding, | |
| 26 | } from "../src/release/webspec.ts"; | |
| 27 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 3 | 28 | |
| 4 | const GOOD_HTML = `<!doctype html><html lang="en"><head><meta charset="utf-8"> | |
| 5 | <meta name="viewport" content="width=device-width, initial-scale=1"><title>Home</title> | |
| 6 | <meta name="description" content="d"><link rel="canonical" href="https://x.test/"> | |
| 7 | <meta name="theme-color" content="#fff" media="(prefers-color-scheme: light)"> | |
| 8 | <meta name="theme-color" content="#000" media="(prefers-color-scheme: dark)"> | |
| 9 | <meta name="color-scheme" content="light dark"> | |
| 10 | <meta property="og:title" content="t"><meta property="og:type" content="website"><meta property="og:url" content="https://x.test/"> | |
| 11 | <meta property="og:description" content="d"><meta property="og:image" content="https://x.test/og.png"> | |
| 12 | <link rel="icon" href="/icon.svg"><link rel="manifest" href="/m.json"></head><body>hi</body></html>`; | |
| 29 | const lines = (fs: Finding[]) => fs.map((f) => `${f.url} [${f.section}] ${f.why}`); | |
| 13 | 30 | |
| 14 | const GOOD_HEADERS: Record<string, string> = { | |
| 15 | "content-type": "text/html", | |
| 16 | "content-security-policy": "default-src 'self'; script-src 'self'; frame-ancestors 'none'", | |
| 17 | "x-content-type-options": "nosniff", | |
| 18 | "referrer-policy": "same-origin", | |
| 19 | "permissions-policy": "camera=()", | |
| 20 | "strict-transport-security": "max-age=63072000", | |
| 21 | "cache-control": "no-cache", | |
| 22 | etag: '"v1"', | |
| 23 | }; | |
| 31 | describe("the forge against the website specification", () => { | |
| 32 | let dataDir: string; | |
| 33 | let app: App; | |
| 34 | let servers: Servers; | |
| 35 | let base: string; | |
| 24 | 36 | |
| 25 | function site(html = GOOD_HTML, headers: Record<string, string> = GOOD_HEADERS, extra: Record<string, number> = {}) { | |
| 26 | return async (input: string, init?: RequestInit) => { | |
| 27 | const u = new URL(input); | |
| 28 | if (u.pathname in extra) return new Response("x", { status: extra[u.pathname]! }); | |
| 29 | if (u.pathname === "/icon.svg" || u.pathname === "/m.json") return new Response("x"); | |
| 30 | const h = new Headers(init?.headers); | |
| 31 | if (h.get("if-none-match") && headers["etag"] === h.get("if-none-match")) return new Response(null, { status: 304 }); | |
| 32 | return new Response(html, { headers }); | |
| 33 | }; | |
| 34 | } | |
| 35 | ||
| 36 | const checks = async (html?: string, headers?: Record<string, string>, extra?: Record<string, number>) => | |
| 37 | (await webspec("https://x.test", ["/"], site(html, headers, extra))).map((f) => f.check); | |
| 38 | const without = (k: string) => Object.fromEntries(Object.entries(GOOD_HEADERS).filter(([n]) => n !== k)); | |
| 39 | ||
| 40 | test("a page meeting every check has no findings", async () => { | |
| 41 | expect(await webspec("https://x.test", ["/"], site())).toEqual([]); | |
| 42 | }); | |
| 43 | ||
| 44 | test("each head check yields exactly its finding", async () => { | |
| 45 | const cases: [string, string, string][] = [ | |
| 46 | ["doctype", GOOD_HTML.replace("<!doctype html>", ""), "doctype"], | |
| 47 | ["lang", GOOD_HTML.replace(' lang="en"', ""), "lang"], | |
| 48 | ["charset", GOOD_HTML.replace('<meta charset="utf-8">', ""), "charset"], | |
| 49 | ["zoom", GOOD_HTML.replace("initial-scale=1", "maximum-scale=1"), "viewport"], | |
| 50 | ["user-scalable", GOOD_HTML.replace("initial-scale=1", "user-scalable=no"), "viewport"], | |
| 51 | ["two titles", GOOD_HTML.replace("</head>", "<title>b</title></head>"), "title"], | |
| 52 | ["no title", GOOD_HTML.replace("<title>Home</title>", ""), "title"], | |
| 53 | ["description", GOOD_HTML.replace('<meta name="description" content="d">', ""), "description"], | |
| 54 | ["canonical missing", GOOD_HTML.replace(/<link rel="canonical"[^>]*>/, ""), "canonical"], | |
| 55 | ["canonical differs", GOOD_HTML.replace('canonical" href="https://x.test/"', 'canonical" href="https://x.test/a"'), "canonical"], | |
| 56 | ["dark theme", GOOD_HTML.replace(/<meta name="theme-color" content="#000"[^>]*>/, ""), "theme-color"], | |
| 57 | ["color-scheme", GOOD_HTML.replace('<meta name="color-scheme" content="light dark">', ""), "color-scheme"], | |
| 58 | ["og:image", GOOD_HTML.replace(/<meta property="og:image"[^>]*>/, ""), "open-graph"], | |
| 59 | ]; | |
| 60 | for (const [name, html, check] of cases) expect([name, await checks(html)]).toEqual([name, [check]]); | |
| 61 | }); | |
| 62 | ||
| 63 | test("icons and the manifest must resolve", async () => { | |
| 64 | expect(await checks(undefined, undefined, { "/icon.svg": 404 })).toEqual(["head-links"]); | |
| 65 | expect(await checks(undefined, undefined, { "/m.json": 500 })).toEqual(["head-links"]); | |
| 66 | }); | |
| 67 | ||
| 68 | test("each header check yields exactly its finding", async () => { | |
| 69 | const h = (k: string, v: string) => ({ ...GOOD_HEADERS, [k]: v }); | |
| 70 | const cases: [string, Record<string, string>, string][] = [ | |
| 71 | ["csp missing", without("content-security-policy"), "csp"], | |
| 72 | ["unsafe-eval", h("content-security-policy", "script-src 'self' 'unsafe-eval'; frame-ancestors 'none'"), "csp"], | |
| 73 | ["unsafe-inline script", h("content-security-policy", "script-src 'self' 'unsafe-inline'; frame-ancestors 'none'"), "csp"], | |
| 74 | ["frame-ancestors", h("content-security-policy", "script-src 'self'"), "frame-ancestors"], | |
| 75 | ["nosniff", without("x-content-type-options"), "nosniff"], | |
| 76 | ["referrer", without("referrer-policy"), "referrer-policy"], | |
| 77 | ["permissions", without("permissions-policy"), "permissions-policy"], | |
| 78 | ["xss", h("x-xss-protection", "1"), "x-xss-protection"], | |
| 79 | ["immutable html", h("cache-control", "public, max-age=1, immutable"), "cache-html"], | |
| 80 | ["etag", without("etag"), "etag"], | |
| 81 | ]; | |
| 82 | for (const [name, headers, check] of cases) expect([name, await checks(undefined, headers)]).toEqual([name, [check]]); | |
| 83 | }); | |
| 84 | ||
| 85 | test("style-src unsafe-inline is not a script finding", async () => { | |
| 86 | const csp = "script-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'"; | |
| 87 | expect(await checks(undefined, { ...GOOD_HEADERS, "content-security-policy": csp })).toEqual([]); | |
| 88 | }); | |
| 89 | ||
| 90 | test("HSTS is an edge finding on https only", async () => { | |
| 91 | const found = await webspec("https://x.test", ["/"], site(GOOD_HTML, without("strict-transport-security"))); | |
| 92 | expect(found.map((f) => [f.check, f.edge])).toEqual([["hsts", true]]); | |
| 93 | expect(await webspec("http://x.test", ["/"], site(GOOD_HTML, without("strict-transport-security")))).toEqual([]); | |
| 94 | }); | |
| 95 | ||
| 96 | test("an ETag that does not answer 304 is a finding", async () => { | |
| 97 | const f = async (input: string) => | |
| 98 | input.endsWith(".svg") || input.endsWith(".json") ? new Response("x") : new Response(GOOD_HTML, { headers: GOOD_HEADERS }); | |
| 99 | const found = await webspec("https://x.test", ["/"], f); | |
| 100 | expect(found.map((x) => x.check)).toEqual(["etag"]); | |
| 101 | }); | |
| 102 | ||
| 103 | test("findings are plain data citing a section; failures to fetch are findings", async () => { | |
| 104 | const [f] = await webspec("https://x.test", ["/a"], site(GOOD_HTML.replace(' lang="en"', ""))); | |
| 105 | expect(f).toEqual({ path: "/a", check: "lang", message: expect.any(String), section: "https://specification.website/#lang" }); | |
| 106 | const down = await webspec("https://x.test", ["/"], async () => { | |
| 107 | throw new Error("boom"); | |
| 37 | beforeAll(async () => { | |
| 38 | dataDir = await mkdtemp(join(tmpdir(), "forge-webspec-")); | |
| 39 | app = createApp({ dataDir, port: 0 }); | |
| 40 | servers = await serve(app); | |
| 41 | base = servers.url; | |
| 42 | const a = await createUser(app.db, { origin: "seed", trusted: true, | |
| 43 | username: "alice", | |
| 44 | email: "[email protected]", | |
| 45 | password: "a-good-passphrase", | |
| 46 | adminIfFirst: true, | |
| 47 | }); | |
| 48 | if (!a.ok) throw new Error(a.error); | |
| 49 | const pub = await createRepo(app, a.value, { name: "open", visibility: "public" }); | |
| 50 | if (!pub.ok) throw new Error(String(pub.error)); | |
| 51 | const priv = await createRepo(app, a.value, { name: "closed", visibility: "private" }); | |
| 52 | if (!priv.ok) throw new Error(String(priv.error)); | |
| 108 | 53 | }); |
| 109 | expect(down.map((x) => x.check)).toEqual(["fetch"]); | |
| 110 | }); | |
| 111 | 54 | |
| 112 | test("a page that does not answer 2xx is a fetch finding", async () => { | |
| 113 | const f = async () => new Response("nope", { status: 500 }); | |
| 114 | const found = await webspec("https://x.test", ["/"], f); | |
| 115 | expect(found.map((x) => x.check)).toEqual(["fetch"]); | |
| 116 | }); | |
| 117 | ||
| 118 | test("default-src 'unsafe-inline' counts when there is no script-src", async () => { | |
| 119 | const csp = "default-src 'self' 'unsafe-inline'; frame-ancestors 'none'"; | |
| 120 | expect(await checks(undefined, { ...GOOD_HEADERS, "content-security-policy": csp })).toEqual(["csp"]); | |
| 121 | }); | |
| 122 | ||
| 123 | test("the http-equiv charset form is accepted", async () => { | |
| 124 | const html = GOOD_HTML.replace('<meta charset="utf-8">', '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'); | |
| 125 | expect(await checks(html)).toEqual([]); | |
| 126 | }); | |
| 127 | ||
| 128 | test("apple-touch-icon must resolve, and an invalid href is a finding", async () => { | |
| 129 | const html = GOOD_HTML.replace("</head>", '<link rel="apple-touch-icon" href="/touch.png"></head>'); | |
| 130 | expect(await checks(html, undefined, { "/touch.png": 404 })).toEqual(["head-links"]); | |
| 131 | expect(await checks(html, undefined, { "/touch.png": 200 })).toEqual([]); | |
| 132 | const bad = GOOD_HTML.replace("</head>", '<link rel="icon" href="http://[bad"></head>'); | |
| 133 | expect(await checks(bad)).toEqual(["head-links"]); | |
| 134 | }); | |
| 135 | ||
| 136 | test("every fetch carries a timeout signal", async () => { | |
| 137 | const seen: boolean[] = []; | |
| 138 | const inner = site(); | |
| 139 | await webspec("https://x.test", ["/"], async (u, init) => { | |
| 140 | seen.push(init?.signal instanceof AbortSignal); | |
| 141 | return inner(u, init); | |
| 55 | afterAll(async () => { | |
| 56 | servers.stop(); | |
| 57 | app.close(); | |
| 58 | await rm(dataDir, { recursive: true, force: true }); | |
| 59 | }); | |
| 60 | ||
| 61 | const paths = () => [...forgeJson.app.looks, "/alice", "/alice/open", "/alice/open/issues"]; | |
| 62 | ||
| 63 | test("a stranger's every look passes, with the well-known files and the 404", async () => { | |
| 64 | expect(lines(await webspec(base, { paths: paths() }))).toEqual([]); | |
| 65 | }); | |
| 66 | ||
| 67 | test("the admin's every look passes", async () => { | |
| 68 | const token = tokenFor(app, "alice", "admin"); | |
| 69 | const found = await webspec(base, { paths: paths(), headers: { authorization: `Bearer ${token}` } }); | |
| 70 | expect(lines(found)).toEqual([]); | |
| 71 | }); | |
| 72 | ||
| 73 | test("a sitemap entry a stranger cannot read is caught", async () => { | |
| 74 | const fetchWith: typeof fetch = Object.assign( | |
| 75 | async (input: string | URL | Request, init?: RequestInit) => { | |
| 76 | const url = new URL(String(input)); | |
| 77 | if (url.pathname === "/sitemap.xml") | |
| 78 | return new Response(`<urlset><url><loc>${base}/alice/closed</loc></url></urlset>`, { headers: { "content-type": "application/xml" } }); | |
| 79 | return fetch(input, init); | |
| 80 | }, | |
| 81 | { preconnect: fetch.preconnect }, | |
| 82 | ); | |
| 83 | const found = await webspec(base, { paths: ["/"], fetch: fetchWith }); | |
| 84 | expect(lines(found)).toEqual([`${base}/alice/closed [Well-known files] in the sitemap, answers a stranger 404`]); | |
| 85 | }); | |
| 86 | }); | |
| 87 | ||
| 88 | describe("what the forge sends beyond what it sent before", () => { | |
| 89 | let dataDir: string; | |
| 90 | let app: App; | |
| 91 | let servers: Servers; | |
| 92 | ||
| 93 | beforeAll(async () => { | |
| 94 | dataDir = await mkdtemp(join(tmpdir(), "forge-webspec-https-")); | |
| 95 | // Served behind a proxy that terminates TLS: the public URL is https. | |
| 96 | app = createApp({ dataDir, port: 0, url: "https://forge.example" }); | |
| 97 | servers = await serve(app); | |
| 98 | }); | |
| 99 | ||
| 100 | afterAll(async () => { | |
| 101 | servers.stop(); | |
| 102 | app.close(); | |
| 103 | await rm(dataDir, { recursive: true, force: true }); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a page over https asks to stay there for a year and names its canonical address", async () => { | |
| 107 | const res = await fetch(`${servers.url}/explore`, { headers: { accept: "text/html" } }); | |
| 108 | expect(res.status).toBe(200); | |
| 109 | expect(res.headers.get("strict-transport-security")).toBe(`max-age=${HSTS_SECONDS}`); | |
| 110 | expect(res.headers.get("permissions-policy")).toBe(PERMISSIONS_POLICY); | |
| 111 | const body = await res.text(); | |
| 112 | expect(body).toMatch(/<link\s+rel="canonical"\s+href="https:\/\/forge\.example\/explore"/); | |
| 113 | expect(documentHeaderFindings("https://forge.example/explore", res.headers)).toEqual([]); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a response that is not a page carries the permissions policy too", async () => { | |
| 117 | const res = await fetch(`${servers.url}/api/v1/nowhere`); | |
| 118 | expect(res.headers.get("permissions-policy")).toBe(PERMISSIONS_POLICY); | |
| 119 | }); | |
| 120 | ||
| 121 | test("a handler that throws shows a browser a 500 page and anything else a bare body", async () => { | |
| 122 | const page = failure(app, new Error("boom"), new Request("http://x/explore", { headers: { accept: "text/html" } })); | |
| 123 | expect(page.status).toBe(500); | |
| 124 | expect(page.headers.get("content-type")).toStartWith("text/html"); | |
| 125 | const body = await page.text(); | |
| 126 | expect(body).toContain("<h1>500</h1>"); | |
| 127 | // The fault itself is never shown, and a broken page is not a place. | |
| 128 | expect(body).not.toContain("boom"); | |
| 129 | expect(headFindings("https://forge.example/explore", body, 500)).toEqual([]); | |
| 130 | expect(documentHeaderFindings("https://forge.example/explore", page.headers).map((f) => f.why)).toEqual([]); | |
| 131 | const api = failure(app, new Error("boom"), new Request("http://x/api/v1/x", { headers: { accept: "text/html" } })); | |
| 132 | expect(await api.json()).toEqual({ error: "internal" }); | |
| 133 | const bare = failure(app, new Error("boom")); | |
| 134 | expect(bare.headers.get("content-type")).toStartWith("application/json"); | |
| 135 | }); | |
| 136 | }); | |
| 137 | ||
| 138 | describe("each check catches what it names", () => { | |
| 139 | const url = "https://forge.example/x"; | |
| 140 | const good = `<!doctype html><html lang="en"><head><meta charset="utf-8"> | |
| 141 | <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 142 | <title>x</title><meta name="description" content="d"><meta name="color-scheme" content="light dark"> | |
| 143 | <meta name="theme-color" media="(prefers-color-scheme: light)" content="#fff"> | |
| 144 | <meta name="theme-color" media="(prefers-color-scheme: dark)" content="#000"> | |
| 145 | <meta property="og:title" content="x"><meta property="og:description" content="d"> | |
| 146 | <meta property="og:type" content="website"><meta property="og:image" content="https://forge.example/og.png"> | |
| 147 | <meta property="og:url" content="${url}"><link rel="canonical" href="${url}"> | |
| 148 | <link rel="icon" href="/i.png"><link rel="manifest" href="/m.json"></head><body></body></html>`; | |
| 149 | const whys = (html: string, status = 200) => headFindings(url, html, status).map((f) => f.why); | |
| 150 | ||
| 151 | test("a whole head has nothing to say", () => { | |
| 152 | expect(whys(good)).toEqual([]); | |
| 153 | }); | |
| 154 | ||
| 155 | test("each missing or wrong piece of the head is named", () => { | |
| 156 | expect(whys(good.replace("<!doctype html>", ""))).toEqual(["does not start with <!doctype html>"]); | |
| 157 | expect(whys(good.replace(' lang="en"', ""))).toEqual(["<html> has no lang"]); | |
| 158 | expect(whys(good.replace('<meta charset="utf-8">', ""))).toEqual(["no <meta charset=utf-8> in the first 1024 bytes"]); | |
| 159 | expect(whys(good.replace("initial-scale=1", "user-scalable=no"))).toEqual(["viewport forbids zoom (user-scalable=no)"]); | |
| 160 | expect(whys(good.replace("initial-scale=1", "maximum-scale=1"))).toEqual(["viewport caps zoom at maximum-scale=1"]); | |
| 161 | expect(whys(good.replace("<title>x</title>", "<title>x</title><title>y</title>"))).toEqual(["2 <title> elements, wanted one"]); | |
| 162 | expect(whys(good.replace('<meta name="description" content="d">', ""))).toEqual(["no meta description"]); | |
| 163 | expect(whys(good.replace('<meta name="color-scheme" content="light dark">', ""))).toEqual(["no meta color-scheme"]); | |
| 164 | expect(whys(good.replace('media="(prefers-color-scheme: dark)"', 'media="print"'))).toEqual([ | |
| 165 | "theme-color has no (prefers-color-scheme: dark) half", | |
| 166 | ]); | |
| 167 | expect(whys(good.replace('<link rel="canonical" href="https://forge.example/x">', ""))).toEqual(["no <link rel=canonical>"]); | |
| 168 | expect(whys(good.replace('rel="canonical" href="https://forge.example/x"', 'rel="canonical" href="https://forge.example/y"'))).toEqual([ | |
| 169 | `rel=canonical https://forge.example/y is not og:url ${url}`, | |
| 170 | ]); | |
| 171 | expect(whys(good.replace('content="https://forge.example/og.png"', 'content="/og.png"'))).toEqual(["og:image is not an absolute URL"]); | |
| 172 | expect(whys(good.replace('<link rel="icon" href="/i.png">', ""))).toEqual(["no <link rel=icon>"]); | |
| 173 | expect(whys(good.replace('<link rel="manifest" href="/m.json">', ""))).toEqual(["no <link rel=manifest>"]); | |
| 174 | }); | |
| 175 | ||
| 176 | test("an error page names no canonical address", () => { | |
| 177 | expect(whys(good, 404)).toEqual(["an error page names a canonical address"]); | |
| 178 | }); | |
| 179 | ||
| 180 | test("a document's headers are held to the security floor", () => { | |
| 181 | const floor = { | |
| 182 | "content-security-policy": "default-src 'none'; script-src 'nonce-a'; frame-ancestors 'none'", | |
| 183 | "x-content-type-options": "nosniff", | |
| 184 | "referrer-policy": "same-origin", | |
| 185 | "permissions-policy": "camera=()", | |
| 186 | "strict-transport-security": "max-age=31536000", | |
| 187 | "cache-control": "no-cache", | |
| 188 | }; | |
| 189 | const headers = (over: Record<string, string | null>) => { | |
| 190 | const h = new Headers(floor); | |
| 191 | for (const [k, v] of Object.entries(over)) v === null ? h.delete(k) : h.set(k, v); | |
| 192 | return documentHeaderFindings(url, h).map((f) => f.why); | |
| 193 | }; | |
| 194 | expect(headers({})).toEqual([]); | |
| 195 | expect(headers({ "content-security-policy": "script-src 'self' 'unsafe-eval' 'unsafe-inline'" })).toEqual([ | |
| 196 | "script-src allows 'unsafe-eval'", | |
| 197 | "script-src allows 'unsafe-inline'", | |
| 198 | "no frame-ancestors (nor X-Frame-Options)", | |
| 199 | ]); | |
| 200 | expect(headers({ "x-content-type-options": null })).toEqual(["no X-Content-Type-Options: nosniff"]); | |
| 201 | expect(headers({ "referrer-policy": "unsafe-url" })).toEqual(["Referrer-Policy unsafe-url sends the full URL off-site"]); | |
| 202 | expect(headers({ "permissions-policy": null })).toEqual(["no Permissions-Policy"]); | |
| 203 | expect(headers({ "x-xss-protection": "1; mode=block" })).toEqual(["X-XSS-Protection: 1; mode=block (send none, or 0)"]); | |
| 204 | expect(headers({ "x-xss-protection": "0" })).toEqual([]); | |
| 205 | expect(headers({ "strict-transport-security": "max-age=300" })).toEqual(["HSTS max-age 300 is under a year"]); | |
| 206 | expect(headers({ "cache-control": "public, max-age=600" })).toEqual([ | |
| 207 | "HTML is cached without revalidation (cache-control: public, max-age=600)", | |
| 208 | ]); | |
| 209 | // The edge in front of the app may own HSTS, so its finding says so; no other does. | |
| 210 | const short = new Headers(floor); | |
| 211 | short.set("strict-transport-security", "max-age=300"); | |
| 212 | expect(documentHeaderFindings(url, short).map((f) => f.edge)).toEqual([true]); | |
| 213 | expect(documentHeaderFindings(url, new Headers({ ...floor, "permissions-policy": "" }))[0]?.edge).toBeUndefined(); | |
| 214 | // HSTS means nothing over plain http, so it is not asked for there. | |
| 215 | const plain = new Headers(floor); | |
| 216 | plain.delete("strict-transport-security"); | |
| 217 | expect(documentHeaderFindings("http://localhost/", plain)).toEqual([]); | |
| 218 | }); | |
| 219 | ||
| 220 | test("a hashed asset must be immutable and revalidatable", () => { | |
| 221 | const ok = new Headers({ "cache-control": "public, max-age=31536000, immutable", etag: '"a"', "x-content-type-options": "nosniff" }); | |
| 222 | expect(assetHeaderFindings(url, ok)).toEqual([]); | |
| 223 | const bad = new Headers({ "cache-control": "max-age=60" }); | |
| 224 | expect(assetHeaderFindings(url, bad).map((f) => f.why)).toEqual([ | |
| 225 | "a hashed asset is not cached for a year as immutable (cache-control: max-age=60)", | |
| 226 | "no ETag or Last-Modified to revalidate with", | |
| 227 | "no X-Content-Type-Options: nosniff", | |
| 228 | ]); | |
| 229 | }); | |
| 230 | ||
| 231 | test("robots must name its sitemap, security.txt must not be expired", () => { | |
| 232 | expect(robotsFindings(url, "User-agent: *\nDisallow: /settings\n").map((f) => f.why)).toEqual([ | |
| 233 | "robots.txt names no Sitemap by absolute URL", | |
| 234 | ]); | |
| 235 | const now = new Date("2026-10-19T00:00:00Z"); | |
| 236 | expect(securityTxtFindings(url, "Contact: https://a/\nExpires: 2027-01-01T00:00:00Z\n", now)).toEqual([]); | |
| 237 | expect(securityTxtFindings(url, "Contact: https://a/\nExpires: 2026-01-01T00:00:00Z\n", now).map((f) => f.why)).toEqual([ | |
| 238 | "security.txt expired 2026-01-01T00:00:00Z", | |
| 239 | ]); | |
| 240 | expect(securityTxtFindings(url, "Expires: soon\n", now).map((f) => f.why)).toEqual([ | |
| 241 | "security.txt has no Contact", | |
| 242 | "security.txt has no valid Expires", | |
| 243 | ]); | |
| 244 | }); | |
| 245 | ||
| 246 | test("attributes read every quoting a tag is written with", () => { | |
| 247 | expect(attributes(`<link rel=icon href='/a.png' data-x="a & b" hidden>`)).toEqual({ | |
| 248 | rel: "icon", | |
| 249 | href: "/a.png", | |
| 250 | "data-x": "a & b", | |
| 251 | hidden: "", | |
| 252 | }); | |
| 142 | 253 | }); |
| 143 | expect(seen.length).toBeGreaterThan(3); | |
| 144 | expect(seen.every(Boolean)).toBe(true); | |
| 145 | 254 | }); |
new above
offline
Low: this is the same year as
HSTS_SECONDSinhttp/respond.ts, and the literal31_536_000inassetHeaderFindingsis the same number again. One named constant would keep the checker and the server from drifting apart.