Files
Homelab-manager/server/test/shareAndLayout.test.ts
bobbanandClaude Sonnet 5.5 44e393f172 Add saved filter views, a customisable dashboard, server comparison, row keyboard navigation and share links
- Table search, status, tag and sort live in the address; Save view pins one as a favourite.
- Dashboard cards can be moved and hidden per user (users.dashboard_layout, migration 0022).
- Compare two to four servers' load, memory or disk on one chart.
- j/k move through table rows that open a detail panel.
- Share links open a read-only wall without signing in, numbers only or with names
  (share_links, migration 0023); the wall is split into a shared view over two data sources.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 22:15:29 +02:00

267 lines
13 KiB
TypeScript

/**
* Saved views as favourites, the dashboard layout, and the share links that open a read-only wall without signing in.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, 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-share-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, auditLog, shareLinks, maintenanceWindows, secrets } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { meRouter, parseDashboardLayout } = await import("../src/routes/me.js");
const { shareLinksRouter } = await import("../src/routes/shareLinks.js");
const { publicWallRouter } = await import("../src/routes/publicWall.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("parseDashboardLayout", () => {
test("anything that isn't a layout is the default layout", () => {
const empty = { hidden: [], order: {} };
assert.deepEqual(parseDashboardLayout(null), empty);
assert.deepEqual(parseDashboardLayout("not json"), empty);
assert.deepEqual(parseDashboardLayout(JSON.stringify({ hidden: "Gitea" })), empty);
assert.deepEqual(parseDashboardLayout(JSON.stringify({ hidden: ["Gitea"], order: { DNS: 1 } })), { hidden: ["Gitea"], order: { DNS: 1 } });
});
});
describe("favourites, dashboard layout and share links", () => {
let app: Server;
let base = "";
let who = "admin";
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const hours = (n: number) => new Date(Date.now() - n * 3600_000).toISOString();
await db.insert(servers).values([
{ name: "elsa", apiTokenHash: "a", apiTokenPrefix: "a", lastSeenAt: hours(5) }, // stopped reporting
{ name: "anna", apiTokenHash: "b", apiTokenPrefix: "b", lastSeenAt: new Date().toISOString() },
]);
// Something that alerts straight away (a process that has only just started doesn't alert about silent servers for a while).
await db.insert(secrets).values({ name: "Old VPN token", type: "api_token", expiryDate: "2020-01-01", warnDays: 30 });
// Switched off, so collecting the alerts doesn't try to reach it.
await db.insert(integrations).values({ type: "gitea", name: "Gitea", baseUrl: "https://git.lab", config: "{}", enabled: false });
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/me", meRouter);
a.use("/api/share-links", shareLinksRouter);
// The public route has no sign-in: a request there carries no session at all.
const pub = express();
pub.use("/api/public/wall", publicWallRouter);
a.use(pub);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const send = (method: string, path: string, body?: unknown) =>
fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
test("a page with its filters can be pinned, and anything that isn't a path in this app can't", async () => {
const good = ["/servers", "/servers?status=offline", "/servers?q=elsa+running&sort=name&dir=desc&tag=back%C3%A5k"];
const res = await send("PUT", "/me/favorites", { paths: good });
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).favorites, good);
for (const bad of ["//evil.example", "https://evil.example/x", "/servers?q=<script>", "/servers?q=a b", "/servers?", "/servers?" + "a".repeat(161), "servers"]) {
assert.equal((await send("PUT", "/me/favorites", { paths: [bad] })).status, 400, bad);
}
const me = await (await send("GET", "/me")).json();
assert.deepEqual(me.user.favorites, good);
});
test("the dashboard layout is saved for the person, read back with them, and reset by sending nothing", async () => {
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: [], order: {} });
const layout = { hidden: ["Gitea", "Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } };
const res = await send("PUT", "/me/dashboard", layout);
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).dashboard, { hidden: ["Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } }, "a card named twice is hidden once");
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: ["Gitea", "osTicket"], order: { DNS: 1, Secrets: 0 } });
who = "viewer";
assert.deepEqual((await (await send("GET", "/me")).json()).user.dashboard, { hidden: [], order: {} }, "someone else's arrangement is theirs");
who = "admin";
await send("PUT", "/me/dashboard", { hidden: [], order: {} });
const [row] = await db.select().from(users).where(eq(users.oidcSub, "admin"));
assert.equal(row.dashboardLayout, null, "the default layout stores nothing");
});
test("a layout that isn't one is refused", async () => {
for (const bad of [
{ hidden: "Gitea", order: {} },
{ hidden: [], order: { DNS: 1.5 } },
{ hidden: [], order: { DNS: -1 } },
{ hidden: [], order: { DNS: 100000 } },
{ hidden: ["x".repeat(61)], order: {} },
{ hidden: new Array(61).fill("a").map((_, i) => `c${i}`), order: {} },
{},
]) {
assert.equal((await send("PUT", "/me/dashboard", bad)).status, 400, JSON.stringify(bad).slice(0, 60));
}
});
test("only an administrator can make, list or remove share links", async () => {
who = "viewer";
assert.equal((await send("GET", "/share-links")).status, 403);
assert.equal((await send("POST", "/share-links", { label: "TV", detail: "summary", expiresInDays: null })).status, 403);
assert.equal((await send("DELETE", "/share-links/1")).status, 403);
who = "admin";
});
let summaryToken = "";
let namesToken = "";
let namesId = 0;
test("a link is made once: the secret is in that answer and nowhere after", async () => {
const made = await send("POST", "/share-links", { label: "Hall TV", detail: "summary", expiresInDays: null });
assert.equal(made.status, 201);
const body = await made.json();
summaryToken = body.token;
assert.ok(summaryToken.length >= 30);
assert.equal(body.path, `/share/wall/${summaryToken}`);
assert.equal(body.link.label, "Hall TV");
const named = await (await send("POST", "/share-links", { label: "Rack screen", detail: "names", expiresInDays: 30 })).json();
namesToken = named.token;
namesId = named.link.id;
assert.ok(named.link.expiresAt);
const list = await (await send("GET", "/share-links")).json();
assert.equal(list.links.length, 2);
const text = JSON.stringify(list);
assert.ok(!text.includes(summaryToken) && !text.includes(namesToken), "the list never shows the secret");
assert.ok(!text.includes("tokenHash"), "or its hash");
const [stored] = await db.select().from(shareLinks).where(eq(shareLinks.id, body.link.id));
assert.notEqual(stored.tokenHash, summaryToken);
assert.equal(stored.tokenHash.length, 64);
const audits = (await db.select().from(auditLog)).filter((a) => a.category === "share_link");
assert.equal(audits.length, 2);
assert.ok(audits.every((a) => !(a.detail ?? "").includes(summaryToken) && !(a.detail ?? "").includes(namesToken)));
});
test("a bad request is refused", async () => {
for (const bad of [{ label: "", detail: "summary", expiresInDays: null }, { label: "x", detail: "everything", expiresInDays: null }, { label: "x", detail: "summary", expiresInDays: 0 }, { label: "x", detail: "summary", expiresInDays: 400 }, { label: "x", detail: "summary" }]) {
assert.equal((await send("POST", "/share-links", bad)).status, 400, JSON.stringify(bad));
}
});
test("the public wall needs no sign-in, and a summary link says how things are in numbers only", async () => {
who = "nobody-at-all"; // no such user: the public route must not care
after(() => {
who = "admin";
});
const res = await fetch(`${base}/public/wall/${summaryToken}`);
assert.equal(res.status, 200);
assert.equal(res.headers.get("cache-control"), "no-store");
assert.match(res.headers.get("x-robots-tag") ?? "", /noindex/);
const wall = await res.json();
assert.equal(wall.detail, "summary");
assert.equal(wall.servers.offline, 1);
assert.equal(wall.servers.online, 1);
assert.equal(wall.level, "critical");
assert.ok(wall.alerts.critical + wall.alerts.warning >= 1);
assert.equal(wall.problems, undefined);
assert.equal(wall.integrations, undefined);
assert.equal(wall.maintenanceWindows, undefined);
const text = JSON.stringify(wall);
for (const secret of ["elsa", "anna", "Gitea", "git.lab", "hash", "Old VPN token"]) assert.ok(!text.includes(secret), `a summary must not contain "${secret}"`);
assert.deepEqual(wall.display, { dateFormat: "ymd", timeFormat: "24h" });
who = "admin";
});
test("a names link adds what is wrong and what is in maintenance, but not addresses or settings", async () => {
const [anna] = await db.select().from(servers).where(eq(servers.name, "anna"));
await db.insert(maintenanceWindows).values({
targetType: "server",
targetId: anna.id,
reason: "secret reason text",
startedAt: new Date(Date.now() - 600_000).toISOString(),
endsAt: new Date(Date.now() + 3600_000).toISOString(),
createdBy: "Ada",
});
const wall = await (await fetch(`${base}/public/wall/${namesToken}`)).json();
assert.equal(wall.detail, "names");
assert.ok(wall.problems.some((p: { message: string }) => p.message.includes("Old VPN token")), JSON.stringify(wall.problems));
assert.deepEqual(wall.maintenanceWindows.map((w: { name: string }) => w.name), ["anna"]);
assert.equal(wall.maintenance, 1);
assert.deepEqual(wall.integrations, [], "a disabled integration isn't listed");
const text = JSON.stringify(wall);
for (const secret of ["git.lab", "secret reason text", "tokenHash", "apiToken"]) assert.ok(!text.includes(secret), `names must not contain "${secret}"`);
});
test("a link that never existed, ended, or was removed all answer the same", async () => {
const unknown = await fetch(`${base}/public/wall/${"x".repeat(32)}`);
assert.equal(unknown.status, 404);
const unknownBody = await unknown.text();
// ended
await db.update(shareLinks).set({ expiresAt: new Date(Date.now() - 1000).toISOString() }).where(eq(shareLinks.id, namesId));
const expired = await fetch(`${base}/public/wall/${namesToken}`);
assert.equal(expired.status, 404);
assert.equal(await expired.text(), unknownBody);
assert.equal((await (await send("GET", "/share-links")).json()).links.find((l: { id: number }) => l.id === namesId).expired, true);
// removed
assert.equal((await send("DELETE", `/share-links/${namesId}`)).status, 204);
const gone = await fetch(`${base}/public/wall/${namesToken}`);
assert.equal(gone.status, 404);
assert.equal(await gone.text(), unknownBody);
assert.equal((await send("DELETE", `/share-links/${namesId}`)).status, 404);
assert.equal((await fetch(`${base}/public/wall/short`)).status, 404);
// the other link carries on
assert.equal((await fetch(`${base}/public/wall/${summaryToken}`)).status, 200);
});
test("using a link is noted, and removal is in the audit log without the secret", async () => {
const [link] = await db.select().from(shareLinks);
assert.ok(link.lastUsedAt, "the summary link was opened above");
const audits = (await db.select().from(auditLog)).filter((a) => a.category === "share_link" && a.action === "delete");
assert.equal(audits.length, 1);
assert.match(audits[0].detail ?? "", /Rack screen/);
});
test("there is a limit to how many links there can be", async () => {
let made = (await db.select().from(shareLinks)).length;
while (made < 20) {
assert.equal((await send("POST", "/share-links", { label: `Link ${made}`, detail: "summary", expiresInDays: 1 })).status, 201);
made++;
}
const over = await send("POST", "/share-links", { label: "One too many", detail: "summary", expiresInDays: 1 });
assert.equal(over.status, 400);
assert.equal((await over.json()).error, "too_many");
});
});