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

The 404 page says what happened in one line and offers home, search and the last page visited #14163

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/14140-the-404-page-says-what-happened-in-one-l → main 9 commits fork 3 threads · 3 unresolved

  • Merged. torque/14140-the-404-page-says-what-happened-in-one-l was merged into main as 67953be.

Review

Sign in to review this change.
13 files changed +105 −25
docs/features/README.md +1
@@ -81,6 +81,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
8181 - [`g` then a letter: jump between pages](go-jumps.md)
8282 - [Hotkey hints](hotkey-hints.md)
8383 - [The 404 offers the pages nearest the path asked](near-pages.md)
84 - [The 404 says what happened in one line and offers home, sign-in and search](not-found-page.md)
8485 - [Lists that ask for a decision answer the same keys](decision-keys.md)
8586 - [Page help (`? Help`)](page-help.md)
8687 - [Palette rows: numbers, people, settings, actions](palette-rows.md)
docs/features/not-found-page.md added +14
@@ -0,0 +1,14 @@
1 # The 404 page
2
3 A dead end says what happened in one line and gives a way on.
4
5 - **The sentence:** "The page you asked for does not exist, or is not visible to you" —
6 the same words for a missing page and one you may not see.
7 - **The path asked for,** once, escaped, never placed in an attribute.
8 - **Home:** a "Go home" link always, with "Sign in" beside it when signed out.
9 - **Search:** one plain GET form to `/search`; for a path shaped `/owner/name` the box
10 starts with that name.
11 - **Near misses:** pages and repositories you can see with a similar name.
12 - **The API** stays JSON; a dead `/go/:code` shows no path and no sign-in.
13
14 In the terminal, the palette's "owner/name" prompt answers a miss with the same sentence.
src/http/server.ts +1 −1
@@ -1262,7 +1262,7 @@ export function buildRouter(): Router<Handler> {
12621262 ctx.app.config.dataDir,
12631263 ctx.params.code ?? "",
12641264 );
1265 if (target === undefined) return notFoundPage(ctx, { plain: true });
1265 if (target === undefined) return notFoundPage(ctx, { plain: true, noEcho: true });
12661266 return new Response(null, {
12671267 status: 303,
12681268 headers: { location: target, "cache-control": "no-store" },
src/tui/forge.ts +1 −1
@@ -327,7 +327,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
327327 }).map((p) => p.href);
328328 return near.length === 0
329329 ? pages.length === 0
330 ? "not found"
330 ? "not found — it does not exist, or is not visible to you"
331331 : `not found — pages like it, on the web: ${pages.join(", ")}`
332332 : `not found — did you mean ${near.map((r) => `${r.ownerName}/${r.name}`).join(", ")}?`;
333333 }
src/web/chrome.ts +9 −8
@@ -72,8 +72,8 @@ export function crumbsFor(repo: Repo): { label: string; href: string }[] {
7272 /** The one 404 in the product: same words for "no such thing" and "not
7373 * yours to see". With no session, on a GET, it also offers sign-in back to
7474 * this address; `plain` leaves that out for a miss that must reveal nothing
75 * (a dead `/go/:code`). */
76 export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response {
75 * (a dead `/go/:code`), and `noEcho` leaves out the path it echoes. */
76 export function notFoundPage(ctx: Ctx, opts: { plain?: boolean; noEcho?: boolean } = {}): Response {
7777 // A machine path, anything under `/assets/` (a reserved owner, so `/assets/x.woff2` lands on a
7878 // repository route), or a miss at the owner level (no repository named), may be the few typed
7979 // bytes; a person's missing repo file (`/o/r/blob/x.md`) keeps the page and its nearby links.
@@ -95,10 +95,11 @@ export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response
9595 ? html``
9696 : html`<p class="muted">Try ${tries.map((t, i) => html`${i > 0 ? ", " : ""}${t}`)}</p>`;
9797 const term = get ? searchTermFor(ctx.url.pathname) : undefined;
98 const hint =
99 term === undefined
100 ? html``
101 : html`<p class="muted"><a href="/search?q=${encodeURIComponent(term)}">Search for ${term}</a></p>`;
98 const asked = ctx.url.pathname.length > 120 ? `${ctx.url.pathname.slice(0, 120)}…` : ctx.url.pathname;
99 const find = html`<form method="get" action="/search" role="search" class="row">
100 <input type="search" name="q" aria-label="Search this forge" placeholder="Search this forge" value="${term ?? ""}" autocomplete="off" />
101 <button type="submit">Search</button>
102 </form>`;
102103 const id = requestId();
outdated

Principle 1/7: a bordered-feeling row form plus the existing Search for <term> link duplicates search; drop the older link or fold it into the form (prefill value with the term, escaped).

103104 const offerSignIn = get && ctx.auth.user === undefined;
104105 const res = page(
@@ -111,9 +112,9 @@ export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response
111112 title: "Nothing here",
112113 note: "The page you asked for does not exist, or is not visible to you.",
113114 action: offerSignIn
114 ? btn("Sign in", { href: notFoundSignIn(ctx), variant: "primary" })
115 ? html`${btn("Go home", { href: "/", variant: "primary" })} ${btn("Sign in", { href: notFoundSignIn(ctx) })}`
115116 : btn("Go home", { href: "/", variant: "primary" }),
116 })}${didYouMean}${hint}${disclosure("Request id", html`<p class="muted small">Quote <code>${id}</code> if you ask about this page.</p>`, { small: true })}`,
117 })}${opts.noEcho ? html`` : html`<p class="muted">Asked for <code>${asked}</code></p>`}${find}${didYouMean}${disclosure("Request id", html`<p class="muted small">Quote <code>${id}</code> if you ask about this page.</p>`, { small: true })}`,
117118 },
118119 404,
119120 );
test/boards-doors.test.ts +1 −1
@@ -90,7 +90,7 @@ describe("/boards doors", () => {
9090 expect(r.status).toBe(303);
9191 expect(r.headers.get("location")).toStartWith("/signin");
9292 } else expect(r.status, path).toBe(404);
93 const body = await r.text();
93 const body = (await r.text()).replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, "");
9494 expect(body).not.toContain("One");
9595 expect(body).not.toContain("/boards/mine");
9696 }
test/file-hold-form.test.ts +2 −1
@@ -68,7 +68,8 @@ describe("the file hold form", () => {
6868 body: (await res.text())
6969 .replace(/nonce="[^"]*"/g, 'nonce=""')
7070 .replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>")
71 .replaceAll(encodeURIComponent(asked), "ASKED"),
71 .replaceAll(encodeURIComponent(asked), "ASKED")
72 .replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, ""),
7273 });
7374
7475 beforeAll(async () => {
test/forges-refused.test.ts +1 −1
@@ -97,7 +97,7 @@ describe("the link on /forges", () => {
9797 expect(body).toContain("Refused first asks (2)");
9898 });
9999 test("a non-admin sees no link", async () => {
100 const body = await (await forgesPage(ctxOf(fresh(), { id: "b", isAdmin: false }))).text();
100 const body = (await (await forgesPage(ctxOf(fresh(), { id: "b", isAdmin: false }))).text()).replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, "");
101101 expect(body).not.toContain("/forges/refused");
102102 });
103103 });
test/front-milestones-private.test.ts +1 −1
@@ -89,7 +89,7 @@ afterAll(async () => {
8989 });
9090
9191 const as = (who: "guest" | "alice" | "bob") => (path: string) =>
92 fetch(`${servers.url}${path}`, { headers: who === "guest" ? {} : { cookie: cookies.get(who)! } }).then(async (r) => ({ status: r.status, text: await r.text() }));
92 fetch(`${servers.url}${path}`, { headers: who === "guest" ? {} : { cookie: cookies.get(who)! } }).then(async (r) => ({ status: r.status, text: (await r.text()).replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, "") }));
9393
9494 const SECRETS = ["Hidden goal", "Hidden wave headline", "hidden part", "/alice/hidden/"];
9595
test/not-found-page.test.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * The 404 page: one sentence, the path once and escaped, a GET search form, a home link; the API
3 * stays JSON.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11
12 let dir = "";
13 let app: App, servers: Servers;
14 beforeAll(async () => {
15 dir = await mkdtemp(join(tmpdir(), "forge-404-page-"));
16 app = createApp({ dataDir: dir, port: 0 });
17 servers = await serve(app);
18 });
19 afterAll(async () => {
20 servers.stop();
21 app.close();
22 await rm(dir, { recursive: true, force: true });
23 });
24 const main = (b: string) => b.slice(b.indexOf("<main"), b.indexOf("</main>"));
25
26 test("a missing page has a sentence, a GET search form, a home link and the path once", async () => {
27 const res = await fetch(`${servers.url}/a/b/c/gone`);
28 expect(res.status).toBe(404);
29 const m = main(await res.text());
30 expect(m).toContain("does not exist, or is not visible to you");
31 expect(m).toMatch(/<form method="get" action="\/search"/);
32 expect(m).toContain('name="q"');
33 expect(m).toMatch(/<a\s[^>]*href="\/"/);
outdated

This href="/" check does not prove a home link inside main for a signed-out request; assert on an a href="/" within the main slice.

34 expect(m.split("/a/b/c/gone").length - 1).toBe(1);
35 });
36
37 test("a hostile path is escaped and never lands in an attribute", async () => {
38 const evil = `/a/b/c/"><script>alert(1)</script>`;
39 const res = await fetch(`${servers.url}/${encodeURI(evil).slice(1)}`);
40 expect(res.status).toBe(404);
41 const body = await res.text();
42 expect(body).not.toContain("<script>alert(1)");
43 expect(main(body)).not.toContain("<script");
44 expect(main(body)).not.toMatch(/(value|href|placeholder)="[^"]*alert/);
45 });
46
47 test("the API's 404 stays JSON", async () => {
48 const res = await fetch(`${servers.url}/api/v1/nothing-here`);
49 expect(res.status).toBe(404);
50 expect(res.headers.get("content-type")).toContain("application/json");
51 expect(typeof ((await res.json()) as { error: unknown }).error).toBe("string");
52 });
53
54 test("a signed-out visitor gets a home link inside main beside Sign in, and one search offer", async () => {
55 const m = main(await (await fetch(`${servers.url}/nope/gone`)).text());
56 expect(m).toMatch(/<a\s[^>]*href="\/"[^>]*>Go home</);
57 expect(m).toContain("Sign in");
58 expect(m).toContain('value="gone"');
59 expect(m).not.toContain("Search for gone");
60 expect(m.match(/action="\/search"/g)?.length).toBe(1);
61 });
test/not-found-search.test.ts +5 −5
@@ -37,20 +37,20 @@ const get = async (path: string, signedIn = false) => {
3737 test("/owner/name offers a search for name; the 404 says once that a private app looks the same", async () => {
3838 const { status, body } = await get("/nope/nothing");
3939 expect(status).toBe(404);
40 expect(body).toContain('href="/search?q=nothing"');
41 expect(body).toContain("Search for nothing");
40 expect(body).toContain('name="q" aria-label="Search this forge" placeholder="Search this forge" value="nothing"');
41 expect(body).not.toContain("Search for nothing");
4242 expect(body).not.toContain("A private app looks the same");
4343 expect(body.match(/not visible to you/g)?.length).toBe(1);
4444 expect(body).toContain("Sign in");
4545 });
4646
4747 test("/owner alone searches for that word", async () => {
48 expect((await get("/nopeperson")).body).toContain('href="/search?q=nopeperson"');
48 expect((await get("/nopeperson")).body).toContain('value="nopeperson"');
4949 });
5050
5151 test("a signed-in reader sees the search but no Sign in button", async () => {
5252 const { body } = await get("/nope/nothing", true);
53 expect(body).toContain("Search for nothing");
53 expect(body).toContain('value="nothing"');
5454 expect(body).not.toContain(">Sign in<");
5555 expect(body).toContain("Go home");
5656 });
@@ -69,7 +69,7 @@ test("a 404 that is not /owner/name is the page it was: two of them differ only
6969 const a = await get("/a/b/c");
7070 const b = await get("/x/y/z");
7171 expect(norm(a.body, "/a/b/c")).toBe(norm(b.body, "/x/y/z"));
72 expect(a.body).not.toContain("Search for");
72 expect(a.body).toContain('placeholder="Search this forge" value=""');
7373 });
7474
7575 test("the search offer adds under 400 bytes to a 404", async () => {
test/not-found-way-on.test.ts +5 −4
@@ -47,16 +47,17 @@ test("a private repo and a missing one read the same signed out", async () => {
4747 .replaceAll(encodeURIComponent(p), "PATHQ")
4848 .replaceAll(p, "PATH")
4949 // the search offer echoes the asked name, so it differs by that name alone
50 .replace(/q=\w+">Search for \w+</, 'q=NAME">Search for NAME<');
50 .replace(/value="\w+"/, 'value="NAME"');
5151 expect(norm(priv.body, "/alice/secret")).toBe(norm(miss.body, "/alice/nothere"));
5252 });
5353
54 test("the 404 says one sentence, offers one button (sign in, back here, when signed out) and folds a request id", async () => {
54 test("the 404 says one sentence, offers home and sign in (back here, when signed out) and folds a request id", async () => {
5555 const res = await fetch(servers.url + "/alice/secret");
5656 const m = main(await res.text());
5757 expect(m).toContain("does not exist, or is not visible to you");
58 expect(m.match(/class="btn/g)?.length).toBe(1);
59 expect(m).toContain("/search?q=secret"); // a link, not a second button
58 expect(m.match(/class="btn/g)?.length).toBe(2);
59 expect(m).toContain('value="secret"'); // the one search box starts with the name
60 expect(m).not.toContain("/search?q=");
6061 expect(m).toContain("/signin?next=");
6162 expect(m).toContain("<details");
6263 const id = /<code>([0-9a-f]{8})<\/code>/.exec(m)?.[1];
test/web-ui.test.ts +3 −2
@@ -444,6 +444,7 @@ describe("web ui", () => {
444444 .replaceAll(/nonce-?="?[\w-]+/g, "nonce")
445445 .replaceAll(/here\?path=[^"&\s]*/g, "here?path=")
446446 .replaceAll(/Quote <code>\w+<\/code>/g, "Quote <code>id</code>")
447 .replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, "")
447448 .replaceAll(/next=[^"]*/g, "next=")
448449 .replaceAll(/\/new\/issue\?from=[^"]*/g, "/new/issue?from=");
449450 expect(scrub(await hidden.text())).toBe(scrub(await absent.text()));
@@ -454,11 +455,11 @@ describe("web ui", () => {
454455 const absent = await (await fetch(`${base}/kim/nothing`)).text();
455456
456457 const main = (t: string) =>
457 t.slice(t.indexOf("<main"), t.indexOf("</main>")).replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>").replaceAll(/next=%2Fkim%2F\w+/g, "next=PATH").replace(/q=\w+">Search for \w+</, "q=NAME\">Search for NAME<");
458 t.slice(t.indexOf("<main"), t.indexOf("</main>")).replaceAll(/<p class="muted">Asked for <code>[^<]*<\/code><\/p>/g, "").replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>").replaceAll(/next=%2Fkim%2F\w+/g, "next=PATH").replace(/value="\w+"/, 'value="NAME"');
458459 expect(main(hidden)).toBe(main(absent));
459460 expect(main(absent)).toContain("Sign in");
460461 expect(main(absent)).not.toContain("Create an account");
461 expect(main(absent)).toContain("Search for NAME");
462 expect(main(absent)).toContain('value="NAME"');
462463
463464 const odd = await (await fetch(`${base}/%3Cx%3E`)).text();
464465 expect(odd).not.toContain("<x>");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs