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

small: the 404 page for a signed-out visitor offers home and search as its two links, with before and after looks #16006

Merged opened this

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

Merged

scout/forge:scout/15978-small-the-404-page-for-a-signed-out-visi → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15978-small-the-404-page-for-a-signed-out-visi was merged into main as 671d44c.

Review

Sign in to review this change.
9 files changed +91 −59
src/http/server.ts +7 −1
@@ -3257,7 +3257,13 @@ async function answer(
32573257 };
32583258 // No session was read, so it cannot tell signed-out from signed-in:
32593259 // it offers no sign-in rather than one to someone who has signed in.
3260 return notFoundPage(anonCtx, { plain: true });
3260 // Carrying no credential at all is signed out, known without a read; it gets the short page.
3261 const bare =
3262 cookieValue(request, "forge_session") === undefined &&
3263 request.headers.get("authorization") === null &&
3264 request.headers.get("x-forge-identity") === null &&
3265 edgeIdentity(request, activeEdgeToken(app)) === undefined;
3266 return notFoundPage(anonCtx, { plain: true, signedOut: bare });
32613267 }
32623268 return noRoute(request.method, url.pathname);
32633269 }
src/web/chrome.ts +12 −1
@@ -78,7 +78,7 @@ export function crumbsFor(repo: Repo): { label: string; href: string }[] {
7878 * yours to see". With no session, on a GET, it also offers sign-in back to
7979 * this address; `plain` leaves that out for a miss that must reveal nothing
8080 * (a dead `/go/:code`), and `noEcho` leaves out the path it echoes. */
81 export function notFoundPage(ctx: Ctx, opts: { plain?: boolean; noEcho?: boolean } = {}): Response {
81 export function notFoundPage(ctx: Ctx, opts: { plain?: boolean; noEcho?: boolean; signedOut?: boolean } = {}): Response {
8282 // A machine path, anything under `/assets/` (a reserved owner, so `/assets/x.woff2` lands on a
8383 // repository route), or a miss at the owner level (no repository named), may be the few typed
8484 // bytes; a person's missing repo file (`/o/r/blob/x.md`) keeps the page and its nearby links.
@@ -86,6 +86,17 @@ export function notFoundPage(ctx: Ctx, opts: { plain?: boolean; noEcho?: boolean
8686 const typedPath = ctx.params.name === undefined || MACHINE_PREFIX.test(path) || path.startsWith("/assets/");
8787 const typed = opts.plain || !typedPath ? undefined : typedMiss(ctx.request, path);
8888 if (typed) return typed;
89 if (opts.signedOut === true || (!opts.plain && ctx.auth.user === undefined)) {
outdated

Principle 1: the <h1> 'Nothing here' and the sentence 'That page is not here.' say the same thing twice. Keep one confident sentence, for example make 'That page is not here.' the h1 and drop the muted paragraph. Update the tests that look for the sentence.

90 // A signed-out visitor learns one thing: it is not here; two ways on, and nothing of the path.
91 const id = requestId();
92 const res = leanPage(
93 "Not found",
94 html`<h1>That page is not here.</h1><p>${btn("Home", { href: "/", variant: "primary" })} ${btn("Search", { href: "/search" })}</p>`,
95 404,
96 );
97 res.headers.set("x-request-id", id);
98 return res;
99 }
89100 const get = !opts.plain && (ctx.request.method === "GET" || ctx.request.method === "HEAD");
90101 const near = get ? nearTo(ctx.app.db, ctx.auth.user, ctx.params.owner ?? "", ctx.params.name ?? "") : [];
91102 const pages = get
test/docs-not-found.test.ts +1 −1
@@ -35,7 +35,7 @@ for (const path of ["/docs/start", "/docs/features/nope"]) {
3535 const res = await ask(path, BROWSER);
3636 expect(res.status).toBe(404);
3737 expect(res.headers.get("content-type")).toContain("text/html");
38 expect(await res.text()).toContain("Nothing here");
38 expect(await res.text()).toContain("That page is not here.");
3939 });
4040
4141 test(`${path} is JSON to Accept: application/json`, async () => {
test/near-pages.test.ts +12 −3
@@ -7,15 +7,21 @@ import { tmpdir } from "node:os";
77 import { join } from "node:path";
88 import { createApp, type App } from "../src/app.ts";
99 import { serve, type Servers } from "../src/http/server.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { createSession } from "../src/core/sessions.ts";
1012 import { nearPages } from "../src/web/near_pages.ts";
1113
1214 let dataDir = "";
1315 let app: App, servers: Servers;
16 let cookie = "";
1417
1518 beforeAll(async () => {
1619 dataDir = await mkdtemp(join(tmpdir(), "forge-nearpages-"));
1720 app = createApp({ dataDir, port: 0 });
1821 servers = await serve(app);
22 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
23 if (!u.ok) throw new Error("user");
24 cookie = `forge_session=${createSession(app.db, u.value.id).token}`;
1925 });
2026
2127 afterAll(async () => {
@@ -44,12 +50,15 @@ test("a page the viewer may not open is never named", () => {
4450 });
4551
4652 test("the 404 page shows the links, escaped, and a far path shows none", async () => {
47 const near = await (await fetch(`${servers.url}/explroe`)).text();
53 // A signed-in person gets the full 404 with suggestions; a signed-out one gets the short page.
54 const near = await (await fetch(`${servers.url}/explroe`, { headers: { cookie } })).text();
4855 expect(near).toContain('Did you mean <a href="/explore">/explore</a>?');
49 const far = await fetch(`${servers.url}/zzzzzzzzzzzzzzzzzzzz`);
56 const far = await fetch(`${servers.url}/zzzzzzzzzzzzzzzzzzzz`, { headers: { cookie } });
5057 expect(far.status).toBe(404);
5158 expect(await far.text()).not.toContain("Did you mean");
52 const evil = await (await fetch(`${servers.url}/apps%3Cb%3E`)).text();
59 const evil = await (await fetch(`${servers.url}/apps%3Cb%3E`, { headers: { cookie } })).text();
60 const out = await (await fetch(`${servers.url}/explroe`)).text();
61 expect(out).not.toContain("Did you mean");
5362 expect(evil).not.toContain("<b>");
5463 });
5564
test/not-found-page.test.ts +34 −13
@@ -7,14 +7,29 @@ import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { createUser } from "../src/core/users.ts";
1011 import { serve, type Servers } from "../src/http/server.ts";
1112
1213 let dir = "";
1314 let app: App, servers: Servers;
15 let cookie = "";
16 /** A signed-in GET: the full 404 page; the bare fetch is the signed-out one. */
17 const asUser = (path: string) => fetch(servers.url + path, { headers: { cookie } });
1418 beforeAll(async () => {
1519 dir = await mkdtemp(join(tmpdir(), "forge-404-page-"));
1620 app = createApp({ dataDir: dir, port: 0 });
1721 servers = await serve(app);
22 await createUser(app.db, {
23 origin: "seed", trusted: true, username: "ada", email: "[email protected]",
24 password: "a-good-passphrase", adminIfFirst: true,
25 });
26 const res = await fetch(servers.url + "/signin", {
27 method: "POST",
28 redirect: "manual",
29 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
30 body: new URLSearchParams({ username: "ada", password: "a-good-passphrase" }),
31 });
32 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
1833 });
1934 afterAll(async () => {
2035 servers.stop();
@@ -23,8 +38,8 @@ afterAll(async () => {
2338 });
2439 const main = (b: string) => b.slice(b.indexOf("<main"), b.indexOf("</main>"));
2540
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`);
41 test("a signed-in missing page has a sentence, a GET search form, a home link and the path once", async () => {
42 const res = await asUser(`/a/b/c/gone`);
2843 expect(res.status).toBe(404);
2944 const m = main(await res.text());
3045 expect(m).toContain("does not exist, or is not visible to you");
@@ -51,17 +66,23 @@ test("the API's 404 stays JSON", async () => {
5166 expect(typeof ((await res.json()) as { error: unknown }).error).toBe("string");
5267 });
5368
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);
69 test("a signed-out visitor gets one sentence and exactly two links: home and search", async () => {
70 const res = await fetch(`${servers.url}/nope/gone`);
71 const body = await res.text();
72 expect(new TextEncoder().encode(body).length).toBeLessThan(3000);
73 expect(res.status).toBe(404);
74 const m = main(body);
75 expect(m).toContain("That page is not here.");
76 expect([...m.matchAll(/<a\s[^>]*href="([^"]*)"/g)].map((x) => x[1])).toEqual(["/", "/search"]);
77 expect(m).not.toContain("<form");
78 expect(m).not.toContain("Sign in");
79 expect(m).not.toContain("gone");
outdated

A wall-clock bound on a fetch in a shared test run can flake on a loaded machine. Rely on the byte-size and no-database-read guarantees, or use a generous bound.

80 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
81 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
6182 });
6283
6384 test("a missing page answers under 3,000 bytes with no shell, no script, and the security floor", async () => {
64 const res = await fetch(`${servers.url}/nope-404`);
85 const res = await asUser(`/nope-404`);
6586 expect(res.status).toBe(404);
6687 const body = await res.text();
6788 expect(new TextEncoder().encode(body).length).toBeLessThan(3000);
@@ -75,9 +96,9 @@ test("a missing page answers under 3,000 bytes with no shell, no script, and the
7596 });
7697
7798 test("a path one edit from a known page says 'Did you mean /explore'; a far one offers Explore", async () => {
78 const near = main(await (await fetch(`${servers.url}/explor`)).text());
99 const near = main(await (await asUser(`/explor`)).text());
79100 expect(near).toContain('Did you mean <a href="/explore">/explore</a>?');
80 const far = main(await (await fetch(`${servers.url}/zzqqxx`)).text());
101 const far = main(await (await asUser(`/zzqqxx`)).text());
81102 expect(far).not.toContain("Did you mean");
82103 expect(far).toContain('<a href="/explore">Explore</a>');
83104 expect(far).toMatch(/<a\s[^>]*href="\/"[^>]*>Go home</);
@@ -85,7 +106,7 @@ test("a path one edit from a known page says 'Did you mean /explore'; a far one
85106 });
86107
87108 test("the echoed path of a near miss stays escaped and out of links", async () => {
88 const m = main(await (await fetch(`${servers.url}/explor%3Cb%3E`)).text());
109 const m = main(await (await asUser("/explor%3Cb%3E")).text());
89110 expect(m).not.toContain("<b>");
90111 expect(m).not.toMatch(/href="[^"]*explor%3C|href="[^"]*<b/);
91112 });
test/not-found-search.test.ts +9 −10
@@ -34,19 +34,18 @@ const get = async (path: string, signedIn = false) => {
3434 return { status: res.status, body: await res.text() };
3535 };
3636
37 test("/owner/name offers a search for name; the 404 says once that a private app looks the same", async () => {
38 const { status, body } = await get("/nope/nothing");
37 test("signed in, /owner/name offers a search for name; the 404 says once that a private app looks the same", async () => {
38 const { status, body } = await get("/nope/nothing", true);
3939 expect(status).toBe(404);
4040 expect(body).toContain('name="q" aria-label="Search this forge" placeholder="Search this forge" value="nothing"');
4141 expect(body).not.toContain("Search for nothing");
4242 expect(body).not.toContain("A private app looks the same");
4343 // The share head repeats the description in meta tags; the visible page says it once.
4444 expect(body.replace(/<head>[\s\S]*?<\/head>/, "").match(/not visible to you/g)?.length).toBe(1);
45 expect(body).toContain("Sign in");
4645 });
4746
48 test("/owner alone searches for that word", async () => {
49 expect((await get("/nopeperson")).body).toContain('value="nopeperson"');
47 test("signed in, /owner alone searches for that word", async () => {
48 expect((await get("/nopeperson", true)).body).toContain('value="nopeperson"');
5049 });
5150
5251 test("a signed-in reader sees the search but no Sign in button", async () => {
@@ -58,7 +57,7 @@ test("a signed-in reader sees the search but no Sign in button", async () => {
5857
5958 test("other 404s are unchanged: deeper paths and odd segments get no search", async () => {
6059 for (const path of ["/a/b/c", "/a/b/", "/a/%3Cb%3E"]) {
61 const { status, body } = await get(path);
60 const { status, body } = await get(path, true);
6261 expect(status).toBe(404);
6362 expect(body).not.toContain("/search?q=");
6463 }
@@ -67,14 +66,14 @@ test("other 404s are unchanged: deeper paths and odd segments get no search", as
6766 test("a 404 that is not /owner/name is the page it was: two of them differ only by path and id", async () => {
6867 const norm = (b: string, p: string) =>
6968 b.replace(/<code>[0-9a-f]{8}<\/code>/, "<code>ID</code>").replaceAll(encodeURIComponent(p), "PATHQ").replaceAll(p, "PATH");
70 const a = await get("/a/b/c");
71 const b = await get("/x/y/z");
69 const a = await get("/a/b/c", true);
70 const b = await get("/x/y/z", true);
7271 expect(norm(a.body, "/a/b/c")).toBe(norm(b.body, "/x/y/z"));
7372 expect(a.body).toContain('placeholder="Search this forge" value=""');
7473 });
7574
7675 test("the search offer adds under 400 bytes to a 404", async () => {
77 const shaped = (await get("/nope/nothing")).body.length;
78 const plain = (await get("/a/b/c")).body.length;
76 const shaped = (await get("/nope/nothing", true)).body.length;
77 const plain = (await get("/a/b/c", true)).body.length;
7978 expect(Math.abs(shaped - plain)).toBeLessThan(400);
8079 });
test/not-found-way-on.test.ts +7 −20
@@ -45,35 +45,22 @@ test("a private repo and a missing one read the same signed out", async () => {
4545 main(b)
4646 .replace(/<code>[0-9a-f]{8}<\/code>/, "<code>ID</code>")
4747 .replaceAll(encodeURIComponent(p), "PATHQ")
48 .replaceAll(p, "PATH")
49 // the search offer echoes the asked name, so it differs by that name alone
50 .replace(/value="\w+"/, 'value="NAME"');
48 .replaceAll(p, "PATH");
5149 expect(norm(priv.body, "/alice/secret")).toBe(norm(miss.body, "/alice/nothere"));
outdated

Leftover bare ; line after the removed .replace(...). Drop it so the expression ends cleanly.

5250 });
5351
54 test("the 404 says one sentence, offers home and sign in (back here, when signed out) and folds a request id", async () => {
52 test("a signed-out 404 is one sentence and two links, home and search, with the request id in a header", async () => {
5553 const res = await fetch(servers.url + "/alice/secret");
5654 const m = main(await res.text());
57 expect(m).toContain("does not exist, or is not visible to you");
55 expect(m).toContain("That page is not here.");
5856 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=");
61 expect(m).toContain("/signin?next=");
62 expect(m).toContain("<details");
63 const id = /<code>([0-9a-f]{8})<\/code>/.exec(m)?.[1];
64 expect(id).toBeDefined();
65 expect(res.headers.get("x-request-id")).toBe(id!);
57 expect(m).toContain('href="/search"');
58 expect(m).not.toContain("secret");
59 expect(res.headers.get("x-request-id")).toMatch(/^[0-9a-f]{8}$/);
6660 for (const h of ["content-security-policy", "x-content-type-options", "referrer-policy"]) expect(res.headers.get(h)).toBeTruthy();
6761 });
6862
69 test("the 404 names the path and links home and Explore; the API's 404 stays JSON", async () => {
70 const res = await fetch(servers.url + "/nope/nothing", { headers: { accept: "text/html" } });
71 expect(res.status).toBe(404);
72 const m = main(await res.text());
73 expect(m).toContain("<code>/nope/nothing</code>");
74 expect(m).toContain('href="/"');
75 expect(m).toContain('href="/explore"');
76 expect(m.match(/class="btn/g)?.length).toBe(2);
63 test("the API's 404 stays JSON", async () => {
7764 const api = await fetch(servers.url + "/api/v1/nothing-here");
7865 expect(api.status).toBe(404);
7966 expect(api.headers.get("content-type")).toStartWith("application/json");
test/web-ui.test.ts +5 −6
@@ -450,16 +450,15 @@ describe("web ui", () => {
450450 expect(scrub(await hidden.text())).toBe(scrub(await absent.text()));
451451 });
452452
453 test("a hidden and an absent page read the same, with one button and the echoed path escaped", async () => {
453 test("a hidden and an absent page read the same to a signed-out visitor, and the echoed path stays escaped", async () => {
454454 const hidden = await (await fetch(`${base}/kim/secret`)).text();
455455 const absent = await (await fetch(`${base}/kim/nothing`)).text();
456456
457 const main = (t: string) =>
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"');
457 const main = (t: string) => t.slice(t.indexOf("<main"), t.indexOf("</main>")).replaceAll(/<code>[0-9a-f]{8}<\/code>/g, "<code>ID</code>");
459458 expect(main(hidden)).toBe(main(absent));
460 expect(main(absent)).toContain("Sign in");
461 expect(main(absent)).not.toContain("Create an account");
462 expect(main(absent)).toContain('value="NAME"');
459 expect(main(absent)).toContain("That page is not here.");
460 expect(main(absent)).not.toContain("secret");
461 expect(main(absent)).not.toContain("nothing");
463462
464463 const odd = await (await fetch(`${base}/%3Cx%3E`)).text();
465464 expect(odd).not.toContain("<x>");
test/web.test.ts +4 −4
@@ -555,7 +555,7 @@ describe("web pages end to end", () => {
555555 });
556556 const anon = await fetch(`${base}/ada/secret`);
557557 expect(anon.status).toBe(404); // 404 status, not a soft 200…
558 expect(await anon.text()).toContain("Nothing here"); // …with a real page body
558 expect(await anon.text()).toContain("That page is not here."); // …with a real page body
559559 const owner = await (
560560 await fetch(`${base}/ada/secret`, { headers: { cookie } })
561561 ).text();
@@ -570,7 +570,7 @@ describe("web pages end to end", () => {
570570 ]) {
571571 const response = await fetch(`${base}${path}`);
572572 const text = await response.text();
573 expect(text).toContain("Nothing here");
573 expect(text).toContain("That page is not here.");
574574 }
575575 });
576576
@@ -589,8 +589,8 @@ describe("web pages end to end", () => {
589589 expect(browser.headers.get("x-content-type-options")).toBe("nosniff");
590590 expect(browser.headers.get("referrer-policy")).toBeTruthy();
591591 const html = await browser.text();
592 expect(html).toContain("Nothing here");
593 expect(html).toContain("Go home");
592 expect(html).toContain("That page is not here.");
593 expect(html).toContain(">Home<");
594594
595595 // No Accept header at all — curl, a crawler, a link unfurler — gets the page
596596 // too (#6733); a caller that asks for JSON keeps the contract.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs