- Speedtest Tracker integration: charts, alerts for a slow line (median of the last three tests under a share of what is paid for) and for failing tests. - Costs page (Records): things paid for by hand plus Hetzner's estimate, totals per currency, bills rolled forward into Coming up as Renewals. - Status pages: a "Having trouble" state for things that answer but have an open alert; Speedtest reads as the internet. - Integrations page and kind picker grouped like the sidebar (one shared types file); Notifications "What to send" shown one group at a time; Dashboard integration sections follow the menu groups, with tiles for integrations that have no widget. - Docs, tests, and ROLES.md menu table brought up to date. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
427 lines
26 KiB
TypeScript
427 lines
26 KiB
TypeScript
/**
|
|
* 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();
|
|
|
|
// The alerts the page sees: none, unless a test says so (the real collector asks every integration, which is not what these tests are about).
|
|
type TestAlert = { id: string; severity: "critical" | "warning" | "info"; silenced: boolean; target: { type: "server" | "integration"; id: number; name: string } | null };
|
|
let testAlerts: TestAlert[] = [];
|
|
sp.setAlertsLoaderForTests(async () => testAlerts as never);
|
|
|
|
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, trouble = 0) => ({ up, trouble, down, maintenance, unknown });
|
|
test("anything down is a problem; then anything having trouble; then anything being worked on; 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, 1, 0, 0, 2)), "issue", "down outranks trouble");
|
|
assert.equal(sp.pageLevel(c(4, 0, 1, 0, 1)), "trouble", "trouble outranks being worked on");
|
|
assert.equal(sp.pageLevel(c(0, 0, 0, 0, 2)), "trouble");
|
|
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, trouble: 0, 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);
|
|
});
|
|
|
|
describe("having trouble: it answers, but something is not right", () => {
|
|
const alert = (target: TestAlert["target"], extra: Partial<TestAlert> = {}): TestAlert => ({ id: `services:x:${Math.random()}`, severity: "warning", silenced: false, target, ...extra });
|
|
const server = (id: number) => ({ type: "server" as const, id, name: "private server name" });
|
|
const integration = (id: number) => ({ type: "integration" as const, id, name: "private integration name" });
|
|
const read = async () => stateOf(await sp.buildPublicStatus(link, NOW));
|
|
after(() => {
|
|
testAlerts = [];
|
|
});
|
|
|
|
test("a server that reports, with a warning or critical alert nobody has put aside, is having trouble; a server that is down stays down", async () => {
|
|
testAlerts = [alert(server(ids.up), { severity: "critical" }), alert(server(ids.down))];
|
|
const s = await read();
|
|
assert.equal(s.Files, "trouble");
|
|
assert.equal(s.Backups, "down", "down outranks trouble");
|
|
testAlerts = [alert(server(ids.up))];
|
|
assert.equal((await read()).Files, "trouble");
|
|
});
|
|
|
|
test("an alert that is silenced (maintenance, snoozed, closed), only information, or about something else says nothing", async () => {
|
|
testAlerts = [alert(server(ids.up), { silenced: true }), alert(server(ids.up), { severity: "info" }), alert(server(ids.never)), alert(null), alert({ type: "integration", id: ids.up, name: "x" })];
|
|
assert.equal((await read()).Files, "up", "an integration with the server's number is not the server");
|
|
});
|
|
|
|
test("an integration that works, with an alert open, is having trouble; one that fails is down; one under maintenance is being worked on", async () => {
|
|
testAlerts = [alert(integration(sem))];
|
|
assert.equal((await read()).Automation, "trouble");
|
|
await trackIntegrationHealth("semaphore", false);
|
|
assert.equal((await read()).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() });
|
|
assert.equal((await read()).Automation, "maintenance");
|
|
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.targetId, sem));
|
|
});
|
|
|
|
test("the internet, through Speedtest Tracker: slow is trouble, speed tests that keep failing is down, fine is up", async () => {
|
|
const st = (await db.insert(integrations).values({ type: "speedtest", name: "Line", baseUrl: "http://x", config: "{}", enabled: true }).returning())[0].id;
|
|
await trackIntegrationHealth("speedtest", true);
|
|
await sp.setStatusItems(linkId, [...(await sp.getStatusItems(linkId)).map((i) => ({ label: i.label, kind: i.kind, targetId: i.targetId, monitorId: i.monitorId })), { label: "Internet", kind: "integration", targetId: st }]);
|
|
testAlerts = [];
|
|
assert.equal((await read()).Internet, "up");
|
|
testAlerts = [alert(integration(st), { id: `monitoring:speedtest-slow:${st}` })];
|
|
assert.equal((await read()).Internet, "trouble");
|
|
testAlerts = [alert(integration(st), { id: `monitoring:speedtest-failing:${st}` })];
|
|
assert.equal((await read()).Internet, "down");
|
|
testAlerts = [];
|
|
});
|
|
|
|
test("the page says how many are in trouble and reads as trouble when nothing is down; and no alert text, name or id reaches the public", async () => {
|
|
await sp.setStatusItems(linkId, (await sp.getStatusItems(linkId)).filter((i) => ["Files", "Automation", "Movies"].includes(i.label)).map((i) => ({ label: i.label, kind: i.kind, targetId: i.targetId, monitorId: i.monitorId })));
|
|
testAlerts = [alert(server(ids.up), { id: "services:secret-alert-id" })];
|
|
const page = await sp.buildPublicStatus(link, NOW);
|
|
assert.deepEqual(page.counts, { up: 2, trouble: 1, down: 0, maintenance: 0, unknown: 0 });
|
|
assert.equal(page.level, "trouble");
|
|
const text = JSON.stringify(page);
|
|
for (const secret of ["private server name", "secret-alert-id", "private integration name"]) assert.ok(!text.includes(secret), secret);
|
|
testAlerts = [];
|
|
});
|
|
|
|
test("alerts that cannot be read say nothing is in trouble, and the page still works", async () => {
|
|
sp.setAlertsLoaderForTests(async () => {
|
|
throw new Error("alerts are down");
|
|
});
|
|
assert.equal((await read()).Files, "up");
|
|
sp.setAlertsLoaderForTests(async () => testAlerts as never);
|
|
});
|
|
});
|
|
|
|
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");
|
|
});
|
|
});
|