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>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-17 18:06:14 +01:00
1 parent b8ce337dfb
commit 8ffae62281
16 files changed
+662 -31

No files matched your search

+11 -1
View File
@@ -95,6 +95,7 @@ import { alertsBulkRouter, inventoryBulkRouter, serversBulkRouter } from "./rout
import { publicCalendarRouter } from "./routes/publicCalendar.js";
import { heartbeatPingRouter } from "./routes/heartbeatPing.js";
import { apiErrorHandler } from "./utils/apiErrorHandler.js";
import { notFoundHandler } from "./utils/errorPage.js";
import { securityHeaders } from "./utils/securityHeaders.js";
import { sameOriginGuard } from "./utils/sameOriginGuard.js";
@@ -102,6 +103,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const webDist = join(__dirname, "..", "..", "web", "dist");
const agentDir = join(__dirname, "..", "..", "agent");
/** The addresses the server answers itself (the API, sign-in, the agent files, the metrics): never one of the app's pages. */
const isServerPath = (path: string) => /^\/(api|auth|agent|metrics)(\/|$)/.test(path);
/**
* The whole web application, ready to listen. It lives apart from index.ts (which also runs migrations and starts the
* schedulers) so the tests can run the real thing — the order of the middleware below is part of what they check.
@@ -249,9 +253,15 @@ export function createApp() {
if (existsSync(webDist)) {
app.use(express.static(webDist));
app.get("*", (_req, res) => res.sendFile(join(webDist, "index.html")));
// Every page of the app is drawn by the app, so an address that is one of its pages gets index.html. What is not one — the server's own namespaces, and anything that names a file (a script
// or an image that isn't there) — must not be answered with a page and a 200: it falls through to the 404 below.
app.get("*", (req, res, next) => {
if (isServerPath(req.path) || /\.[a-z0-9]+$/i.test(req.path)) return next();
res.sendFile(join(webDist, "index.html"));
});
}
app.use(notFoundHandler);
app.use(apiErrorHandler);
return app;
}
+2 -9
View File
@@ -12,6 +12,7 @@ import { recordAudit } from "../services/audit.js";
import { verifyIdTokenSignature } from "./idToken.js";
import { rateLimit } from "../utils/rateLimit.js";
import { pictureFromClaims } from "../services/avatars.js";
import { sendErrorPage } from "../utils/errorPage.js";
export const authRouter = Router();
@@ -19,14 +20,6 @@ export const authRouter = Router();
// audit log, so without a limit one script could fill the disk and the log.
const signInLimiter = rateLimit({ windowMs: 60_000, max: 20, message: "Too many sign-in attempts. Wait a minute and try again." });
const SIGN_IN_FAILED_PAGE = `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign-in failed</title></head>
<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5">
<h1>Sign-in failed</h1>
<p>Something went wrong while signing you in. <a href="/auth/login">Try again</a>.</p>
<p>If it keeps failing, ask an administrator to look at the audit log.</p>
</body></html>`;
/**
* A sign-in that didn't work: the person gets a plain explanation (never the reason — that tells an attacker what to adjust),
* and the reason goes to the server log and, unless it's just a stale page, the audit log.
@@ -47,7 +40,7 @@ async function failSignIn(req: Request, res: Response, reason: string, err?: unk
}
}
delete req.session.pendingAuth; // a failed attempt's state and verifier can't be tried again
res.status(400).type("html").send(SIGN_IN_FAILED_PAGE);
sendErrorPage(req, res, 400, "sign_in_failed");
}
authRouter.get("/login", signInLimiter, async (req, res, next) => {
+3 -1
View File
@@ -1,14 +1,16 @@
import type { NextFunction, Request, Response } from "express";
import { sendErrorPage, wantsPage } from "./errorPage.js";
/**
* The app's last-resort error handler. A body that's too large or isn't valid JSON is the caller's doing, so it's answered
* as such (413 / 400) rather than as a server error — an agent whose report is too big then sees "payload_too_large", not a
* vague 500.
*/
export function apiErrorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction) {
export function apiErrorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
const status = (err as { status?: unknown } | null)?.status;
if (status === 413) return res.status(413).json({ error: "payload_too_large" });
if (status === 400 && (err as { type?: unknown }).type === "entity.parse.failed") return res.status(400).json({ error: "invalid_json" });
console.error(err);
if (wantsPage(req)) return sendErrorPage(req, res, 500, "server_error");
res.status(500).json({ error: "internal_error" });
}
+94
View File
@@ -0,0 +1,94 @@
/**
* The pages the server itself answers with when the app can't: a path that is nothing (outside the app's own routes — those the app draws), a failure while answering a browser, a sign-in
* that didn't work. Self-contained (no script bundle to load — it may be the bundle that is missing) and made to look like the sign-in page: the card, the logo, the app's colours, light or
* dark as the person last chose. English or Swedish, from the browser's language.
*/
import type { Request, Response, NextFunction } from "express";
export type ErrorPageKind = "not_found" | "server_error" | "sign_in_failed";
const TEXT = {
en: {
not_found: { title: "Page not found", message: "There is nothing at this address. The link may be old, or the page may have moved." },
server_error: { title: "Something went wrong", message: "The server couldn't answer that. Try again in a moment; if it keeps happening, the server log has the details." },
sign_in_failed: { title: "Sign-in failed", message: "Something went wrong while signing you in. If it keeps failing, ask an administrator to look at the audit log." },
home: "Go to the dashboard",
retry: "Try again",
},
sv: {
not_found: { title: "Sidan hittades inte", message: "Det finns inget på den här adressen. Länken kan vara gammal, eller så har sidan flyttats." },
server_error: { title: "Något gick fel", message: "Servern kunde inte svara på det. Försök igen om en stund; om det fortsätter finns detaljerna i serverloggen." },
sign_in_failed: { title: "Inloggningen misslyckades", message: "Något gick fel när du loggades in. Om det fortsätter, be en administratör titta i granskningsloggen." },
home: "Gå till översikten",
retry: "Försök igen",
},
} as const;
type Language = keyof typeof TEXT;
const CODE: Record<ErrorPageKind, string> = { not_found: "404", server_error: "500", sign_in_failed: "!" };
const escapeHtml = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
/** Swedish when that is the browser's first choice, else English. */
export function pickLanguage(acceptLanguage: string | undefined): Language {
return /^\s*sv\b/i.test(acceptLanguage ?? "") ? "sv" : "en";
}
// The look of the sign-in page (web/src/styles.css), in the colours of Tabler's light and dark themes.
const STYLE = `
:root{color-scheme:light dark;--bg:#f6f8fb;--surface:#fff;--text:#182433;--muted:#667382;--primary:#066fd1;--shadow:0 1px 3px rgba(24,36,51,.12)}
[data-bs-theme=dark]{--bg:#151f2c;--surface:#182433;--text:#dce1e7;--muted:#9aa4b2;--primary:#4299e1;--shadow:0 1px 3px rgba(0,0,0,.4)}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:1rem;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",sans-serif;line-height:1.5}
.card{width:100%;max-width:30rem;padding:2rem;text-align:center;background:var(--surface);border-radius:4px;box-shadow:var(--shadow)}
.logo{display:block;width:100%;overflow:hidden;margin:-.5rem 0 .75rem}
.logo img{display:block;width:122%;max-width:none;height:auto;margin:-16% -11%}
.code{font-size:4.5rem;font-weight:700;line-height:1;color:var(--muted);opacity:.45}
h1{margin:.75rem 0 .25rem;font-size:1.5rem}
p{margin:0 0 1.5rem;color:var(--muted)}
.actions{display:flex;flex-wrap:wrap;justify-content:center;gap:.5rem}
a.btn{display:inline-block;padding:.4375rem 1rem;border:1px solid var(--primary);border-radius:4px;background:var(--primary);color:#fff;font-size:.875rem;text-decoration:none}
a.btn.plain{background:transparent;color:var(--primary)}
a.btn:focus-visible{outline:2px solid var(--primary);outline-offset:2px}
`;
// The same choice of theme as the app's own page (web/index.html): what the person picked, else what their system prefers.
const THEME_SCRIPT = `(function(){try{var s=localStorage.getItem("hlm-theme");var d=s==="light"||s==="dark"?s:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";document.documentElement.setAttribute("data-bs-theme",d)}catch(e){}})()`;
export function errorPageHtml(kind: ErrorPageKind, language: Language = "en"): string {
const text = TEXT[language];
const { title, message } = text[kind];
// A failed sign-in is tried again from the start; the others go home.
const primary = kind === "sign_in_failed" ? `<a class="btn" href="/auth/login">${escapeHtml(text.retry)}</a>` : kind === "server_error" ? `<a class="btn" href="">${escapeHtml(text.retry)}</a>` : "";
const home = `<a class="btn${primary ? " plain" : ""}" href="/">${escapeHtml(text.home)}</a>`;
return `<!doctype html>
<html lang="${language}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)} · Homelab Manager</title>
<script>${THEME_SCRIPT}</script><style>${STYLE}</style></head>
<body><main class="card">
<span class="logo"><img src="/logo.webp" alt="Homelab Manager" width="901" height="460"></span>
<div class="code" aria-hidden="true">${CODE[kind]}</div>
<h1>${escapeHtml(title)}</h1>
<p>${escapeHtml(message)}</p>
<div class="actions">${primary}${home}</div>
</main></body></html>`;
}
/** Whether the one asking is a browser opening a page, rather than the app's own code (or a script) asking for data. */
export function wantsPage(req: Request): boolean {
return !req.path.startsWith("/api/") && req.accepts(["json", "html"]) === "html";
}
/** Sends the page for `kind` with `status`, in the language the browser asks for. */
export function sendErrorPage(req: Request, res: Response, status: number, kind: ErrorPageKind): void {
res.status(status).type("html").send(errorPageHtml(kind, pickLanguage(req.headers["accept-language"])));
}
/**
* The last thing that answers: nothing above knew this path. An address in the app's own namespace (/api, /auth, /agent, /metrics), or from code that wants data, gets the plain JSON 404 the
* rest of the API gives; a browser gets the page.
*/
export function notFoundHandler(req: Request, res: Response, _next: NextFunction): void {
if (wantsPage(req)) return sendErrorPage(req, res, 404, "not_found");
res.status(404).json({ error: "not_found", message: "No such address." });
}