/** * 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 night", () => { const at = (hh: number, mm = 0) => new Date(2026, 10, 10, hh, mm, 0); const night = { from: "22:00", to: "07:00", mode: "dim" as const, wakeOnCritical: true }; test("a night across midnight is from the start up to, not including, the end; one within a day is plain", () => { assert.equal(P.inNight(at(21, 59), night), false); assert.equal(P.inNight(at(22, 0), night), true); assert.equal(P.inNight(at(23, 59), night), true); assert.equal(P.inNight(at(0, 0), night), true); assert.equal(P.inNight(at(6, 59), night), true); assert.equal(P.inNight(at(7, 0), night), false, "the end is the morning"); assert.equal(P.inNight(at(12, 0), night), false); const nap = { from: "13:00", to: "15:30" }; assert.deepEqual([at(12, 59), at(13, 0), at(15, 29), at(15, 30)].map((d) => P.inNight(d, nap)), [false, true, true, false]); assert.equal(P.inNight(at(3), { from: "05:00", to: "05:00" }), false, "no length, no night"); }); test("at night it is dimmed or blank; by day, with no schedule, or when something is critical (if told to) it is the board", () => { const quiet = { critical: false, wokenUntil: null }; assert.equal(P.nightState(at(12), night, quiet), "day"); assert.equal(P.nightState(at(23), night, quiet), "dim"); assert.equal(P.nightState(at(23), { ...night, mode: "off" }, quiet), "off"); assert.equal(P.nightState(at(23), null, quiet), "day"); assert.equal(P.nightState(at(23), undefined, quiet), "day"); assert.equal(P.nightState(at(23), night, { critical: true, wokenUntil: null }), "day", "something is critical"); assert.equal(P.nightState(at(23), { ...night, mode: "off", wakeOnCritical: false }, { critical: true, wokenUntil: null }), "off", "told not to"); }); test("a touch brings the board back for two minutes, then the night returns", () => { const now = at(23); const touched = now.getTime() + P.WAKE_FOR_MS; assert.equal(P.WAKE_FOR_MS, 120_000); assert.equal(P.nightState(now, night, { critical: false, wokenUntil: touched }), "day"); assert.equal(P.nightState(new Date(touched + 1), night, { critical: false, wokenUntil: touched }), "dim"); }); test("what is stored is a night only when all of it is there and makes sense", () => { const row = { nightFrom: "22:00", nightTo: "07:00", nightMode: "off", nightWakeCritical: false }; assert.deepEqual(W.nightOf(row), { from: "22:00", to: "07:00", mode: "off", wakeOnCritical: false }); for (const bad of [{ nightFrom: null }, { nightTo: null }, { nightMode: null }, { nightFrom: "7:00" }, { nightTo: "24:00" }, { nightMode: "sleep" }, { nightTo: "22:00" }]) assert.equal(W.nightOf({ ...row, ...bad }), null, JSON.stringify(bad)); }); }); 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, night: null }); // 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("a display can have a night schedule; it is read back, given to the public board, and taken away by saving without one", async () => { const made = await call("POST", "/wall-displays", { name: "Bedroom", night: { from: "23:00", to: "06:30", mode: "off", wakeOnCritical: false } }); assert.equal(made.status, 201); const display = (await made.json()).display; assert.deepEqual(display.night, { from: "23:00", to: "06:30", mode: "off", wakeOnCritical: false }); const link = await (await call("POST", "/share-links", { label: "Bedroom screen", kind: "wall", displayId: display.id, expiresInDays: null })).json(); const board = await (await call("GET", `/public/wall/${link.token}`)).json(); assert.deepEqual(board.displayConfig.night, { from: "23:00", to: "06:30", mode: "off", wakeOnCritical: false }); const without = (await (await call("PUT", `/wall-displays/${display.id}`, { name: "Bedroom" })).json()).display; assert.equal(without.night, null); assert.equal((await (await call("GET", `/public/wall/${link.token}`)).json()).displayConfig.night, null); const defaults = (await (await call("PUT", `/wall-displays/${display.id}`, { name: "Bedroom", night: { from: "22:00", to: "07:00", mode: "dim" } })).json()).display; assert.equal(defaults.night.wakeOnCritical, true, "a critical alert brings it back unless it is told not to"); await call("DELETE", `/wall-displays/${display.id}`); }); test("a night needs real times, two that differ, and a way", async () => { const bad = (night: unknown) => call("POST", "/wall-displays", { name: "Nope", night }); for (const n of [{ from: "7:00", to: "22:00", mode: "dim" }, { from: "22:00", to: "25:00", mode: "dim" }, { from: "22:00", to: "22:00", mode: "dim" }, { from: "22:00", to: "07:00", mode: "sleep" }, { from: "22:00", to: "07:00" }, { from: "22:00" }, "night"]) { assert.equal((await bad(n)).status, 400, JSON.stringify(n)); } assert.match((await (await bad({ from: "22:00", to: "22:00", mode: "dim" })).json()).message, /start and an end that differ/); }); 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"); }); });