/** * Named wall displays: the address made from a name, which pages a display rotates through and in what order, how fast (and who wins: the address, the display, or the browser), the admin routes, the share * link that opens one, and what the public board is told. * * 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-walls-")); 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, shareLinks, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const W = await import("../src/services/wallDisplays.js"); const { createShareLink } = await import("../src/services/shareLinks.js"); const { wallDisplaysRouter } = await import("../src/routes/wallDisplays.js"); const { shareLinksRouter } = await import("../src/routes/shareLinks.js"); const { publicWallRouter } = await import("../src/routes/publicWall.js"); const { describeChange } = await import("../src/services/changeLog.js"); const P = await import("../../web/src/utils/wallPages.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); describe("the address", () => { test("a name becomes an address of lower case letters, digits and single hyphens; Swedish letters are folded", () => { assert.equal(W.slugOf("Hall TV"), "hall-tv"); assert.equal(W.slugOf(" Office monitor (upstairs)! "), "office-monitor-upstairs"); assert.equal(W.slugOf("Köket & Vardagsrummet"), "koket-vardagsrummet"); assert.equal(W.slugOf("Åke"), "ake"); assert.equal(W.slugOf("!!!"), "display", "nothing to make one from"); assert.ok(W.slugOf("x".repeat(100)).length <= W.MAX_SLUG); for (const s of [W.slugOf("Hall TV"), W.slugOf("Köket"), W.slugOf("a b")]) assert.match(s, W.SLUG); }); test("one that is taken gets a number", () => { assert.equal(W.freeSlug("hall-tv", []), "hall-tv"); assert.equal(W.freeSlug("hall-tv", ["hall-tv"]), "hall-tv-2"); assert.equal(W.freeSlug("hall-tv", ["hall-tv", "hall-tv-2", "hall-tv-3"]), "hall-tv-4"); assert.ok(W.freeSlug("y".repeat(40), ["y".repeat(40)]).length <= W.MAX_SLUG); }); test("a stored list of pages is read back as ids of pages that exist, once each; anything else is none", () => { assert.deepEqual(W.parsePages(JSON.stringify(["overview", "group:apps", "overview", "bogus", 5, "group:Bad"])), ["overview", "group:apps"]); for (const odd of [null, undefined, "", "{", "{}", '"overview"']) assert.deepEqual(W.parsePages(odd as string), []); }); }); describe("what a display shows, and how fast", () => { const board: import("../../web/src/utils/wallPages.js").WallPage[] = [ { id: "overview", label: "Overview", kind: "overview" }, { id: "alerts", label: "Needs attention", kind: "alerts" }, { id: "group:apps", label: "Apps", kind: "group", groupId: "apps" }, { id: "group:network", label: "Network", kind: "group", groupId: "network" }, ]; test("the pages it lists, in its order, that the board has now; none listed is every page", () => { assert.deepEqual(P.applyDisplay(board, []).map((p) => p.id), ["overview", "alerts", "group:apps", "group:network"]); assert.deepEqual(P.applyDisplay(board, ["group:network", "overview"]).map((p) => p.id), ["group:network", "overview"], "its order, not the board's"); assert.deepEqual(P.applyDisplay(board, ["overview", "overview", "group:apps"]).map((p) => p.id), ["overview", "group:apps"]); }); test("a page the board has not got just now is left out, and a display with none of its pages shows the overview", () => { const quiet = board.filter((p) => p.id !== "alerts"); assert.deepEqual(P.applyDisplay(quiet, ["alerts", "group:apps"]).map((p) => p.id), ["group:apps"]); assert.deepEqual(P.applyDisplay(quiet, ["alerts"]).map((p) => p.id), ["overview"]); assert.deepEqual(P.applyDisplay(quiet, ["group:nothing"]).map((p) => p.id), ["overview"]); }); test("the pages a display may be given are the board's, in its order", () => { const ids = P.displayPageChoices().map((c) => c.id); assert.deepEqual(ids.slice(0, 2), ["overview", "alerts"]); assert.ok(ids.includes("group:infrastructure") && ids.includes("group:other")); for (const id of ids) assert.match(id, W.PAGE_ID, `${id} is a page the server accepts`); }); test("the address wins, then what the display says, then what the browser last chose", () => { assert.equal(P.rotateSeconds("45", "off", 60), 45, "the address"); assert.equal(P.rotateSeconds("off", "30", 60), null, "the address may switch it off"); assert.equal(P.rotateSeconds(null, "off", 60), 60, "the display, over the browser"); assert.equal(P.rotateSeconds(null, "30", null), 30, "the browser, when the display says nothing"); assert.equal(P.rotateSeconds(null, null, null), null); assert.equal(P.rotateSeconds(null, null, 5), P.ROTATE_MIN, "a speed out of range is brought into it"); assert.equal(P.rotateSeconds(null, "30"), 30, "existing callers are unchanged"); }); }); describe("the routes", () => { let app: Server; let base = ""; let who = "root"; 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: "root", name: "Rut", role: "admin" }, { oidcSub: "viewer", name: "Vera", role: "viewer" }, ]); 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/wall-displays", wallDisplaysRouter); a.use("/api/share-links", shareLinksRouter); a.use("/api/public/wall", publicWallRouter); app = await new Promise((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("an administrator makes one, the address is made from the name, and anyone signed in can see the list", async () => { const res = await call("POST", "/wall-displays", { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 }); assert.equal(res.status, 201); const { display } = await res.json(); assert.deepEqual([display.name, display.slug, display.pages, display.rotateSeconds], ["Hall TV", "hall-tv", ["overview", "group:apps"], 30]); assert.equal(display.createdBy, "Rut"); who = "viewer"; const list = await (await call("GET", "/wall-displays")).json(); assert.deepEqual(list.displays.map((d: { slug: string }) => d.slug), ["hall-tv"]); who = "root"; }); test("a viewer can not make, change or remove one", async () => { who = "viewer"; assert.equal((await call("POST", "/wall-displays", { name: "No" })).status, 403); const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id; assert.equal((await call("PUT", `/wall-displays/${id}`, { name: "No" })).status, 403); assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 403); who = "root"; }); test("a second with the same name gets a number; an address asked for that is taken is refused; a bad one is refused with a reason", async () => { const second = (await (await call("POST", "/wall-displays", { name: "Hall TV" })).json()).display; assert.equal(second.slug, "hall-tv-2"); assert.deepEqual([second.pages, second.rotateSeconds], [[], null], "no pages is every page"); const taken = await call("POST", "/wall-displays", { name: "Other", slug: "hall-tv" }); assert.equal(taken.status, 409); assert.equal((await taken.json()).error, "slug_taken"); for (const bad of [{ name: "" }, { name: "x", slug: "Has Spaces" }, { name: "x", slug: "-lead" }, { name: "x", pages: ["nonsense"] }, { name: "x", pages: ["group:UPPER"] }, { name: "x", rotateSeconds: 3 }, { name: "x", rotateSeconds: 9999 }, { name: "x", pages: Array(25).fill("overview") }]) { assert.equal((await call("POST", "/wall-displays", bad)).status, 400, JSON.stringify(bad).slice(0, 50)); } assert.match((await (await call("POST", "/wall-displays", { name: "x", pages: ["nonsense"] })).json()).message, /not a page of the board/); await call("DELETE", `/wall-displays/${second.id}`); }); test("changing it keeps its address unless that is changed on purpose, so a bookmark on a screen survives a corrected name", async () => { const id = (await (await call("GET", "/wall-displays")).json()).displays.find((d: { slug: string }) => d.slug === "hall-tv").id; const renamed = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", pages: ["group:network"], rotateSeconds: null })).json()).display; assert.deepEqual([renamed.name, renamed.slug, renamed.pages, renamed.rotateSeconds], ["Hallway TV", "hall-tv", ["group:network"], null]); const moved = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", slug: "hallway" })).json()).display; assert.equal(moved.slug, "hallway"); assert.equal((await call("PUT", "/wall-displays/9999", { name: "x" })).status, 404); assert.equal((await call("PUT", "/wall-displays/abc", { name: "x" })).status, 400); await call("PUT", `/wall-displays/${id}`, { name: "Hall TV", slug: "hall-tv", pages: ["overview", "group:apps"], rotateSeconds: 30 }); }); test("a wall share link can open one; the public board is told its name, pages and speed; one that is gone opens the whole board", async () => { const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id; const made = await call("POST", "/share-links", { label: "Hall screen", kind: "wall", detail: "summary", displayId: id, expiresInDays: null }); assert.equal(made.status, 201); const { link, token } = await made.json(); assert.equal(link.displayId, id); const board = await (await call("GET", `/public/wall/${token}`)).json(); assert.deepEqual(board.displayConfig, { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 }); // a link with no display says none const plain = (await (await call("POST", "/share-links", { label: "Whole board", kind: "wall", expiresInDays: null })).json()).token; assert.equal((await (await call("GET", `/public/wall/${plain}`)).json()).displayConfig, null); // taking the display away leaves the link working, on the whole board assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 204); const after = await (await call("GET", `/public/wall/${token}`)).json(); assert.equal(after.displayConfig, null); const [row] = await db.select().from(shareLinks).where(eq(shareLinks.label, "Hall screen")); assert.equal(row.displayId, null); }); test("a link can only open a display that exists, only a wall can, and the rest of what it needs is unchanged", async () => { const refused = await call("POST", "/share-links", { label: "x", kind: "wall", displayId: 9999, expiresInDays: null }); assert.equal(refused.status, 400); assert.equal((await refused.json()).error, "no_such_display"); const display = (await (await call("POST", "/wall-displays", { name: "For status" })).json()).display; const calendar = (await (await call("POST", "/share-links", { label: "cal", kind: "calendar", detail: "summary", displayId: display.id, expiresInDays: null })).json()).link; assert.equal(calendar.displayId, null, "a calendar has no display"); void createShareLink; }); test("it is in the audit log and the change log", async () => { const audit = (await db.select().from(auditLog)).filter((a) => a.category === "wall_display"); assert.deepEqual([...new Set(audit.map((a) => a.action))].sort(), ["create", "delete", "update"]); assert.deepEqual(describeChange("wall_display", "create", { name: "Hall TV", address: "/wall/hall-tv" }), { title: "Wall display added: Hall TV", tone: "neutral", detail: "/wall/hall-tv" }); assert.equal(describeChange("wall_display", "update", { name: "Hall TV" }).title, "Wall display changed: Hall TV"); assert.equal(describeChange("wall_display", "delete", { name: "Hall TV" }).title, "Wall display removed: Hall TV"); }); test("no more than twenty", async () => { for (let i = 0; i < 25; i++) { const r = await call("POST", "/wall-displays", { name: `Screen ${i}` }); if (r.status === 409) { assert.equal((await r.json()).error, "too_many"); return; } } assert.fail("never refused"); }); });