Add status pages (a share link kind) and a downloadable Grafana dashboard

- Share links can open a status page: an admin picks servers, integrations and Uptime Kuma
  monitors and names them; the public sees only those names, Working / Not working /
  Being worked on / Can't tell, an optional message and the 30-day figure (share_links.kind/
  title/message and status_items, migration 0033). A status address doesn't open the wall and
  the other way round; Uptime Kuma is asked at most every 30 seconds
- Grafana dashboard built from code (download in Settings -> API and webhooks); a test checks
  it only uses series /metrics serves
- Tests and docs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-18 15:38:08 +02:00
1 parent 2744a84719
commit 5cc51c57de
24 files changed
+4880 -35

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
/**
* The Grafana dashboard: that it is a dashboard Grafana will import, that every panel sits on the grid, and — the point of building it
* here — that it only asks for series `/metrics` really serves, so renaming one can't quietly blank a panel.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-grafana-"));
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 } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { buildGrafanaDashboard } = await import("../src/services/grafanaDashboard.js");
const { metricsTokensRouter } = await import("../src/routes/metrics.js");
await runMigrations();
type Panel = { id: number; type: string; title: string; gridPos: { h: number; w: number; x: number; y: number }; targets?: { expr: string; legendFormat: string; refId: string; datasource: { uid: string } }[]; datasource?: { uid: string } };
const dashboard = buildGrafanaDashboard() as { panels: Panel[]; templating: { list: { name: string }[] }; __inputs: { name: string }[]; uid: string; title: string; schemaVersion: number };
const panels = dashboard.panels;
const withQueries = panels.filter((p) => p.targets);
const exprs = withQueries.flatMap((p) => p.targets!.map((t) => t.expr));
// What /metrics can serve: every series the code that builds it adds.
const here = dirname(fileURLToPath(import.meta.url));
const served = new Set([...readFileSync(join(here, "..", "src", "services", "metrics.ts"), "utf8").matchAll(/out\.add\(\s*"(homelab_[a-z0-9_]+)"/g)].map((m) => m[1]));
describe("the dashboard is one Grafana will import", () => {
test("it has a title, a fixed id, asks which Prometheus to use, and every query uses that choice", () => {
assert.equal(dashboard.title, "Homelab Manager");
assert.equal(dashboard.uid, "homelab-manager");
assert.ok(dashboard.schemaVersion >= 36);
assert.deepEqual(dashboard.__inputs.map((i) => i.name), ["DS_PROMETHEUS"]);
for (const p of withQueries) {
assert.equal(p.datasource?.uid, "${DS_PROMETHEUS}", p.title);
for (const t of p.targets!) assert.equal(t.datasource.uid, "${DS_PROMETHEUS}", `${p.title} / ${t.refId}`);
}
});
test("it survives being written out and read back, as an import does", () => {
const again = JSON.parse(JSON.stringify(dashboard));
assert.equal(again.panels.length, panels.length);
assert.ok(panels.length >= 30, `${panels.length} panels`);
});
test("every panel has an id of its own, a title, and sits on the 24-column grid without overlapping another", () => {
assert.equal(new Set(panels.map((p) => p.id)).size, panels.length, "ids are unique");
for (const p of panels) {
assert.ok(p.title, `panel ${p.id} has no title`);
const g = p.gridPos;
assert.ok(g.x >= 0 && g.w >= 1 && g.x + g.w <= 24, `${p.title} sits outside the grid: ${JSON.stringify(g)}`);
assert.ok(g.h >= 1 && g.y >= 0);
}
for (let i = 0; i < panels.length; i++) {
for (let j = i + 1; j < panels.length; j++) {
const a = panels[i].gridPos;
const b = panels[j].gridPos;
const overlap = a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
assert.equal(overlap, false, `${panels[i].title} overlaps ${panels[j].title}`);
}
}
});
test("it is in rows, and the rows come in a sensible order", () => {
const rows = panels.filter((p) => p.type === "row").map((p) => p.title);
assert.deepEqual(rows, ["Needs attention", "Servers", "Disks", "Backups", "Secrets, power and the app itself"]);
const ys = panels.filter((p) => p.type === "row").map((p) => p.gridPos.y);
assert.deepEqual([...ys].sort((a, b) => a - b), ys, "top to bottom");
});
});
describe("what it asks for", () => {
test("it asks only for series /metrics serves (and says so if one is renamed)", () => {
assert.ok(served.size >= 30, `found ${served.size} served series in metrics.ts`);
const asked = new Set(exprs.flatMap((e) => e.match(/\bhomelab_[a-z0-9_]+\b/g) ?? []));
assert.ok(asked.size >= 25, `the dashboard uses ${asked.size} series`);
const missing = [...asked].filter((m) => !served.has(m));
assert.deepEqual(missing, [], `series the dashboard uses that /metrics doesn't serve: ${missing.join(", ")}`);
});
test("the big groups of series are all covered", () => {
const asked = new Set(exprs.flatMap((e) => e.match(/\bhomelab_[a-z0-9_]+\b/g) ?? []));
for (const m of [
"homelab_alerts", "homelab_incidents_open", "homelab_server_up", "homelab_server_disk_used_percent", "homelab_server_disk_days_to_full", "homelab_server_disk_healthy",
"homelab_server_zfs_pool_online", "homelab_backup_guests", "homelab_backup_last_age_seconds", "homelab_selfbackup_last_success_timestamp_seconds", "homelab_secret_expiry_days",
"homelab_integration_up", "homelab_server_uptime_ratio_30d", "homelab_server_pending_updates",
]) assert.ok(asked.has(m), `${m} has no panel`);
});
test("each query is well-formed: not empty, brackets and quotes balanced, no stray template text", () => {
for (const p of withQueries) {
for (const t of p.targets!) {
const e = t.expr;
assert.ok(e.trim().length > 0, `${p.title}: empty query`);
for (const [open, close] of [["(", ")"], ["{", "}"], ["[", "]"]]) assert.equal(e.split(open).length, e.split(close).length, `${p.title}: unbalanced ${open}${close} in ${e}`);
assert.equal(e.split('"').length % 2, 1, `${p.title}: an unclosed quote in ${e}`);
assert.doesNotMatch(e, /undefined|\[object/, `${p.title}: ${e}`);
}
}
});
test("the server picker exists, takes its values from the series, and everything that uses it is told how", () => {
const names = dashboard.templating.list.map((v) => v.name);
assert.deepEqual(names, ["server"]);
const variable = dashboard.templating.list[0] as unknown as { query: { query: string }; allValue: string; multi: boolean };
assert.equal(variable.query.query, "label_values(homelab_server_up, server)");
assert.equal(variable.multi, true);
assert.equal(variable.allValue, ".+", "all servers, including ones with no label at all, matches");
const using = exprs.filter((e) => e.includes("$server"));
assert.ok(using.length >= 10);
for (const e of using) assert.match(e, /\{server=~"\$server"\}/);
});
test("series that exist only once something happens use 'or vector(0)' where a stat would otherwise read 'No data'", () => {
for (const title of ["Critical alerts", "Warnings", "Servers down", "Integrations failing", "Servers up"]) {
const p = withQueries.find((x) => x.title === title)!;
assert.match(p.targets![0].expr, /or vector\(0\)/, title);
}
});
});
describe("downloading it", () => {
let app: Server;
let base = "";
let who = "ada";
before(async () => {
await db.insert(users).values([
{ oidcSub: "ada", name: "Ada", role: "admin" },
{ oidcSub: "olle", name: "Olle", role: "operator" },
]);
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/metrics-tokens", metricsTokensRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/metrics-tokens`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("an administrator gets it as a file; nobody else does", async () => {
who = "olle";
assert.equal((await fetch(`${base}/grafana-dashboard.json`)).status, 403);
who = "ada";
const res = await fetch(`${base}/grafana-dashboard.json`);
assert.equal(res.status, 200);
assert.match(res.headers.get("content-disposition") ?? "", /attachment; filename="homelab-manager-dashboard\.json"/);
assert.match(res.headers.get("content-type") ?? "", /application\/json/);
const body = await res.json();
assert.equal(body.uid, "homelab-manager");
assert.equal(body.panels.length, panels.length);
});
});
+351
View File
@@ -0,0 +1,351 @@
/**
* The status page behind a share link: what can be put on it, how each thing reads, what the public is and isn't given, and that a status
* page's address and a wall's address each open only their own.
*
* 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-statuspage-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, shareLinks, statusItems, maintenanceWindows, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { createShareLink } = await import("../src/services/shareLinks.js");
const sp = await import("../src/services/statusPage.js");
const { trackIntegrationHealth } = await import("../src/services/integrationHealthMonitor.js");
const { shareLinksRouter } = await import("../src/routes/shareLinks.js");
const { publicStatusRouter } = await import("../src/routes/publicStatus.js");
const { publicWallRouter } = await import("../src/routes/publicWall.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const NOW = new Date("2026-10-17T12:00:00.000Z");
const minutesAgo = (m: number) => new Date(NOW.getTime() - m * 60_000).toISOString();
describe("how the whole page reads", () => {
const c = (up: number, down: number, maintenance: number, unknown: number) => ({ up, down, maintenance, unknown });
test("anything down is a problem; otherwise anything being worked on says so; nothing known at all is unknown", () => {
assert.equal(sp.pageLevel(c(5, 0, 0, 0)), "ok");
assert.equal(sp.pageLevel(c(4, 1, 1, 1)), "issue");
assert.equal(sp.pageLevel(c(4, 0, 1, 1)), "maintenance");
assert.equal(sp.pageLevel(c(4, 0, 0, 1)), "ok", "one thing that can't be told doesn't spoil the rest");
assert.equal(sp.pageLevel(c(0, 0, 0, 3)), "unknown");
assert.equal(sp.pageLevel(c(0, 0, 0, 0)), "ok", "an empty page isn't alarming");
});
});
describe("what can be put on it", () => {
let linkId = 0;
let serverId = 0;
let kumaId = 0;
let semId = 0;
before(async () => {
const { link } = await createShareLink({ label: "Family", detail: "summary", kind: "status", expiresInDays: null, createdBy: "Ada" });
linkId = link.id;
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: "x", apiTokenPrefix: "x", lastSeenAt: minutesAgo(1) }).returning();
serverId = s.id;
const [k] = await db.insert(integrations).values({ type: "uptimekuma", name: "Kuma", baseUrl: "https://kuma.lab", config: "{}", enabled: false }).returning();
kumaId = k.id;
const [m] = await db.insert(integrations).values({ type: "semaphore", name: "Semaphore", baseUrl: "https://sem.lab", config: "{}", enabled: false }).returning();
semId = m.id;
});
const rejects = (items: Parameters<typeof sp.setStatusItems>[1], code: string) => assert.rejects(sp.setStatusItems(linkId, items), (e: unknown) => e instanceof sp.StatusPageError && e.code === code, code);
test("a server, an integration and a monitor, in the order given, each with its own name; saving again replaces the list", async () => {
await sp.setStatusItems(linkId, [
{ label: " Movies ", kind: "monitor", targetId: kumaId, monitorId: "12" },
{ label: "Files", kind: "server", targetId: serverId },
{ label: "Automation", kind: "integration", targetId: semId },
]);
const items = await sp.getStatusItems(linkId);
assert.deepEqual(items.map((i) => [i.label, i.kind, i.targetName, i.monitorId]), [["Movies", "monitor", "Kuma", "12"], ["Files", "server", "elsa", null], ["Automation", "integration", "Semaphore", null]]);
await sp.setStatusItems(linkId, [{ label: "Just files", kind: "server", targetId: serverId }]);
assert.deepEqual((await sp.getStatusItems(linkId)).map((i) => i.label), ["Just files"]);
await sp.setStatusItems(linkId, []);
assert.deepEqual(await sp.getStatusItems(linkId), []);
});
test("what doesn't exist, or isn't what it says, is refused with a reason — and nothing changes", async () => {
await sp.setStatusItems(linkId, [{ label: "Keep me", kind: "server", targetId: serverId }]);
await rejects([{ label: "Ghost", kind: "server", targetId: 99999 }], "unknown_target");
await rejects([{ label: "Ghost", kind: "integration", targetId: 99999 }], "unknown_target");
await rejects([{ label: "Monitor on the wrong thing", kind: "monitor", targetId: semId, monitorId: "1" }], "unknown_target");
await rejects([{ label: "No monitor", kind: "monitor", targetId: kumaId }], "invalid_monitor");
await rejects([{ label: "No monitor", kind: "monitor", targetId: kumaId, monitorId: "x".repeat(101) }], "invalid_monitor");
await rejects([{ label: " ", kind: "server", targetId: serverId }], "invalid_label");
await rejects([{ label: "x".repeat(sp.MAX_LABEL + 1), kind: "server", targetId: serverId }], "invalid_label");
await rejects(Array.from({ length: sp.MAX_ITEMS + 1 }, (_, i) => ({ label: `n${i}`, kind: "server" as const, targetId: serverId })), "too_many");
assert.deepEqual((await sp.getStatusItems(linkId)).map((i) => i.label), ["Keep me"], "the list is as it was");
});
});
describe("how each thing reads", () => {
let linkId = 0;
let link: Awaited<ReturnType<typeof createShareLink>>["link"];
let kumaId = 0;
let sem = 0;
const ids: Record<string, number> = {};
const monitor = (id: string, status: string, uptime30d: number | null = 99.123) => ({ id, name: `private name ${id}`, type: "http", target: "10.1.2.3", port: 443, status, responseTimeMs: 5, certDaysRemaining: null, uptime24h: 100, uptime30d, uptime1y: 100 }) as never;
before(async () => {
({ link } = await createShareLink({ label: "Family", detail: "summary", kind: "status", title: " Our home ", message: " Movies are being updated tonight. ", expiresInDays: null, createdBy: "Ada" }));
linkId = link.id;
const mk = async (name: string, extra: Partial<typeof servers.$inferInsert> = {}) => (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: "x", ...extra }).returning())[0].id;
ids.up = await mk("up", { lastSeenAt: minutesAgo(5) });
ids.down = await mk("down", { lastSeenAt: minutesAgo(180) });
ids.never = await mk("never");
ids.worked = await mk("worked", { lastSeenAt: minutesAgo(180) });
ids.laptop = await mk("laptop", { lastSeenAt: minutesAgo(180), thresholds: JSON.stringify({ serverOfflineMinutes: 600 }) });
await db.insert(maintenanceWindows).values({ targetType: "server", targetId: ids.worked, reason: "x", startedAt: minutesAgo(30), endsAt: new Date(NOW.getTime() + 3600_000).toISOString() });
kumaId = (await db.insert(integrations).values({ type: "uptimekuma", name: "Kuma", baseUrl: "https://kuma.lab", config: "{}", enabled: true }).returning())[0].id;
sem = (await db.insert(integrations).values({ type: "semaphore", name: "Semaphore", baseUrl: "https://sem.lab", config: "{}", enabled: true }).returning())[0].id;
await trackIntegrationHealth("semaphore", true);
await sp.setStatusItems(linkId, [
{ label: "Files", kind: "server", targetId: ids.up },
{ label: "Backups", kind: "server", targetId: ids.down },
{ label: "Printer", kind: "server", targetId: ids.never },
{ label: "Photos", kind: "server", targetId: ids.worked },
{ label: "Laptop", kind: "server", targetId: ids.laptop },
{ label: "Automation", kind: "integration", targetId: sem },
{ label: "Movies", kind: "monitor", targetId: kumaId, monitorId: "m-up" },
{ label: "Music", kind: "monitor", targetId: kumaId, monitorId: "m-down" },
{ label: "Podcasts", kind: "monitor", targetId: kumaId, monitorId: "m-maint" },
{ label: "Books", kind: "monitor", targetId: kumaId, monitorId: "m-pending" },
{ label: "Gone", kind: "monitor", targetId: kumaId, monitorId: "m-missing" },
]);
sp.setKumaLoaderForTests(async () => [monitor("m-up", "up"), monitor("m-down", "down", 80.04), monitor("m-maint", "maintenance"), monitor("m-pending", "pending", null)]);
});
after(() => sp.setKumaLoaderForTests(null));
const stateOf = (page: Awaited<ReturnType<typeof sp.buildPublicStatus>>) => Object.fromEntries(page.items.map((i) => [i.label, i.state]));
test("a server is up if it reported lately, down if not, unknown if it never has, and 'being worked on' during maintenance — whatever it is doing", async () => {
const page = await sp.buildPublicStatus(link, NOW);
const s = stateOf(page);
assert.equal(s.Files, "up");
assert.equal(s.Backups, "down");
assert.equal(s.Printer, "unknown");
assert.equal(s.Photos, "maintenance", "quiet for three hours, but it is under a maintenance window");
assert.equal(s.Laptop, "up", "its own limit of ten hours applies");
});
test("an integration is up while its calls work", async () => {
assert.equal(stateOf(await sp.buildPublicStatus(link, NOW)).Automation, "up");
await trackIntegrationHealth("semaphore", false);
assert.equal(stateOf(await sp.buildPublicStatus(link, NOW)).Automation, "down");
await trackIntegrationHealth("semaphore", true);
await db.insert(maintenanceWindows).values({ targetType: "integration", targetId: sem, reason: "x", startedAt: minutesAgo(10), endsAt: new Date(NOW.getTime() + 3600_000).toISOString() });
await trackIntegrationHealth("semaphore", false);
assert.equal(stateOf(await sp.buildPublicStatus(link, NOW)).Automation, "maintenance");
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.targetId, sem));
await trackIntegrationHealth("semaphore", true);
});
test("a monitor reads as Uptime Kuma says; one that is checking, or is gone, can't be told — never 'up'", async () => {
const s = stateOf(await sp.buildPublicStatus(link, NOW));
assert.equal(s.Movies, "up");
assert.equal(s.Music, "down");
assert.equal(s.Podcasts, "maintenance");
assert.equal(s.Books, "unknown");
assert.equal(s.Gone, "unknown");
});
test("when Uptime Kuma can't be reached its monitors can't be told, and the rest of the page still works", async () => {
sp.setKumaLoaderForTests(async () => {
throw new Error("connection refused");
});
const page = await sp.buildPublicStatus(link, NOW);
const s = stateOf(page);
assert.equal(s.Movies, "unknown");
assert.equal(s.Music, "unknown");
assert.equal(s.Files, "up");
sp.setKumaLoaderForTests(async () => [monitor("m-up", "up"), monitor("m-down", "down", 80.04), monitor("m-maint", "maintenance"), monitor("m-pending", "pending", null)]);
});
test("Uptime Kuma is asked once in a while, not on every look at the page", async () => {
let asked = 0;
sp.setKumaLoaderForTests(async () => {
asked++;
return [monitor("m-up", "up")];
});
await sp.buildPublicStatus(link, NOW);
await sp.buildPublicStatus(link, new Date(NOW.getTime() + 5_000));
await sp.buildPublicStatus(link, new Date(NOW.getTime() + 10_000));
assert.equal(asked, 1);
sp.setKumaLoaderForTests(async () => [monitor("m-up", "up"), monitor("m-down", "down", 80.04), monitor("m-maint", "maintenance"), monitor("m-pending", "pending", null)]);
});
test("the page has its title and message, the counts, and the overall reading", async () => {
const page = await sp.buildPublicStatus(link, NOW);
assert.equal(page.title, "Our home");
assert.equal(page.message, "Movies are being updated tonight.");
assert.deepEqual(page.counts, { up: 4, down: 2, maintenance: 2, unknown: 3 });
assert.equal(page.level, "issue");
assert.deepEqual(page.items.map((i) => i.label), ["Files", "Backups", "Printer", "Photos", "Laptop", "Automation", "Movies", "Music", "Podcasts", "Books", "Gone"], "in the order they were put");
assert.equal(page.items.find((i) => i.label === "Music")!.uptime30d, 80, "30-day uptime from Uptime Kuma, to one decimal");
assert.equal(page.items.find((i) => i.label === "Books")!.uptime30d, null);
// with no title the link's own name is used, and no message is none
const bare = await sp.buildPublicStatus({ ...link, title: null, message: " " }, NOW);
assert.equal(bare.title, "Family");
assert.equal(bare.message, null);
});
test("the public is given names and states and nothing else", async () => {
const text = JSON.stringify(await sp.buildPublicStatus(link, NOW));
for (const secret of ["10.1.2.3", "kuma.lab", "sem.lab", "private name", "m-up", "apiToken", "elsa", "tok"]) assert.ok(!text.includes(secret), `the page leaks "${secret}"`);
assert.deepEqual(Object.keys(JSON.parse(text)).sort(), ["counts", "display", "generatedAt", "items", "level", "message", "title"]);
assert.deepEqual(Object.keys(JSON.parse(text).items[0]).sort(), ["id", "label", "state", "uptime30d"]);
});
test("a page with nothing on it is a page, not an error", async () => {
const { link: empty } = await createShareLink({ label: "Empty", detail: "summary", kind: "status", expiresInDays: null, createdBy: "Ada" });
const page = await sp.buildPublicStatus(empty, NOW);
assert.deepEqual(page.items, []);
assert.equal(page.level, "ok");
});
});
describe("through the routes", () => {
let app: Server;
let base = "";
let who = "ada";
let statusToken = "";
let statusLinkId = 0;
let wallToken = "";
let serverId = 0;
const call = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
before(async () => {
await db.insert(users).values([
{ oidcSub: "ada", name: "Ada", role: "admin" },
{ oidcSub: "olle", name: "Olle", role: "operator" },
]);
serverId = (await db.insert(servers).values({ name: "plexbox", apiTokenHash: "p", apiTokenPrefix: "p", lastSeenAt: new Date().toISOString() }).returning())[0].id;
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/share-links", shareLinksRouter);
a.use("/api/public/status", publicStatusRouter);
a.use("/api/public/wall", publicWallRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
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.
}
});
test("only an administrator makes a status page; its address is under /share/status and shown once", async () => {
who = "olle";
assert.equal((await call("POST", "/share-links", { label: "x", kind: "status", expiresInDays: null })).status, 403);
assert.equal((await call("GET", "/share-links/status-choices")).status, 403);
who = "ada";
const res = await call("POST", "/share-links", { label: "Family", kind: "status", title: "Our home", message: "Hello", expiresInDays: null });
assert.equal(res.status, 201);
const body = await res.json();
assert.match(body.path, /^\/share\/status\/[A-Za-z0-9_-]{20,}$/);
statusToken = body.path.split("/").pop();
statusLinkId = body.link.id;
assert.equal(body.link.kind, "status");
assert.equal(body.link.title, "Our home");
const wall = await (await call("POST", "/share-links", { label: "Hall TV", expiresInDays: null })).json();
assert.match(wall.path, /^\/share\/wall\//, "a link made the old way is still a wall");
assert.equal(wall.link.kind, "wall");
wallToken = wall.path.split("/").pop();
const list = await (await call("GET", "/share-links")).json();
const mine = list.links.filter((l: { id: number }) => l.id === statusLinkId || l.id === wall.link.id);
assert.deepEqual(mine.map((l: { kind: string; itemCount: number }) => [l.kind, l.itemCount]), [["status", 0], ["wall", 0]]);
assert.ok(!JSON.stringify(list).includes(statusToken), "the secret is not in the list");
});
test("the editor reads and saves the page; a wall has no such page", async () => {
const choices = await (await call("GET", "/share-links/status-choices")).json();
assert.ok(choices.servers.some((s: { name: string }) => s.name === "plexbox"), "the servers to choose from");
assert.ok(Array.isArray(choices.integrations));
const before = await (await call("GET", `/share-links/${statusLinkId}/status`)).json();
assert.deepEqual(before, { title: "Our home", message: "Hello", items: [], maxItems: 30 });
const saved = await call("PUT", `/share-links/${statusLinkId}/status`, { title: "Our home network", message: "", items: [{ label: "Movies", kind: "server", targetId: serverId }] });
assert.equal(saved.status, 200);
const out = await saved.json();
assert.equal(out.items[0].label, "Movies");
assert.equal(out.items[0].targetName, "plexbox");
assert.equal((await (await call("GET", `/share-links/${statusLinkId}/status`)).json()).title, "Our home network");
assert.equal((await (await call("GET", "/share-links")).json()).links.find((l: { id: number }) => l.id === statusLinkId).itemCount, 1);
const bad = await call("PUT", `/share-links/${statusLinkId}/status`, { title: "x", message: "", items: [{ label: "Ghost", kind: "server", targetId: 99999 }] });
assert.equal(bad.status, 400);
assert.match((await bad.json()).message, /server that doesn't exist/);
assert.equal((await (await call("GET", `/share-links/${statusLinkId}/status`)).json()).items.length, 1, "nothing changed");
assert.equal((await call("PUT", `/share-links/${statusLinkId}/status`, { title: "x" })).status, 400);
const wallId = (await (await call("GET", "/share-links")).json()).links.find((l: { kind: string }) => l.kind === "wall").id;
assert.equal((await call("GET", `/share-links/${wallId}/status`)).status, 404);
assert.equal((await call("PUT", `/share-links/${wallId}/status`, { title: "", message: "", items: [] })).status, 404);
assert.equal((await call("GET", "/share-links/x/status")).status, 400);
who = "olle";
assert.equal((await call("PUT", `/share-links/${statusLinkId}/status`, { title: "", message: "", items: [] })).status, 403);
who = "ada";
const entry = (await db.select().from(auditLog)).filter((e) => e.action === "update_status_page").pop()!;
assert.deepEqual(JSON.parse(entry.detail!).items, ["Movies"]);
});
test("anyone with the address can read the page — no sign-in — and it is never cached or indexed", async () => {
who = "nobody-signed-in";
const res = await call("GET", `/public/status/${statusToken}`);
assert.equal(res.status, 200);
assert.equal(res.headers.get("cache-control"), "no-store");
assert.match(res.headers.get("x-robots-tag") ?? "", /noindex/);
const page = await res.json();
assert.equal(page.title, "Our home network");
assert.deepEqual(page.items.map((i: { label: string; state: string }) => [i.label, i.state]), [["Movies", "up"]]);
assert.equal(page.level, "ok");
assert.ok(!JSON.stringify(page).includes("plexbox"));
who = "ada";
});
test("each address opens only its own kind of page; a link that doesn't work says the same thing however it doesn't", async () => {
const asStatusOnWall = await call("GET", `/public/wall/${statusToken}`);
assert.equal(asStatusOnWall.status, 404);
const asWallOnStatus = await call("GET", `/public/status/${wallToken}`);
assert.equal(asWallOnStatus.status, 404);
const never = await call("GET", `/public/status/${"z".repeat(32)}`);
assert.equal(never.status, 404);
assert.deepEqual(await asWallOnStatus.json(), await never.json(), "no way to tell a wall's address from one that never existed");
assert.equal((await call("GET", "/public/status/short")).status, 404);
assert.equal((await call("GET", `/public/wall/${wallToken}`)).status, 200, "and the wall still opens its own");
});
test("a link that has ended, or been removed, stops working; its list goes with it", async () => {
await db.update(shareLinks).set({ expiresAt: new Date(Date.now() - 1000).toISOString() }).where(eq(shareLinks.id, statusLinkId));
assert.equal((await call("GET", `/public/status/${statusToken}`)).status, 404, "ended");
await db.update(shareLinks).set({ expiresAt: null }).where(eq(shareLinks.id, statusLinkId));
assert.equal((await call("GET", `/public/status/${statusToken}`)).status, 200);
assert.equal((await call("DELETE", `/share-links/${statusLinkId}`)).status, 204);
assert.equal((await call("GET", `/public/status/${statusToken}`)).status, 404, "removed");
assert.equal((await db.select().from(statusItems).where(eq(statusItems.linkId, statusLinkId))).length, 0, "its things are gone with it");
});
});