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

The not-found and failed pages say one plain sentence and offer one action #13027

Merged opened this

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

Merged

scout/forge:scout/13006-the-not-found-and-failed-pages-say-one-p → main 9 commits fork 3 threads · 3 unresolved

  • Merged. scout/13006-the-not-found-and-failed-pages-say-one-p was merged into main as 2e403c3.

Review

Sign in to review this change.
10 files changed +64 −92
src/web/chrome.ts +11 −29
@@ -41,7 +41,8 @@ import {
4141 type RepoScope,
4242 } from "./scope.ts";
4343 import { repoSteps, TAB_STEPS, type RepoTab } from "./repo_steps.ts";
44 import { badge, btn, empty, keyHint, pill, tabs, type TabItem } from "./ui.ts";
44 import { requestId } from "./failed_page.ts";
45 import { badge, btn, disclosure, empty, keyHint, pill, tabs, type TabItem } from "./ui.ts";
4546 import { BIND, zeroAttr } from "./bind.ts";
4647
4748 // ---- loading ----
@@ -75,13 +76,6 @@ export function crumbsFor(repo: Repo): { label: string; href: string }[] {
7576 export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response {
7677 if (!opts.plain && isAssetMiss(ctx.request, ctx.url.pathname)) return assetNotFound();
7778 const get = !opts.plain && ctx.request.method === "GET";
78 const offerSignIn = get && ctx.auth.user === undefined;
79 const asked = get ? askedFor(ctx.url.pathname) : "";
80 const search = asked
81 ? btn(`Search for ‘${asked}’`, { href: `/search?q=${encodeURIComponent(asked)}` })
82 : get
83 ? btn("Search", { href: "/search" })
84 : html``;
8579 const near = get ? nearTo(ctx.app.db, ctx.auth.user, ctx.params.owner ?? "", ctx.params.name ?? "") : [];
8680 const pages = get
8781 ? nearPages(ctx.url.pathname, { signedIn: ctx.auth.user !== undefined, admin: ctx.auth.user?.isAdmin === true })
@@ -94,7 +88,9 @@ export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response
9488 tries.length === 0
9589 ? html``
9690 : html`<p class="muted">Try ${tries.map((t, i) => html`${i > 0 ? ", " : ""}${t}`)}</p>`;
97 return page(
91 const id = requestId();
92 const offerSignIn = get && ctx.auth.user === undefined;
93 const res = page(
9894 {
outdated

Principle 1: Go home is the only action, so a signed-out visitor on a private link loses the way back. Offer sign-in with return-to when signed out, still as the single button.

9995 ctx,
10096 title: "Not found",
@@ -103,29 +99,15 @@ export function notFoundPage(ctx: Ctx, opts: { plain?: boolean } = {}): Response
10399 icon: "search",
104100 title: "Nothing here",
105101 note: "The page you asked for does not exist, or is not visible to you.",
106 action: opts.plain
107 ? btn("Go home", { href: "/", variant: "primary" })
108 : offerSignIn
109 ? html`${btn("Sign in", { href: notFoundSignIn(ctx), variant: "primary" })}
110 ${btn("Create an account", { href: withReturn("/signup", returnTo(ctx)) })} ${search}
111 ${btn("Go home", { href: "/" })} ${btn("Explore", { href: "/explore" })}`
112 : html`${btn("Go home", { href: "/", variant: "primary" })} ${search}
113 ${btn("Explore", { href: "/explore" })}`,
114 })}${didYouMean}`,
102 action: offerSignIn
103 ? btn("Sign in", { href: notFoundSignIn(ctx), variant: "primary" })
104 : btn("Go home", { href: "/", variant: "primary" }),
105 })}${didYouMean}${disclosure("Request id", html`<p class="muted small">Quote <code>${id}</code> if you ask about this page.</p>`, { small: true })}`,
115106 },
116107 404,
117108 );
118 }
119
120 /** What the reader asked for: the last path segment, URL-decoded, trimmed,
121 * at most 100 characters; empty for `/` or an undecodable segment. */
122 function askedFor(pathname: string): string {
123 const segment = pathname.slice(pathname.lastIndexOf("/") + 1);
124 try {
125 return decodeURIComponent(segment).trim().slice(0, 100).trim();
126 } catch {
127 return "";
128 }
109 res.headers.set("x-request-id", id);
110 return res;
129111 }
130112
131113 /** The sign-in door from a 404: back here through `returnTo`; behind an edge, the edge's. */
src/web/failed_page.ts +9 −4
@@ -45,9 +45,14 @@ export function parentOf(pathname: string): string {
4545 return segments.length <= 1 ? "/" : `/${segments.slice(0, -1).join("/")}`;
4646 }
4747
48 /** Where Try again goes: this path for a read, home for anything that wrote. */
49 export function retryTarget(request: Request, pathname: string): string {
50 const read = request.method === "GET" || request.method === "HEAD";
51 return read && !pathname.startsWith("//") ? pathname : "/";
52 }
53
4854 export function failedPage(request: Request, pathname: string, id: string): Response {
4955 const crumbs = failedCrumbs(pathname);
50 const parent = parentOf(pathname);
5156 const body: Html = html`<a class="skip" href="#main">Skip to content</a>
5257 <header class="topbar" role="banner">
5358 <a href="/" class="wordmark"><span class="mark"></span>forge</a>
outdated

Principle 1/8: Try again re-requests the same path with GET even if the failing request was a POST, and the id a person needs is now behind a fold. Give the retry a safe target and keep the id visible.

@@ -55,9 +60,9 @@ export function failedPage(request: Request, pathname: string, id: string): Resp
5560 </header>
5661 <main class="shell" id="main">
5762 <div class="page-head"><h1>Something went wrong</h1></div>
58 <p>The forge failed to show this page. Request id <code>${id}</code>.</p>
59 <p class="actions">${btn("Go home", { href: "/", variant: "primary" })}
60 ${parent === "/" ? null : btn("Go up one level", { href: parent })}</p>
63 <p>The forge failed to show this page. Try again in a moment.</p>
64 <p class="actions">${btn("Try again", { href: retryTarget(request, pathname), variant: "primary" })}</p>
65 <p class="muted small">Quote <code>${id}</code> if you ask about this failure.</p>
6166 </main>`;
6267 const text = `<!doctype html><html lang="en"><head><meta charset="utf-8" />
6368 <meta name="viewport" content="width=device-width, initial-scale=1" />
test/error-page-500.test.ts +11 −2
@@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
12 import { failedCrumbs, parentOf } from "../src/web/failed_page.ts";
12 import { failedCrumbs, parentOf, retryTarget } from "../src/web/failed_page.ts";
1313
1414 const SECRET = "hunter2-the-database-password";
1515 let dataDir = "";
@@ -54,7 +54,9 @@ test("a throwing page answers 500 with chrome, the way back and an id found in t
5454 expect(body).toContain('class="topbar"');
5555 expect(body).toContain('class="crumbs"');
5656 expect(body).toContain('href="/ada/notes"'); // the parent
57 expect(body).toContain('href="/"');
57 expect(body).toContain("Try again");
58 expect(body).not.toContain("Go up one level");
59 expect(body).not.toContain("<details"); // the id stays in plain sight
5860 const id = /<code>([0-9a-f]{8})<\/code>/.exec(body)?.[1];
5961 expect(id).toBeDefined();
6062 expect(res.headers.get("x-request-id")).toBe(id!);
@@ -97,3 +99,10 @@ test("crumbs and parent come from the path alone", () => {
9799 expect(parentOf("/a/b/c")).toBe("/a/b");
98100 expect(parentOf("/a")).toBe("/");
99101 });
102
103 test("Try again re-requests a read, and sends anything that wrote home", () => {
104 const req = (method: string) => new Request("http://x/a/b", { method });
105 expect(retryTarget(req("GET"), "/a/b")).toBe("/a/b");
106 expect(retryTarget(req("POST"), "/a/b")).toBe("/");
107 expect(retryTarget(req("GET"), "//evil.example")).toBe("/");
108 });
test/file-hold-form.test.ts +1
@@ -67,6 +67,7 @@ describe("the file hold form", () => {
6767 cookie: res.headers.get("set-cookie"),
6868 body: (await res.text())
6969 .replace(/nonce="[^"]*"/g, 'nonce=""')
70 .replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>")
7071 .replaceAll(encodeURIComponent(asked), "ASKED"),
7172 });
7273
test/forges-refused.test.ts +2 −1
@@ -39,7 +39,8 @@ describe("GET /forges/refused", () => {
3939 const mine = forgesRefusedPage(ctxOf(app, user));
4040 const theirs = await forgesPage(ctxOf(app, user));
4141 expect(mine.status).toBe(theirs.status);
42 expect(await mine.text()).toBe(await theirs.text());
42 const id = (t: string) => t.replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>");
43 expect(id(await mine.text())).toBe(id(await theirs.text()));
4344 }
4445 });
4546 test("markup in an ask renders as text", async () => {
test/not-found-way-on.test.ts +15 −11
@@ -40,21 +40,25 @@ test("a private repo and a missing one read the same signed out", async () => {
4040 const miss = await get("/alice/nothere");
4141 expect(priv.status).toBe(404);
4242 expect(miss.status).toBe(404);
43 // Only the full path, its encoded form and the Search button that names the last segment differ.
43 // Only the full path, its encoded form and the request id differ.
4444 const norm = (b: string, p: string) =>
4545 main(b)
46 .replace(/<code>[0-9a-f]{8}<\/code>/, "<code>ID</code>")
4647 .replaceAll(encodeURIComponent(p), "PATHQ")
47 .replaceAll(p, "PATH")
48 .replace(/Search for ‘[^’]*’/, "Search for")
49 .replace(/\/search\?q=[^"]*/, "/search?q=");
48 .replaceAll(p, "PATH");
5049 expect(norm(priv.body, "/alice/secret")).toBe(norm(miss.body, "/alice/nothere"));
outdated

Dead scrub: the Search for button no longer exists, so this replace and its comment go.

5150 });
5251
53 test("the 404 offers home, search and sign-in that comes back", async () => {
54 const { body } = await get("/alice/secret");
55 const m = main(body);
56 expect(m).toContain('href="/"');
57 expect(m).toContain('href="/search');
58 expect(m).toContain('href="/signin?next=%2Falice%2Fsecret"');
59 expect(m).not.toContain("You asked for");
52 test("the 404 says one sentence, offers one button (sign in, back here, when signed out) and folds a request id", async () => {
53 const res = await fetch(servers.url + "/alice/secret");
54 const m = main(await res.text());
55 expect(m).toContain("does not exist, or is not visible to you");
56 expect(m.match(/class="btn/g)?.length).toBe(1);
57 expect(m).not.toContain("/search");
58 expect(m).toContain("/signin?next=");
59 expect(m).toContain("<details");
60 const id = /<code>([0-9a-f]{8})<\/code>/.exec(m)?.[1];
61 expect(id).toBeDefined();
62 expect(res.headers.get("x-request-id")).toBe(id!);
63 for (const h of ["content-security-policy", "x-content-type-options", "referrer-policy"]) expect(res.headers.get(h)).toBeTruthy();
6064 });
test/private-sweep.test.ts +2 −1
@@ -154,7 +154,8 @@ async function body(door: Door, who?: Visitor): Promise<{ status: number; text:
154154 ...(door.post === undefined ? {} : { body: JSON.stringify(door.post) }),
155155 });
156156 const head = [...res.headers].map(([k, v]) => `${k}: ${v}`).join("\n");
157 const content = (await res.text()).toLowerCase();
157 // The request id on an error page is fresh each time.
158 const content = (await res.text()).replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>id</code>").toLowerCase();
158159 return { status: res.status, text: `${head.toLowerCase()}\n\n${content}`, content };
159160 }
160161
test/web-origins.test.ts +2 −1
@@ -818,7 +818,8 @@ describe("origins on the web", () => {
818818 .replaceAll(/nonce="[^"]*"/g, 'nonce="N"')
819819 .replaceAll(/here\?path=[^"&\s]*/g, "here?path=")
820820 .replaceAll(/next=[^"]*/g, "next=")
821 .replaceAll(/\/new\/issue\?from=[^"]*/g, "/new/issue?from=");
821 .replaceAll(/\/new\/issue\?from=[^"]*/g, "/new/issue?from=")
822 .replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>");
822823 const staleText = await stale.text();
823824 const unknownText = await unknown.text();
824825 expect(sameBut(staleText)).toBe(sameBut(unknownText));
test/web-ui.test.ts +10 −42
@@ -448,28 +448,19 @@ describe("web ui", () => {
448448 expect(scrub(await hidden.text())).toBe(scrub(await absent.text()));
449449 });
450450
451 test("a signed-out 404 offers sign-in back to the same address", async () => {
452 const asked = "/kim/secret?tab=x&y=1";
453 const out = await (await fetch(`${base}${asked}`)).text();
454 expect(out).toContain(
455 `href="/signin?next=${encodeURIComponent(asked).replaceAll("&", "&amp;")}"`,
456 );
457 expect(out).toContain('href="/"');
458 expect(out).toContain("Go home");
459 expect(out).toContain('href="/explore"');
451 test("a hidden and an absent page read the same, with one button and the echoed path escaped", async () => {
460452 const hidden = await (await fetch(`${base}/kim/secret`)).text();
461453 const absent = await (await fetch(`${base}/kim/nothing`)).text();
462 const scrub = (t: string) =>
463 t.replaceAll(/nonce-?="?[\w-]+/g, "nonce").replaceAll(/here\?path=[^"&\s]*/g, "here?path=").replaceAll(/next=[^"]*/g, "").replaceAll(/\/new\/issue\?from=[^"]*/g, "/new/issue?from=").replaceAll(/q=[^"]*"/g, 'q="').replaceAll(/Search for ‘[^’]*’/g, "Search for");
464 expect(scrub(hidden)).toBe(scrub(absent));
465454
466 const signedIn = await (
467 await fetch(`${base}/kim/nothing`, { headers: { cookie: stranger } })
468 ).text();
469 expect(signedIn).toContain("Nothing here");
470 expect(signedIn).not.toContain("/signin?next=");
471 expect(signedIn).toContain("Go home");
472 expect(signedIn).toContain('href="/explore"');
455 const main = (t: string) =>
456 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");
457 expect(main(hidden)).toBe(main(absent));
458 expect(main(absent)).toContain("Sign in");
459 expect(main(absent)).not.toContain("Create an account");
460 expect(main(absent)).not.toContain("Search for");
461
462 const odd = await (await fetch(`${base}/%3Cx%3E`)).text();
463 expect(odd).not.toContain("<x>");
473464 });
474465
475466 test("the signed-out home links to /pricing in the top bar", async () => {
@@ -477,29 +468,6 @@ describe("web ui", () => {
477468 expect(out).toContain('<a class="small door-wide" href="/pricing">Pricing</a>');
478469 });
479470
480 test("a 404 offers a search for what was asked, and a stranger an account", async () => {
481 const out = await (await fetch(`${base}/kim/nothing`)).text();
482 expect(out).toContain('href="/search?q=nothing"');
483 expect(out).toContain("Search for ‘nothing’");
484 // The account it offers comes back to the page that was asked for.
485 expect(out).toContain('href="/signup?next=%2Fkim%2Fnothing"');
486 expect(out).toContain("Create an account");
487
488 const odd = await (await fetch(`${base}/%3Cx%3E`)).text();
489 expect(odd).toContain("Search for ‘&lt;x&gt;’");
490 expect(odd).toContain('href="/search?q=%3Cx%3E"');
491 expect(odd).not.toContain("<x>");
492
493 const long = await (await fetch(`${base}/${"a".repeat(150)}`)).text();
494 expect(long).toContain(`q=${"a".repeat(100)}"`);
495
496 const signedIn = await (
497 await fetch(`${base}/kim/nothing`, { headers: { cookie: stranger } })
498 ).text();
499 expect(signedIn).toContain("Search for ‘nothing’");
500 expect(signedIn).not.toContain("Create an account");
501 });
502
503471 test("safeNext refuses another origin", () => {
504472 expect(safeNext("//evil.example/x")).toBeUndefined();
505473 expect(safeNext("https://evil.example")).toBeUndefined();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs