Files
bobbanandClaude Sonnet 5.5 8ffae62281 Error pages: 404, 403, crash and server-rendered pages in the app's style
In the app: an unknown address shows a 404 inside the menu with the address, "Maybe you were looking for" suggestions (misspellings, partial names, moved pages) and a Ctrl+K search button; a page the role can't open shows a 403 "No access"; a render crash is caught by an error boundary (menu stays, clears on navigation, outer boundary for the sign-in and wall); missing servers, incidents and dead status links use the same page.

On the server: unknown /api, /auth, /agent and /metrics addresses and missing files now get a JSON 404 instead of the app's front page with a 200; browsers get self-contained 404, 500 and sign-in-failed pages in the sign-in card's look, light or dark, English or Swedish.

Swedish translations added. Tests in server/test/errorPages.test.ts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 18:06:14 +01:00

193 lines
9.5 KiB
TypeScript

/**
* The pages for what isn't there or went wrong: the server's own 404 and 500 pages and what decides whether a browser or the app's code is answered, that an address which is not a page
* no longer gets the app's front page with a 200, and the app's own 404 / 403 / crash pages and the "maybe you were looking for" list.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-errorpages-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const { createApp } = await import("../src/app.js");
const { errorPageHtml, pickLanguage } = await import("../src/utils/errorPage.js");
const { suggestPages, distance } = await import("../../web/src/utils/pageSuggestions.js");
const WEB = new URL("../../web/src/", import.meta.url);
const read = (path: string) => readFileSync(new URL(path, WEB), "utf8");
describe("the page the server answers with", () => {
test("says what happened, looks like the sign-in page, and leads home", () => {
const html = errorPageHtml("not_found");
assert.match(html, /<title>Page not found · Homelab Manager<\/title>/);
assert.match(html, />404</);
assert.match(html, /src="\/logo\.webp"/);
assert.match(html, /href="\/">Go to the dashboard</);
assert.match(html, /hlm-theme/, "the theme the person chose in the app");
assert.doesNotMatch(html, /href="\/auth\/login"/);
});
test("a failed sign-in offers to try again, a failure offers the same page again, neither says why", () => {
assert.match(errorPageHtml("sign_in_failed"), /href="\/auth\/login">Try again</);
assert.match(errorPageHtml("server_error"), /href="">Try again</);
assert.doesNotMatch(errorPageHtml("sign_in_failed"), /ECONN|stack|Error:/);
});
test("is in Swedish for a browser that asks for it, and the language is the first one asked for", () => {
assert.equal(pickLanguage("sv-SE,sv;q=0.9,en;q=0.8"), "sv");
assert.equal(pickLanguage("sv"), "sv");
assert.equal(pickLanguage("en-GB,en;q=0.9,sv;q=0.8"), "en");
assert.equal(pickLanguage(undefined), "en");
assert.equal(pickLanguage("svg"), "en");
assert.match(errorPageHtml("not_found", "sv"), /Sidan hittades inte/);
assert.match(errorPageHtml("not_found", "sv"), /<html lang="sv">/);
});
});
describe("an address that is nothing", () => {
let server: Server;
let base = "";
const get = (path: string, accept?: string, language?: string) => fetch(`${base}${path}`, { headers: { ...(accept ? { accept } : {}), ...(language ? { "accept-language": language } : {}) } });
before(async () => {
server = await new Promise<Server>((resolve) => {
const s = createApp().listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => {
server.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("under /api it is a JSON 404, for a browser as well — never the app's front page", async () => {
for (const accept of [undefined, "application/json", "text/html,application/xhtml+xml,*/*;q=0.8"]) {
const res = await get("/api/no-such-thing", accept);
assert.equal(res.status, 404, String(accept));
assert.match(res.headers.get("content-type") ?? "", /json/);
assert.equal((await res.json()).error, "not_found");
}
});
test("the other addresses of the server's own (sign-in, the agent files, metrics) are not pages either", async () => {
for (const path of ["/auth/no-such-thing", "/agent/no-such-file.sh", "/metrics/no-such-thing"]) {
const res = await get(path, "application/json");
assert.equal(res.status, 404, path);
assert.equal((await res.json()).error, "not_found", path);
}
});
test("a browser opening one outside the app is given the page, in its language", async () => {
const res = await get("/auth/no-such-thing", "text/html,application/xhtml+xml,*/*;q=0.8", "sv-SE,sv;q=0.9");
assert.equal(res.status, 404);
assert.match(res.headers.get("content-type") ?? "", /html/);
assert.match(await res.text(), /Sidan hittades inte/);
});
test("something that names a file which is not there is a 404, not the front page with a 200", async () => {
const res = await get("/assets/no-such-file.js");
assert.equal(res.status, 404);
assert.doesNotMatch(await res.text(), /<div id="root">/);
});
test("another method on an unknown address is a 404 too", async () => {
const res = await fetch(`${base}/api/no-such-thing`, { method: "POST", headers: { "content-type": "application/json", origin: base }, body: "{}" });
assert.ok([403, 404].includes(res.status), String(res.status));
});
test("the app's own pages still get the app (it draws their 404 itself)", { skip: !existsSync(new URL("../../web/dist/index.html", import.meta.url)) }, async () => {
for (const path of ["/", "/servers", "/servers/3", "/alerts/incidents/9", "/share/status/abc-DEF_123", "/no-such-page"]) {
const res = await get(path, "text/html");
assert.equal(res.status, 200, path);
assert.match(await res.text(), /<div id="root">/, path);
}
});
});
describe("what the app draws for itself", () => {
test("an unknown address is a 404 page inside the menu, at the top level and under Settings", () => {
const app = read("App.tsx");
assert.match(app, /<Route path="\*" element=\{<NotFound user=\{user\} \/>\} \/>\s*<\/Routes>/, "the end of the list of pages");
assert.match(app, /<Route path="notifications"[\s\S]*<Route path="\*" element=\{<NotFound user=\{user\} \/>\} \/>\s*<\/Route>/, "under /settings");
});
test("a page the role doesn't open is a 403 page, and a page that fails is caught so the menu stays", () => {
const app = read("App.tsx");
assert.match(app, /<ForbiddenPage minRole=/);
assert.doesNotMatch(app, /alert-danger">\{t\("You don't have permission/);
assert.match(app, /<ErrorBoundary resetKey=\{pathname\}>/);
assert.match(read("main.tsx"), /<ErrorBoundary standalone>/, "and a crash outside the frame too");
assert.match(read("components/ErrorPage.tsx"), /componentDidUpdate[\s\S]*prev\.resetKey !== this\.props\.resetKey/, "going to another page clears the failure");
});
test("a server, an incident and a status link that are gone say so with the same page", () => {
assert.match(read("pages/ServerDetail.tsx"), /404[\s\S]*<MissingPage title=\{t\("Server not found"\)\}/);
assert.match(read("pages/IncidentDetail.tsx"), /<MissingPage title=\{t\("Incident not found"\)\}/);
assert.match(read("pages/SharedStatus.tsx"), /<ErrorPage code="404" title=\{t\("This link doesn't work any more"\)\}/);
});
test("the pages are styled", () => {
const css = read("styles.css");
for (const rule of [".error-page", ".error-code", ".error-title", ".error-actions", ".error-card"]) assert.ok(css.includes(rule), rule);
});
});
describe("maybe you were looking for", () => {
const pages = [
{ to: "/", label: "Dashboard" },
{ to: "/servers", label: "Servers" },
{ to: "/alerts", label: "Alerts" },
{ to: "/network/devices", label: "Network devices" },
{ to: "/settings", label: "Settings" },
{ to: "/proxmox", label: "Proxmox" },
{ to: "/uptime-kuma", label: "Uptime Kuma" },
];
const first = (path: string) => suggestPages(path, pages).map((p) => p.to);
test("a part of a name, a misspelling and a page that has moved are all recognised", () => {
assert.deepEqual(first("/server"), ["/servers"]);
assert.equal(first("/sevrers")[0], "/servers");
assert.ok(!suggestPages("/sevrers", [...pages, { to: "/secrets", label: "Secrets" }]).some((p) => p.to === "/secrets"), "a different word two slips away is not a suggestion");
assert.equal(first("/alert")[0], "/alerts");
assert.equal(first("/settings/no-such-tab")[0], "/settings");
assert.equal(first("/network/devicess")[0], "/network/devices");
assert.equal(first("/uptimekuma")[0], "/uptime-kuma");
assert.equal(first("/Proxmox/")[0], "/proxmox");
});
test("a query or a fragment is not part of the address, and an address with nothing like it suggests nothing", () => {
assert.equal(first("/servers?status=offline")[0], "/servers");
assert.deepEqual(first("/zzzz"), []);
assert.deepEqual(first("/"), []);
assert.deepEqual(first("/qx/yw"), []);
});
test("at most three, none twice, best first", () => {
const many = [...pages, { to: "/servers", label: "Servers again" }, { to: "/servers/compare", label: "Compare servers" }, { to: "/servers/x", label: "Server x" }, { to: "/servers/y", label: "Server y" }];
const found = suggestPages("/servers", many).map((p) => p.to);
assert.equal(found.length, 3);
assert.equal(new Set(found).size, 3);
assert.equal(found[0], "/servers");
});
test("the distance between two words counts the single-letter changes", () => {
assert.equal(distance("servers", "servers"), 0);
assert.equal(distance("sevrers", "servers"), 1, "two letters swapped is one slip");
assert.equal(distance("sevrers", "secrets"), 2);
assert.equal(distance("alert", "alerts"), 1);
assert.equal(distance("", "abc"), 3);
});
});