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

+2
View File
@@ -1101,6 +1101,8 @@ install one-liner on a host to pick that up.
**Ports named by their containers.** When a server's Docker host is in Dockhand (the Docker integration), the ports its running containers publish are named after the container — 8096 → *jellyfin* — on the server's Ports card, in the agent table on the Network → Ports page (hover for the image) and in the new-port alert ("a new port is listening — 8096/tcp jellyfin (container)"). It is automatic: nothing to set up beyond the Docker host in Dockhand having the same name as the server (the short name, the hostname or an address — the match Uptime Kuma targets use), and it is only a name beside the port. A label you wrote wins; a container's name wins over a port preset's; it is never written onto the port notes, so a published port is still a new port to be noted, and a container that starts publishing something is still news — now with its name. It is read on the health pass from the container list Dockhand already gives (every 15 minutes, and at start-up, whether or not the container alerts are on); a Docker host Dockhand can't reach keeps its names, and names not refreshed for a day are dropped. Containers on the host network publish nothing Docker lists, so their ports aren't named. **Ports named by their containers.** When a server's Docker host is in Dockhand (the Docker integration), the ports its running containers publish are named after the container — 8096 → *jellyfin* — on the server's Ports card, in the agent table on the Network → Ports page (hover for the image) and in the new-port alert ("a new port is listening — 8096/tcp jellyfin (container)"). It is automatic: nothing to set up beyond the Docker host in Dockhand having the same name as the server (the short name, the hostname or an address — the match Uptime Kuma targets use), and it is only a name beside the port. A label you wrote wins; a container's name wins over a port preset's; it is never written onto the port notes, so a published port is still a new port to be noted, and a container that starts publishing something is still news — now with its name. It is read on the health pass from the container list Dockhand already gives (every 15 minutes, and at start-up, whether or not the container alerts are on); a Docker host Dockhand can't reach keeps its names, and names not refreshed for a day are dropped. Containers on the host network publish nothing Docker lists, so their ports aren't named.
**Error pages** (404, 403, 500). An address that leads nowhere shows a *Page not found* page inside the menu — the address, the pages of the menu it most looks like (a misspelling like `/sevrers` offers *Servers*), and buttons for the dashboard, back and the search (Ctrl+K) — instead of an empty page. A page your role doesn't open says *No access* (403). A page that fails while it is drawn is caught, so the menu stays and the rest of the app keeps working (*Something went wrong*, with the details folded away); going to another page clears it. A server or an incident that is gone, and a status-page link that no longer works, say so in the same style. The server's own answers match: an address under `/api`, `/auth`, `/agent` or `/metrics` that doesn't exist is a JSON 404 (it used to be answered with the app's front page and a 200), a browser opening such an address, a missing file, or a failed sign-in is shown a page in the look of the sign-in card — light or dark as you last chose, English or Swedish from the browser's language — and a server error shown to a browser is a page rather than raw JSON.
**Port presets** (Network → Ports → the *Presets* tab). A preset is a named list of ports written once — *Remote access* (SSH, RDP, VNC, WinRM), *Databases* (MySQL, PostgreSQL, Redis, MongoDB …), *Web*, *File sharing*, *Homelab tools*, and what a machine has open out of the box — *Windows client*, *Windows server* (with the Active Directory ports) and *Debian / Ubuntu* — and for the network, *Network services* (DNS, DHCP, NTP, SNMP, syslog, RADIUS, VPNs, MikroTik, iperf3) and *Tailscale*, come ready-made, and are ordinary presets you can change or delete. The ones added later are added once to an install that already had presets (a preset of the same name is left alone, a deleted one is not put back). Add your own by typing one port to a line (`3389 RDP`, `53/udp DNS`). A preset does three things: it **names ports** — a port in any preset shows its name (3389 → RDP) on every server's Ports card, in the agent table and in the new-port alert ("a new port is listening — 3389/tcp RDP"), without a label typed for each host, and a name you write yourself always wins; it **checks hosts** — pick any number of servers and see in one table which of the preset's TCP ports are open on each, from a scan from the app (private addresses only, at the server's first known address; what it finds is remembered like any scan); and it **names the open ports on all of them** in one go, keeping names somebody already wrote unless you say to replace them. Note that a port with a name counts as noted, so writing names also quiets the new-port alert for those ports. A scan only looks at TCP; a UDP port in a preset is only given its name. Operators change presets; everyone sees them. **Port presets** (Network → Ports → the *Presets* tab). A preset is a named list of ports written once — *Remote access* (SSH, RDP, VNC, WinRM), *Databases* (MySQL, PostgreSQL, Redis, MongoDB …), *Web*, *File sharing*, *Homelab tools*, and what a machine has open out of the box — *Windows client*, *Windows server* (with the Active Directory ports) and *Debian / Ubuntu* — and for the network, *Network services* (DNS, DHCP, NTP, SNMP, syslog, RADIUS, VPNs, MikroTik, iperf3) and *Tailscale*, come ready-made, and are ordinary presets you can change or delete. The ones added later are added once to an install that already had presets (a preset of the same name is left alone, a deleted one is not put back). Add your own by typing one port to a line (`3389 RDP`, `53/udp DNS`). A preset does three things: it **names ports** — a port in any preset shows its name (3389 → RDP) on every server's Ports card, in the agent table and in the new-port alert ("a new port is listening — 3389/tcp RDP"), without a label typed for each host, and a name you write yourself always wins; it **checks hosts** — pick any number of servers and see in one table which of the preset's TCP ports are open on each, from a scan from the app (private addresses only, at the server's first known address; what it finds is remembered like any scan); and it **names the open ports on all of them** in one go, keeping names somebody already wrote unless you say to replace them. Note that a port with a name counts as noted, so writing names also quiets the new-port alert for those ports. A scan only looks at TCP; a UDP port in a preset is only given its name. Operators change presets; everyone sees them.
**Network → Ports** is the cross-server counterpart: one page listing every **Network → Ports** is the cross-server counterpart: one page listing every
+11 -1
View File
@@ -95,6 +95,7 @@ import { alertsBulkRouter, inventoryBulkRouter, serversBulkRouter } from "./rout
import { publicCalendarRouter } from "./routes/publicCalendar.js"; import { publicCalendarRouter } from "./routes/publicCalendar.js";
import { heartbeatPingRouter } from "./routes/heartbeatPing.js"; import { heartbeatPingRouter } from "./routes/heartbeatPing.js";
import { apiErrorHandler } from "./utils/apiErrorHandler.js"; import { apiErrorHandler } from "./utils/apiErrorHandler.js";
import { notFoundHandler } from "./utils/errorPage.js";
import { securityHeaders } from "./utils/securityHeaders.js"; import { securityHeaders } from "./utils/securityHeaders.js";
import { sameOriginGuard } from "./utils/sameOriginGuard.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 webDist = join(__dirname, "..", "..", "web", "dist");
const agentDir = join(__dirname, "..", "..", "agent"); 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 * 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. * 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)) { if (existsSync(webDist)) {
app.use(express.static(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); app.use(apiErrorHandler);
return app; return app;
} }
+2 -9
View File
@@ -12,6 +12,7 @@ import { recordAudit } from "../services/audit.js";
import { verifyIdTokenSignature } from "./idToken.js"; import { verifyIdTokenSignature } from "./idToken.js";
import { rateLimit } from "../utils/rateLimit.js"; import { rateLimit } from "../utils/rateLimit.js";
import { pictureFromClaims } from "../services/avatars.js"; import { pictureFromClaims } from "../services/avatars.js";
import { sendErrorPage } from "../utils/errorPage.js";
export const authRouter = Router(); 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. // 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 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), * 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. * 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 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) => { authRouter.get("/login", signInLimiter, async (req, res, next) => {
+3 -1
View File
@@ -1,14 +1,16 @@
import type { NextFunction, Request, Response } from "express"; 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 * 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 * 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. * 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; const status = (err as { status?: unknown } | null)?.status;
if (status === 413) return res.status(413).json({ error: "payload_too_large" }); 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" }); if (status === 400 && (err as { type?: unknown }).type === "entity.parse.failed") return res.status(400).json({ error: "invalid_json" });
console.error(err); console.error(err);
if (wantsPage(req)) return sendErrorPage(req, res, 500, "server_error");
res.status(500).json({ error: "internal_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." });
}
+192
View File
@@ -0,0 +1,192 @@
/**
* 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);
});
});
+9 -5
View File
@@ -1,6 +1,8 @@
import { Fragment, useEffect, useState, type ReactNode } from "react"; import { Fragment, useEffect, useState, type ReactNode } from "react";
import { detectLanguage, forgetLanguage, setLanguage, t, useLanguage } from "./i18n"; import { detectLanguage, forgetLanguage, setLanguage, t, useLanguage } from "./i18n";
import { Routes, Route, Navigate, useLocation, useParams } from "react-router-dom"; import { Routes, Route, Navigate, useLocation, useParams } from "react-router-dom";
import { ErrorBoundary, ForbiddenPage } from "./components/ErrorPage";
import NotFound from "./pages/NotFound";
import { api, type CurrentUser, type UserRole, UnauthorizedError } from "./api/client"; import { api, type CurrentUser, type UserRole, UnauthorizedError } from "./api/client";
import Login from "./pages/Login"; import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard"; import Dashboard from "./pages/Dashboard";
@@ -96,11 +98,7 @@ function RequireRole({
minRole: UserRole; minRole: UserRole;
children: ReactNode; children: ReactNode;
}) { }) {
if (roleRank[user.role] < roleRank[minRole]) { if (roleRank[user.role] < roleRank[minRole]) return <ForbiddenPage minRole={minRole === "viewer" ? "operator" : minRole} />;
return (
<div className="alert alert-danger">{t("You don't have permission to view this page.")}</div>
);
}
return <>{children}</>; return <>{children}</>;
} }
@@ -174,8 +172,10 @@ export default function App() {
} }
function Shelled({ user }: { user: CurrentUser }) { function Shelled({ user }: { user: CurrentUser }) {
const { pathname } = useLocation();
return ( return (
<AppShell user={user}> <AppShell user={user}>
<ErrorBoundary resetKey={pathname}>
<Routes> <Routes>
<Route path="/" element={<Dashboard user={user} />} /> <Route path="/" element={<Dashboard user={user} />} />
<Route path="/my-work" element={<MyWorkPage user={user} />} /> <Route path="/my-work" element={<MyWorkPage user={user} />} />
@@ -285,8 +285,12 @@ function Shelled({ user }: { user: CurrentUser }) {
<Route path="backup" element={<Navigate to="/settings/data" replace />} /> <Route path="backup" element={<Navigate to="/settings/data" replace />} />
<Route path="logs" element={<Navigate to="/settings/data?view=logs" replace />} /> <Route path="logs" element={<Navigate to="/settings/data?view=logs" replace />} />
<Route path="cache" element={<Navigate to="/settings/data?view=cache" replace />} /> <Route path="cache" element={<Navigate to="/settings/data?view=cache" replace />} />
<Route path="*" element={<NotFound user={user} />} />
</Route> </Route>
{/* Anything else leads nowhere: say so, and offer the way on, rather than showing an empty page. */}
<Route path="*" element={<NotFound user={user} />} />
</Routes> </Routes>
</ErrorBoundary>
<DialogHost /> <DialogHost />
<ToastHost /> <ToastHost />
</AppShell> </AppShell>
+136
View File
@@ -0,0 +1,136 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Link } from "react-router-dom";
import { IconArrowLeft, IconLayoutDashboard, IconRefresh } from "@tabler/icons-react";
import { useEnvironment } from "../utils/environment";
import { t } from "../i18n";
/**
* A page that says where you ended up and what to do next, instead of a blank one: the code in large type, what it means, and the way out. Inside the app it sits where the page would
* have been, with the menu around it; "standalone" is for the places that have no menu (a link someone was given, a crash outside the app's frame) and gets a card with the logo, as the sign-in page has.
*/
export default function ErrorPage({ code, title, message, actions, children, standalone }: { code: string; title: string; message?: ReactNode; actions?: ReactNode; children?: ReactNode; standalone?: boolean }) {
const environment = useEnvironment();
const body = (
<div className="error-page">
<div className="error-code" aria-hidden="true">
{code}
</div>
<h2 className="page-title error-title">{title}</h2>
{message && <p className="error-message">{message}</p>}
{children}
{actions && <div className="error-actions">{actions}</div>}
</div>
);
if (!standalone) return body;
return (
<div className="login-screen">
<div className={`login-card error-card ${environment ? "login-card-env" : ""}`}>
<h1 className="login-logo">
<span className="logo-frame">
<img src="/logo.webp" alt="Homelab Manager" width={901} height={460} />
</span>
{environment?.name && <span className="badge env-badge">{environment.name}</span>}
</h1>
{body}
</div>
</div>
);
}
/** The way back to the start, which every error page offers. */
export function DashboardButton({ primary = true }: { primary?: boolean }) {
return (
<Link to="/" className={`btn ${primary ? "btn-primary" : ""}`}>
<IconLayoutDashboard size={18} className="me-1" aria-hidden="true" />
{t("Go to the dashboard")}
</Link>
);
}
/** For a page the person's role doesn't open. */
export function ForbiddenPage({ minRole }: { minRole: "operator" | "admin" }) {
return (
<ErrorPage
code="403"
title={t("No access")}
message={minRole === "admin" ? t("Only administrators can open this page.") : t("Only operators and administrators can open this page.")}
actions={<DashboardButton />}
/>
);
}
/** For one thing that isn't there (any more): a server, an incident — with the list it would have been in. */
export function MissingPage({ title, message, to, toLabel }: { title: string; message: ReactNode; to: string; toLabel: string }) {
return (
<ErrorPage
code="404"
title={title}
message={message}
actions={
<>
<Link to={to} className="btn btn-primary">
<IconArrowLeft size={18} className="me-1" aria-hidden="true" />
{toLabel}
</Link>
<DashboardButton primary={false} />
</>
}
/>
);
}
/** What a page that failed while it was being drawn shows. The details are for whoever has to find out why. */
function CrashPage({ error, standalone }: { error: Error; standalone?: boolean }) {
return (
<ErrorPage
code="500"
title={t("Something went wrong")}
message={t("This page ran into an error and couldn't be drawn. Reloading usually fixes it.")}
standalone={standalone}
actions={
<>
<button type="button" className="btn btn-primary" onClick={() => window.location.reload()}>
<IconRefresh size={18} className="me-1" aria-hidden="true" />
{t("Reload the page")}
</button>
{standalone ? (
<a className="btn" href="/">
{t("Go to the dashboard")}
</a>
) : (
<DashboardButton primary={false} />
)}
</>
}
>
<details className="error-details">
<summary>{t("Details for whoever looks into it")}</summary>
<pre>{error.message || String(error)}</pre>
</details>
</ErrorPage>
);
}
/**
* Catches a page that fails while it is drawn, so one page's bug leaves the menu and the rest of the app in place instead of a white screen. `resetKey` is the address: going to another
* page clears it.
*/
export class ErrorBoundary extends Component<{ children: ReactNode; resetKey?: string; standalone?: boolean }, { error: Error | null }> {
state: { error: Error | null } = { error: null };
static getDerivedStateFromError(error: Error) {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
console.error(error, info.componentStack);
}
componentDidUpdate(prev: { resetKey?: string }) {
if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null });
}
render() {
return this.state.error ? <CrashPage error={this.state.error} standalone={this.props.standalone} /> : this.props.children;
}
}
+19
View File
@@ -239,6 +239,7 @@ export const sv: Record<string, string> = {
"All online": "Alla online", "All online": "Alla online",
"All reporting": "Alla rapporterar", "All reporting": "Alla rapporterar",
"All results": "Alla resultat", "All results": "Alla resultat",
"All servers": "Alla servrar",
"All severities": "Alla allvarlighetsgrader", "All severities": "Alla allvarlighetsgrader",
"All sources": "Alla källor", "All sources": "Alla källor",
"All statuses": "Alla status", "All statuses": "Alla status",
@@ -543,6 +544,7 @@ export const sv: Record<string, string> = {
"Description": "Beskrivning", "Description": "Beskrivning",
"Destination": "Mål", "Destination": "Mål",
"Details": "Detaljer", "Details": "Detaljer",
"Details for whoever looks into it": "Detaljer för den som utreder det",
"Device": "Enhet", "Device": "Enhet",
"Device (optional)": "Enhet (valfri)", "Device (optional)": "Enhet (valfri)",
"Devices": "Enheter", "Devices": "Enheter",
@@ -752,7 +754,9 @@ export const sv: Record<string, string> = {
"Girls": "Flickor", "Girls": "Flickor",
"Give it a new address": "Ge den en ny adress", "Give it a new address": "Ge den en ny adress",
"Give up after": "Ge upp efter", "Give up after": "Ge upp efter",
"Go back": "Gå tillbaka",
"Go to Servers": "Gå till Servrar", "Go to Servers": "Gå till Servrar",
"Go to the dashboard": "Gå till översikten",
"Go to the inventory": "Gå till inventariet", "Go to the inventory": "Gå till inventariet",
"Good answers": "Bra svar", "Good answers": "Bra svar",
"Got it": "Uppfattat", "Got it": "Uppfattat",
@@ -849,6 +853,7 @@ export const sv: Record<string, string> = {
"In total": "Totalt", "In total": "Totalt",
"In your browser": "I din webbläsare", "In your browser": "I din webbläsare",
"Inactive": "Inaktiv", "Inactive": "Inaktiv",
"Incident not found": "Incidenten hittades inte",
"Incidents": "Incidenter", "Incidents": "Incidenter",
"Incidents began": "Incidenter som började", "Incidents began": "Incidenter som började",
"Indefinitely — automatic deletion is off.": "Obegränsat — automatisk borttagning är av.", "Indefinitely — automatic deletion is off.": "Obegränsat — automatisk borttagning är av.",
@@ -883,6 +888,7 @@ export const sv: Record<string, string> = {
"It is about the server": "Det gäller servern", "It is about the server": "Det gäller servern",
"It is not growing in a straight enough line to forecast.": "Den växer inte i en tillräckligt rak linje för att kunna förutsägas.", "It is not growing in a straight enough line to forecast.": "Den växer inte i en tillräckligt rak linje för att kunna förutsägas.",
"It is taken out of the incident's history.": "Den tas bort ur incidentens historik.", "It is taken out of the incident's history.": "Den tas bort ur incidentens historik.",
"It may have ended or been taken back. Ask whoever gave it to you for a new one.": "Den kan ha upphört eller tagits tillbaka. Be den som gav dig den om en ny.",
"It relies on nothing here.": "Den förlitar sig inte på något här.", "It relies on nothing here.": "Den förlitar sig inte på något här.",
"It runs on nothing, so its alerts always stand alone.": "Den körs inte på något, så dess larm står alltid på egna ben.", "It runs on nothing, so its alerts always stand alone.": "Den körs inte på något, så dess larm står alltid på egna ben.",
"It runs on the server": "Det körs på servern", "It runs on the server": "Det körs på servern",
@@ -1043,6 +1049,7 @@ export const sv: Record<string, string> = {
"Mark every new port as expected": "Markera varje ny port som förväntad", "Mark every new port as expected": "Markera varje ny port som förväntad",
"Matched to a server": "Kopplad till en server", "Matched to a server": "Kopplad till en server",
"Matching settings": "Matchande inställningar", "Matching settings": "Matchande inställningar",
"Maybe you were looking for": "Du kanske letade efter",
"Measure again": "Mät igen", "Measure again": "Mät igen",
"Measured on": "Uppmätt den", "Measured on": "Uppmätt den",
"Media managers": "Mediahanterare", "Media managers": "Mediahanterare",
@@ -1137,6 +1144,7 @@ export const sv: Record<string, string> = {
"Night": "Natt", "Night": "Natt",
"Night — touch the screen to wake it": "Natt — rör vid skärmen för att väcka den", "Night — touch the screen to wake it": "Natt — rör vid skärmen för att väcka den",
"No": "Nej", "No": "Nej",
"No access": "Ingen åtkomst",
"No active alerts, but some checks couldn't run": "Inga aktiva larm, men vissa kontroller kunde inte köras", "No active alerts, but some checks couldn't run": "Inga aktiva larm, men vissa kontroller kunde inte köras",
"No active alerts.": "Inga aktiva larm.", "No active alerts.": "Inga aktiva larm.",
"No active sessions": "Inga aktiva sessioner", "No active sessions": "Inga aktiva sessioner",
@@ -1416,6 +1424,8 @@ export const sv: Record<string, string> = {
"One thing isn't working": "En sak fungerar inte", "One thing isn't working": "En sak fungerar inte",
"Online": "Online", "Online": "Online",
"Online / Total": "Online / Totalt", "Online / Total": "Online / Totalt",
"Only administrators can open this page.": "Bara administratörer kan öppna den här sidan.",
"Only operators and administrators can open this page.": "Bara operatörer och administratörer kan öppna den här sidan.",
"Only the first 200 are shown — search to find the others.": "Bara de första 200 visas — sök för att hitta de andra.", "Only the first 200 are shown — search to find the others.": "Bara de första 200 visas — sök för att hitta de andra.",
"Only the larger ones": "Endast de större", "Only the larger ones": "Endast de större",
"Only those with updates": "Bara de med uppdateringar", "Only those with updates": "Bara de med uppdateringar",
@@ -1451,6 +1461,7 @@ export const sv: Record<string, string> = {
"Package": "Paket", "Package": "Paket",
"Page {page} of {pages} ({total} total)": "Sida {page} av {pages} ({total} totalt)", "Page {page} of {pages} ({total} total)": "Sida {page} av {pages} ({total} totalt)",
"Page contains": "Sidan innehåller", "Page contains": "Sidan innehåller",
"Page not found": "Sidan hittades inte",
"Pages": "Sidor", "Pages": "Sidor",
"Pages it shows, in the order of the board": "Sidor den visar, i tavlans ordning", "Pages it shows, in the order of the board": "Sidor den visar, i tavlans ordning",
"Paid": "Betald", "Paid": "Betald",
@@ -1599,6 +1610,7 @@ export const sv: Record<string, string> = {
"Registrations": "Registreringar", "Registrations": "Registreringar",
"Rejected": "Avvisade", "Rejected": "Avvisade",
"Rejected in Semaphore": "Avvisad i Semaphore", "Rejected in Semaphore": "Avvisad i Semaphore",
"Reload the page": "Ladda om sidan",
"Reminded daily from then until it's renewed.": "Påminns dagligen från då tills den förnyas.", "Reminded daily from then until it's renewed.": "Påminns dagligen från då tills den förnyas.",
"Remote access": "Fjärråtkomst", "Remote access": "Fjärråtkomst",
"Remove": "Ta bort", "Remove": "Ta bort",
@@ -1777,6 +1789,7 @@ export const sv: Record<string, string> = {
"Search servers…": "Sök servrar…", "Search servers…": "Sök servrar…",
"Search the change log": "Sök i ändringsloggen", "Search the change log": "Sök i ändringsloggen",
"Search the history": "Sök i historiken", "Search the history": "Sök i historiken",
"Search the pages": "Sök bland sidorna",
"Search the title or the message": "Sök i rubriken eller meddelandet", "Search the title or the message": "Sök i rubriken eller meddelandet",
"Search users": "Sök användare", "Search users": "Sök användare",
"Search, or type a command": "Sök, eller skriv ett kommando", "Search, or type a command": "Sök, eller skriv ett kommando",
@@ -1825,6 +1838,7 @@ export const sv: Record<string, string> = {
"Server": "Server", "Server": "Server",
"Server (optional)": "Server (valfri)", "Server (optional)": "Server (valfri)",
"Server name": "Servernamn", "Server name": "Servernamn",
"Server not found": "Servern hittades inte",
"Server offline after": "Server offline efter", "Server offline after": "Server offline efter",
"Server offline and disk-full alerts (for a server).": "Larm om offline-servrar och fulla diskar (för en server).", "Server offline and disk-full alerts (for a server).": "Larm om offline-servrar och fulla diskar (för en server).",
"Server removed.": "Servern är borttagen.", "Server removed.": "Servern är borttagen.",
@@ -1929,6 +1943,7 @@ export const sv: Record<string, string> = {
"someone": "någon", "someone": "någon",
"Someone in none of those groups": "Någon i ingen av de grupperna", "Someone in none of those groups": "Någon i ingen av de grupperna",
"Something about to expire, an integration failing": "Något som håller på att gå ut, en integration som fallerar", "Something about to expire, an integration failing": "Något som håller på att gå ut, en integration som fallerar",
"Something went wrong": "Något gick fel",
"Sort A–Z": "Sortera A–Ö", "Sort A–Z": "Sortera A–Ö",
"Source": "Källa", "Source": "Källa",
"Speed": "Hastighet", "Speed": "Hastighet",
@@ -2067,6 +2082,7 @@ export const sv: Record<string, string> = {
"The last backup didn't work": "Den senaste backupen fungerade inte", "The last backup didn't work": "Den senaste backupen fungerade inte",
"The last read is old, so this may be out of date.": "Den senaste avläsningen är gammal, så det här kan vara inaktuellt.", "The last read is old, so this may be out of date.": "Den senaste avläsningen är gammal, så det här kan vara inaktuellt.",
"The latest backup didn't succeed, or the newest snapshot failed verification.": "Den senaste backupen lyckades inte, eller den senaste ögonblicksbilden klarade inte verifieringen.", "The latest backup didn't succeed, or the newest snapshot failed verification.": "Den senaste backupen lyckades inte, eller den senaste ögonblicksbilden klarade inte verifieringen.",
"The link may be old, or the page may have moved.": "Länken kan vara gammal, eller så har sidan flyttats.",
"The logo of the system for an integration’s page, the page’s own icon for the rest. Only for this browser, and it applies at once.": "Systemets logga för en integrations sida, sidans egen ikon för resten. Gäller bara den här webbläsaren och slår igenom direkt.", "The logo of the system for an integration’s page, the page’s own icon for the rest. Only for this browser, and it applies at once.": "Systemets logga för en integrations sida, sidans egen ikon för resten. Gäller bara den här webbläsaren och slår igenom direkt.",
"The maintenance window on {name} ends now. A playbook already started keeps running in Semaphore — it can't be stopped from here.": "Underhållsfönstret för {name} avslutas nu. En playbook som redan har startat fortsätter i Semaphore — den kan inte stoppas härifrån.", "The maintenance window on {name} ends now. A playbook already started keeps running in Semaphore — it can't be stopped from here.": "Underhållsfönstret för {name} avslutas nu. En playbook som redan har startat fortsätter i Semaphore — den kan inte stoppas härifrån.",
"The metrics token": "Mätvärdestoken", "The metrics token": "Mätvärdestoken",
@@ -2093,7 +2109,9 @@ export const sv: Record<string, string> = {
"Theme": "Tema", "Theme": "Tema",
"There are no groups.": "Det finns inga grupper.", "There are no groups.": "Det finns inga grupper.",
"There are no options to edit on this kind of zone from here.": "Det finns inga alternativ att redigera för den här sortens zon härifrån.", "There are no options to edit on this kind of zone from here.": "Det finns inga alternativ att redigera för den här sortens zon härifrån.",
"There is no incident like that. It may be old enough to have been removed.": "Det finns ingen sådan incident. Den kan vara så gammal att den har tagits bort.",
"There is no osTicket integration yet. Add one under Integrations.": "Det finns ingen osTicket-integration ännu. Lägg till en under Integrationer.", "There is no osTicket integration yet. Add one under Integrations.": "Det finns ingen osTicket-integration ännu. Lägg till en under Integrationer.",
"There is no server with that number. It may have been removed.": "Det finns ingen server med det numret. Den kan ha tagits bort.",
"These need a certificate.": "Dessa behöver ett certifikat.", "These need a certificate.": "Dessa behöver ett certifikat.",
"They could not be listed (the key may not be allowed to).": "De gick inte att lista (nyckeln kanske inte får).", "They could not be listed (the key may not be allowed to).": "De gick inte att lista (nyckeln kanske inte får).",
"They could not be listed.": "De gick inte att lista.", "They could not be listed.": "De gick inte att lista.",
@@ -2104,6 +2122,7 @@ export const sv: Record<string, string> = {
"This Homelab Manager instance uses a self-signed certificate (skip TLS verification on the agent)": "Den här Homelab Manager-instansen använder ett självsignerat certifikat (hoppa över TLS-verifiering i agenten)", "This Homelab Manager instance uses a self-signed certificate (skip TLS verification on the agent)": "Den här Homelab Manager-instansen använder ett självsignerat certifikat (hoppa över TLS-verifiering i agenten)",
"This integration has no database login for closing tickets yet": "Den här integrationen har ingen databasinloggning för att stänga ärenden ännu", "This integration has no database login for closing tickets yet": "Den här integrationen har ingen databasinloggning för att stänga ärenden ännu",
"This link doesn't work any more": "Den här länken fungerar inte längre", "This link doesn't work any more": "Den här länken fungerar inte längre",
"This page ran into an error and couldn't be drawn. Reloading usually fixes it.": "Sidan stötte på ett fel och kunde inte visas. Det brukar räcka att ladda om den.",
"This plan has none.": "Den här planen har inga.", "This plan has none.": "Den här planen har inga.",
"This preset has no TCP ports, and a scan only looks at TCP.": "Den här förinställningen har inga TCP-portar, och en skanning tittar bara på TCP.", "This preset has no TCP ports, and a scan only looks at TCP.": "Den här förinställningen har inga TCP-portar, och en skanning tittar bara på TCP.",
"This server has limits of its own; everything else follows Settings.": "Den här servern har egna gränser; allt annat följer Inställningar.", "This server has limits of its own; everything else follows Settings.": "Den här servern har egna gränser; allt annat följer Inställningar.",
+5 -1
View File
@@ -2,6 +2,7 @@ import React from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom"; import { BrowserRouter } from "react-router-dom";
import App from "./App"; import App from "./App";
import { ErrorBoundary } from "./components/ErrorPage";
import "@tabler/core/dist/css/tabler.min.css"; import "@tabler/core/dist/css/tabler.min.css";
import "./styles.css"; import "./styles.css";
import { loadEnvironment } from "./utils/environment"; import { loadEnvironment } from "./utils/environment";
@@ -25,7 +26,10 @@ if ("serviceWorker" in navigator && import.meta.env.PROD) {
ReactDOM.createRoot(document.getElementById("root")!).render( ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
<BrowserRouter> <BrowserRouter>
<App /> {/* The last net: a crash outside the app's frame (the sign-in page, a wall display) still says what happened. */}
<ErrorBoundary standalone>
<App />
</ErrorBoundary>
</BrowserRouter> </BrowserRouter>
</React.StrictMode>, </React.StrictMode>,
); );
+2 -7
View File
@@ -7,6 +7,7 @@ import RunbookEntry from "../components/RunbookEntry";
import TimeAgo from "../components/TimeAgo"; import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton"; import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { MissingPage } from "../components/ErrorPage";
import { confirmDialog } from "../utils/dialogs"; import { confirmDialog } from "../utils/dialogs";
import { formatDateTime } from "../utils/date"; import { formatDateTime } from "../utils/date";
import { readableError } from "../utils/errors"; import { readableError } from "../utils/errors";
@@ -96,13 +97,7 @@ export default function IncidentDetail({ user }: { user: CurrentUser }) {
} }
if (missing) { if (missing) {
return ( return <MissingPage title={t("Incident not found")} message={t("There is no incident like that. It may be old enough to have been removed.")} to="/alerts?view=history" toLabel={t("All incidents")} />;
<div className="card">
<div className="card-body text-secondary">
There is no incident like that (it may be old enough to have been removed). <Link to="/alerts?view=history">{t("All incidents")}</Link>.
</div>
</div>
);
} }
if (!detail) { if (!detail) {
return ( return (
+54
View File
@@ -0,0 +1,54 @@
import { useMemo } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { IconArrowLeft, IconSearch } from "@tabler/icons-react";
import type { CurrentUser } from "../api/client";
import ErrorPage, { DashboardButton } from "../components/ErrorPage";
import { isGroup, visibleNav } from "../layout/nav";
import { suggestPages } from "../utils/pageSuggestions";
import { t } from "../i18n";
/** What an address that leads nowhere shows: the address, the pages of the menu it most looks like, and the ways on — the dashboard, back, and the search that opens with Ctrl+K. */
export default function NotFound({ user }: { user: CurrentUser }) {
const { pathname } = useLocation();
const navigate = useNavigate();
const suggestions = useMemo(() => {
const pages = visibleNav(user.role).flatMap((entry) => (isGroup(entry) ? entry.items : [entry])).map((leaf) => ({ to: leaf.to, label: t(leaf.label) }));
return suggestPages(pathname, pages);
}, [pathname, user.role]);
return (
<ErrorPage
code="404"
title={t("Page not found")}
message={t("The link may be old, or the page may have moved.")}
actions={
<>
<DashboardButton />
{window.history.length > 1 && (
<button type="button" className="btn" onClick={() => navigate(-1)}>
<IconArrowLeft size={18} className="me-1" aria-hidden="true" />
{t("Go back")}
</button>
)}
<button type="button" className="btn" onClick={() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "k", ctrlKey: true, bubbles: true }))}>
<IconSearch size={18} className="me-1" aria-hidden="true" />
{t("Search the pages")}
</button>
</>
}
>
<code className="error-path">{pathname}</code>
{suggestions.length > 0 && (
<div className="error-suggest">
<div className="text-secondary small mb-2">{t("Maybe you were looking for")}</div>
<div className="d-flex gap-2 justify-content-center flex-wrap">
{suggestions.map((s) => (
<Link key={s.to} to={s.to} className="btn btn-sm btn-outline-primary">
{s.label}
</Link>
))}
</div>
</div>
)}
</ErrorPage>
);
}
+6 -1
View File
@@ -40,6 +40,7 @@ import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs"; import { confirmDialog } from "../utils/dialogs";
import { removeWithUndo } from "../utils/undoable"; import { removeWithUndo } from "../utils/undoable";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { MissingPage } from "../components/ErrorPage";
import { useBreadcrumbTail } from "../utils/breadcrumb"; import { useBreadcrumbTail } from "../utils/breadcrumb";
import { PageSkeleton } from "../components/Skeleton"; import { PageSkeleton } from "../components/Skeleton";
import ViewTabs from "../components/ViewTabs"; import ViewTabs from "../components/ViewTabs";
@@ -405,7 +406,11 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
} }
if (loading) return <PageSkeleton />; if (loading) return <PageSkeleton />;
if (error && !detail) return <div className="alert alert-danger">{error}</div>; if (error && !detail) {
// A server number that isn't there (removed, or a mistyped address) is a missing page, not a failure to show in red.
if (/\(404\)/.test(error)) return <MissingPage title={t("Server not found")} message={t("There is no server with that number. It may have been removed.")} to="/servers" toLabel={t("All servers")} />;
return <div className="alert alert-danger">{error}</div>;
}
if (!detail) return null; if (!detail) return null;
const { server, hardware, ipAddresses, dnsMatches, links } = detail; const { server, hardware, ipAddresses, dnsMatches, links } = detail;
+2 -6
View File
@@ -3,6 +3,7 @@ import { useParams } from "react-router-dom";
import { IconAlertTriangle, IconCircleCheck, IconHelpCircle, IconTool } from "@tabler/icons-react"; import { IconAlertTriangle, IconCircleCheck, IconHelpCircle, IconTool } from "@tabler/icons-react";
import { api, type PublicStatus, type PublicStatusItem } from "../api/client"; import { api, type PublicStatus, type PublicStatusItem } from "../api/client";
import { formatDateTime, setDateTimeSettings } from "../utils/date"; import { formatDateTime, setDateTimeSettings } from "../utils/date";
import ErrorPage from "../components/ErrorPage";
import { t } from "../i18n"; import { t } from "../i18n";
const REFRESH_MS = 30_000; const REFRESH_MS = 30_000;
@@ -97,12 +98,7 @@ export default function SharedStatus() {
<div className="page-wrapper" style={{ minHeight: "100vh" }}> <div className="page-wrapper" style={{ minHeight: "100vh" }}>
<div className="container-tight py-4" style={{ maxWidth: 640, margin: "0 auto", paddingLeft: 16, paddingRight: 16 }}> <div className="container-tight py-4" style={{ maxWidth: 640, margin: "0 auto", paddingLeft: 16, paddingRight: 16 }}>
{state === "dead" ? ( {state === "dead" ? (
<div className="card"> <ErrorPage code="404" title={t("This link doesn't work any more")} message={t("It may have ended or been taken back. Ask whoever gave it to you for a new one.")} />
<div className="card-body text-center py-5">
<div className="h3 mb-1">{t("This link doesn't work any more")}</div>
<div className="text-secondary">It may have ended or been taken back. Ask whoever gave it to you for a new one.</div>
</div>
</div>
) : !page ? ( ) : !page ? (
<div className="text-center text-secondary py-5">{state === "unreachable" ? "Can't reach the server right now. Trying again…" : "Loading…"}</div> <div className="text-center text-secondary py-5">{state === "unreachable" ? "Can't reach the server right now. Trying again…" : "Loading…"}</div>
) : ( ) : (
+73
View File
@@ -2038,6 +2038,79 @@ tr.alert-row-child > td:first-child {
color: var(--tblr-secondary); color: var(--tblr-secondary);
} }
/* ── Error pages: 404, 403 and a page that failed. The code in large type, what it means, and the way out. ── */
.error-page {
max-width: 36rem;
margin: 0 auto;
padding: 3rem 1rem;
text-align: center;
}
.error-code {
font-size: clamp(4rem, 14vw, 7rem);
font-weight: 700;
line-height: 1;
letter-spacing: 0.02em;
color: var(--tblr-secondary);
opacity: 0.45;
}
.error-title {
display: block; /* Tabler lays .page-title out as a row, which would pull a short heading to the left */
margin: 0.75rem 0 0.25rem;
font-size: 1.5rem;
}
.error-message {
margin: 0 auto 1rem;
color: var(--tblr-secondary);
}
.error-path {
display: inline-block;
max-width: 100%;
margin-bottom: 1.25rem;
overflow-wrap: anywhere;
}
.error-suggest {
margin-bottom: 1.25rem;
}
.error-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 0.5rem;
}
.error-details {
margin: 0 auto 1.25rem;
text-align: left;
font-size: 0.8125rem;
color: var(--tblr-secondary);
}
.error-details pre {
margin-top: 0.5rem;
max-height: 10rem;
overflow: auto;
white-space: pre-wrap;
}
/* On its own (a crash outside the app's frame): the card of the sign-in page, a little wider, with less space around. */
.error-card {
max-width: 30rem;
}
.error-card .error-page {
padding: 0.5rem 0 0;
}
.error-card .error-code {
font-size: clamp(3.5rem, 12vw, 5rem);
}
/* ── The dashboard's right-hand column: the to-do list as tall as the cards beside it (wide screens), a scrolling card of its own under them (narrow ones). ── */ /* ── The dashboard's right-hand column: the to-do list as tall as the cards beside it (wide screens), a scrolling card of its own under them (narrow ones). ── */
.dash-side { .dash-side {
min-height: 24rem; min-height: 24rem;
+52
View File
@@ -0,0 +1,52 @@
/**
* "Maybe you were looking for…": for an address that leads nowhere, the pages of the menu it most resembles — a misspelling (/sevrers), a part of one (/server, /alert), or a page that
* has moved under another (/settings/nothing → Settings). Pure, so it is tested without a screen.
*/
export interface PageRef {
label: string;
to: string;
}
const words = (text: string): string[] => text.toLowerCase().split(/[^a-z0-9åäö]+/).filter(Boolean);
/** How many single-letter changes (a letter added, dropped or changed, or two next to each other swapped) turn one word into the other. */
export function distance(a: string, b: string): number {
if (a === b) return 0;
const rows: number[][] = [Array.from({ length: b.length + 1 }, (_, j) => j)];
for (let i = 1; i <= a.length; i++) {
const row = [i];
for (let j = 1; j <= b.length; j++) {
row[j] = Math.min(rows[i - 1][j] + 1, row[j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) row[j] = Math.min(row[j], rows[i - 2][j - 2] + 1);
}
rows.push(row);
}
return rows[a.length][b.length];
}
/** How well one typed word matches a word of a page: 3 the same, 2 the start of it (or a near miss), 0 not at all. */
function wordScore(typed: string, page: string): number {
if (typed === page) return 3;
if (typed.length >= 3 && page.startsWith(typed)) return 2;
if (page.length >= 3 && typed.startsWith(page)) return 2;
if (typed.length >= 4 && page.length >= 4 && distance(typed, page) <= (typed.length >= 9 ? 2 : 1)) return 2;
return 0;
}
/** The pages that look most like the address, best first; none when nothing does. */
export function suggestPages(pathname: string, pages: PageRef[], limit = 3): PageRef[] {
const typed = words(pathname.split(/[?#]/)[0]);
if (typed.length === 0) return [];
const seen = new Set<string>();
const scored: { page: PageRef; score: number }[] = [];
for (const page of pages) {
if (seen.has(page.to)) continue;
seen.add(page.to);
const mine = [...words(page.to), ...words(page.label)];
let score = 0;
for (const w of typed) score += Math.max(0, ...mine.map((p) => wordScore(w, p)));
if (score > 0) scored.push({ page, score });
}
scored.sort((a, b) => b.score - a.score || a.page.to.length - b.page.to.length);
return scored.slice(0, limit).map((s) => s.page);
}