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>
This commit is contained in:
1 parent
906220040e
commit
44e393f172
50 files changed
+6114
-258
No files matched your search
@@ -0,0 +1 @@
|
||||
ALTER TABLE `users` ADD `dashboard_layout` text;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE `share_links` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`label` text NOT NULL,
|
||||
`token_hash` text NOT NULL,
|
||||
`token_prefix` text NOT NULL,
|
||||
`detail` text DEFAULT 'summary' NOT NULL,
|
||||
`created_by` text,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL,
|
||||
`expires_at` text,
|
||||
`last_used_at` text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `share_links_token_hash_unique` ON `share_links` (`token_hash`);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -155,6 +155,20 @@
|
||||
"when": 1792177953255,
|
||||
"tag": "0021_conscious_snowbird",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 22,
|
||||
"version": "6",
|
||||
"when": 1792180939809,
|
||||
"tag": "0022_elite_kabuki",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 23,
|
||||
"version": "6",
|
||||
"when": 1792181083723,
|
||||
"tag": "0023_premium_cyclops",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import { resolveDataPath } from "./paths.js";
|
||||
import { authRouter } from "./auth/router.js";
|
||||
import { meRouter } from "./routes/me.js";
|
||||
import { uptimeRouter } from "./routes/uptime.js";
|
||||
import { shareLinksRouter } from "./routes/shareLinks.js";
|
||||
import { publicWallRouter } from "./routes/publicWall.js";
|
||||
import { usersRouter } from "./routes/users.js";
|
||||
import { auditLogRouter } from "./routes/auditLog.js";
|
||||
import { diagLogRouter } from "./routes/diagLog.js";
|
||||
@@ -89,6 +91,8 @@ export function createApp() {
|
||||
app.use("/auth", authRouter);
|
||||
app.use("/api/me", meRouter);
|
||||
app.use("/api/uptime", uptimeRouter);
|
||||
app.use("/api/share-links", shareLinksRouter);
|
||||
app.use("/api/public/wall", publicWallRouter);
|
||||
app.use("/api/users", usersRouter);
|
||||
app.use("/api/audit-log", auditLogRouter);
|
||||
app.use("/api/diag-log", diagLogRouter);
|
||||
|
||||
@@ -20,6 +20,9 @@ export const users = sqliteTable("users", {
|
||||
favorites: text("favorites"),
|
||||
// When this person last pressed "Got it" on the dashboard summary of what changed; the next summary starts from here (ISO).
|
||||
lastLookedAt: text("last_looked_at"),
|
||||
// How this person arranged the dashboard: a JSON object with the cards they hid ("hidden": ["Gitea"]) and the order of the others
|
||||
// ("order": {"DNS": 0, "Secrets": 1}). Follows them to any browser; null is the default layout.
|
||||
dashboardLayout: text("dashboard_layout"),
|
||||
});
|
||||
|
||||
// ─── Audit log ──────────────────────────────────────────────────────────────
|
||||
@@ -480,3 +483,25 @@ export const alertTickets = sqliteTable(
|
||||
},
|
||||
(t) => [index("alert_tickets_key_idx").on(t.alertKey)],
|
||||
);
|
||||
|
||||
// ─── Share links: a read-only status board anyone with the address can open ─
|
||||
|
||||
export const shareLinkDetails = ["summary", "names"] as const;
|
||||
export type ShareLinkDetail = (typeof shareLinkDetails)[number];
|
||||
|
||||
// A link to the wall display that needs no sign-in, for a TV in the hall or someone who only wants to know if things are up. Only a hash
|
||||
// of the secret part of the address is kept (like an agent token), so it can't be read back out of the database or a backup.
|
||||
export const shareLinks = sqliteTable("share_links", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
label: text("label").notNull(), // what it is for, e.g. "Hall TV"
|
||||
tokenHash: text("token_hash").notNull().unique(),
|
||||
tokenPrefix: text("token_prefix").notNull(), // the first characters, to tell links apart in the list
|
||||
// summary = how things are, in numbers; names = also the names of what is wrong, in maintenance, and the integrations
|
||||
detail: text("detail").$type<ShareLinkDetail>().notNull().default("summary"),
|
||||
createdBy: text("created_by"),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
expiresAt: text("expires_at"), // ISO; null = never
|
||||
lastUsedAt: text("last_used_at"), // ISO
|
||||
});
|
||||
+47
-5
@@ -23,15 +23,45 @@ export function parseFavorites(stored: string | null): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
/** What is stored for the dashboard, read back as a layout. Anything that isn't one is the default layout rather than an error. */
|
||||
export function parseDashboardLayout(stored: string | null): DashboardLayout {
|
||||
const empty: DashboardLayout = { hidden: [], order: {} };
|
||||
if (!stored) return empty;
|
||||
try {
|
||||
const value = JSON.parse(stored);
|
||||
const parsed = dashboardSchema.safeParse(value);
|
||||
return parsed.success ? parsed.data : empty;
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
meRouter.get("/", requireAuth, (req, res) => {
|
||||
const { id, email, name, role, oidcSub, favorites } = req.currentUser!;
|
||||
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites) } });
|
||||
const { id, email, name, role, oidcSub, favorites, dashboardLayout } = req.currentUser!;
|
||||
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites), dashboard: parseDashboardLayout(dashboardLayout) } });
|
||||
});
|
||||
|
||||
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes. Which of them are real pages is
|
||||
// the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
|
||||
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes — and, for a saved view of a page,
|
||||
// a short query of the characters a browser leaves as they are or percent-encodes (the search words, a status, a sort). Which of them
|
||||
// are real pages is the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
|
||||
const favoritesSchema = z.object({
|
||||
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}$/, "Not a page path")).max(MAX_FAVORITES),
|
||||
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}(\?[A-Za-z0-9*\-._+%=&]{1,160})?$/, "Not a page path")).max(MAX_FAVORITES),
|
||||
});
|
||||
|
||||
/** The most cards a layout can name: more than any dashboard has. */
|
||||
const MAX_LAYOUT_CARDS = 60;
|
||||
|
||||
export interface DashboardLayout {
|
||||
/** Card labels the person hid. */
|
||||
hidden: string[];
|
||||
/** Position of a card among its neighbours; lower comes first. */
|
||||
order: Record<string, number>;
|
||||
}
|
||||
|
||||
const cardName = z.string().min(1).max(60);
|
||||
const dashboardSchema = z.object({
|
||||
hidden: z.array(cardName).max(MAX_LAYOUT_CARDS),
|
||||
order: z.record(cardName, z.number().int().min(0).max(1000)).refine((o) => Object.keys(o).length <= MAX_LAYOUT_CARDS, "Too many cards"),
|
||||
});
|
||||
|
||||
// Replaces the signed-in person's pinned pages. Only ever their own.
|
||||
@@ -69,3 +99,15 @@ meRouter.post("/changes/seen", requireAuth, asyncHandler(async (req, res) => {
|
||||
await db.update(users).set({ lastLookedAt: at }).where(eq(users.id, req.currentUser!.id));
|
||||
res.json({ lastLookedAt: at });
|
||||
}));
|
||||
|
||||
// Replaces how the signed-in person arranged the dashboard. Only ever their own.
|
||||
meRouter.put("/dashboard", requireAuth, asyncHandler(async (req, res) => {
|
||||
const parsed = dashboardSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
return res.status(400).json({ error: "invalid_body", message: "Name the cards to hide and the order of the rest.", details: parsed.error.flatten() });
|
||||
}
|
||||
const layout: DashboardLayout = { hidden: [...new Set(parsed.data.hidden)], order: parsed.data.order };
|
||||
const empty = layout.hidden.length === 0 && Object.keys(layout.order).length === 0;
|
||||
await db.update(users).set({ dashboardLayout: empty ? null : JSON.stringify(layout) }).where(eq(users.id, req.currentUser!.id));
|
||||
res.json({ dashboard: layout });
|
||||
}));
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Router } from "express";
|
||||
import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js";
|
||||
import { buildPublicWall } from "../services/publicWall.js";
|
||||
import { rateLimit } from "../utils/rateLimit.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const publicWallRouter = Router();
|
||||
|
||||
// No sign-in here: the secret in the address is the whole of the access, so this reads nothing but the wall's picture, and answers a
|
||||
// link that doesn't work — never made, ended, or taken back — in the same words.
|
||||
const limiter = rateLimit({ windowMs: 60_000, max: 60, message: "Too many requests. Wait a minute." });
|
||||
|
||||
publicWallRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
|
||||
const link = await resolveShareLink(req.params.token);
|
||||
if (!link) return res.status(404).json(NOT_FOUND);
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("X-Robots-Tag", "noindex, nofollow");
|
||||
res.json(await buildPublicWall(link.detail));
|
||||
}));
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { shareLinkDetails, shareLinks } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { createShareLink, publicShareLink } from "../services/shareLinks.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const shareLinksRouter = Router();
|
||||
|
||||
// Making a link that anyone can open without signing in is an administrator's decision.
|
||||
shareLinksRouter.use(requireAuth, requireRole("admin"));
|
||||
|
||||
/** More links than anyone needs; each is something to keep track of and take back. */
|
||||
const MAX_LINKS = 20;
|
||||
|
||||
const createSchema = z.object({
|
||||
label: z.string().trim().min(1).max(60),
|
||||
detail: z.enum(shareLinkDetails),
|
||||
expiresInDays: z.number().int().min(1).max(365).nullable(),
|
||||
});
|
||||
|
||||
shareLinksRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const rows = await db.select().from(shareLinks).orderBy(shareLinks.createdAt);
|
||||
res.json({ links: rows.map((r) => publicShareLink(r)) });
|
||||
}));
|
||||
|
||||
// The secret part of the address is in this response and nowhere else, ever: only a hash of it is kept.
|
||||
shareLinksRouter.post("/", asyncHandler(async (req, res) => {
|
||||
const parsed = createSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
return res.status(400).json({ error: "invalid_body", message: "Give the link a name, say how much it shows, and how long it lasts.", details: parsed.error.flatten() });
|
||||
}
|
||||
const existing = await db.select({ id: shareLinks.id }).from(shareLinks);
|
||||
if (existing.length >= MAX_LINKS) {
|
||||
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_LINKS} share links. Remove one you no longer use first.` });
|
||||
}
|
||||
const actor = req.currentUser!;
|
||||
const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
|
||||
await recordAudit({
|
||||
actor,
|
||||
category: "share_link",
|
||||
action: "create",
|
||||
targetType: "share_link",
|
||||
targetId: link.id,
|
||||
detail: { label: link.label, detail: link.detail, expiresAt: link.expiresAt },
|
||||
});
|
||||
res.status(201).json({ link: publicShareLink(link), token, path: `/share/wall/${token}` });
|
||||
}));
|
||||
|
||||
shareLinksRouter.delete("/:id", asyncHandler(async (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.id, id)).limit(1);
|
||||
if (!link) return res.status(404).json({ error: "not_found" });
|
||||
await db.delete(shareLinks).where(eq(shareLinks.id, id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "share_link", action: "delete", targetType: "share_link", targetId: id, detail: { label: link.label } });
|
||||
res.status(204).end();
|
||||
}));
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* What a share link may show: the wall display's picture of how things are, built here on the server so that nothing beyond it ever
|
||||
* reaches someone who isn't signed in. "summary" is only numbers and an overall state; "names" adds the names of what is wrong, of what
|
||||
* is in maintenance, and of the integrations — but never addresses, tokens or other settings.
|
||||
*/
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, servers } from "../db/schema.js";
|
||||
import { env } from "../env.js";
|
||||
import { getAlerts } from "./alerts.js";
|
||||
import { getSourceStatus } from "./integrationHealthMonitor.js";
|
||||
import { describeTarget, listActiveWindows, activeSubjects } from "./maintenance.js";
|
||||
import { buildServerSummary } from "./serverSummary.js";
|
||||
import { getSettings } from "./settingsStore.js";
|
||||
import type { ShareLinkDetail } from "../db/schema.js";
|
||||
|
||||
export interface PublicWall {
|
||||
detail: ShareLinkDetail;
|
||||
/** Overall state, decided here exactly as the signed-in wall decides it. */
|
||||
level: "ok" | "warning" | "critical" | "unsure";
|
||||
environment: string | null;
|
||||
servers: { online: number; offline: number };
|
||||
alerts: { critical: number; warning: number };
|
||||
/** Windows running now. */
|
||||
maintenance: number;
|
||||
integrationsFailing: number;
|
||||
/** Only with detail "names". */
|
||||
problems?: { id: string; severity: "critical" | "warning"; message: string }[];
|
||||
maintenanceWindows?: { id: number; name: string; endsAt: string }[];
|
||||
integrations?: { id: number; name: string; type: string; status: "ok" | "failing" | "unknown" }[];
|
||||
generatedAt: string;
|
||||
/** How dates and times are written here — so the board reads the way the rest of the app does. */
|
||||
display: { dateFormat: string; timeFormat: string };
|
||||
}
|
||||
|
||||
const MAX_PROBLEMS = 7;
|
||||
const MAX_WINDOWS = 8;
|
||||
|
||||
export async function buildPublicWall(detail: ShareLinkDetail, now: Date = new Date()): Promise<PublicWall> {
|
||||
const [report, settings, windows, serverRows, integrationRows, subjects] = await Promise.all([
|
||||
getAlerts(false),
|
||||
getSettings(),
|
||||
listActiveWindows(now),
|
||||
db.select({ id: servers.id, name: servers.name, osType: servers.osType, lastSeenAt: servers.lastSeenAt, disks: servers.disks }).from(servers),
|
||||
db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations),
|
||||
activeSubjects(now),
|
||||
]);
|
||||
|
||||
const summary = buildServerSummary(serverRows, settings.healthChecks, now.getTime(), subjects);
|
||||
const enabled = integrationRows.filter((i) => i.enabled);
|
||||
const statusOf = (type: string) => getSourceStatus(type).status;
|
||||
const failing = enabled.filter((i) => statusOf(i.type) === "failing");
|
||||
|
||||
const critical = report.counts.critical;
|
||||
const warning = report.counts.warning;
|
||||
const level: PublicWall["level"] = critical > 0 ? "critical" : warning > 0 ? "warning" : report.couldntCheck.length > 0 ? "unsure" : "ok";
|
||||
|
||||
const out: PublicWall = {
|
||||
detail,
|
||||
level,
|
||||
environment: env.environment?.name || null,
|
||||
servers: { online: summary.online, offline: summary.offline.length },
|
||||
alerts: { critical, warning },
|
||||
maintenance: windows.length,
|
||||
integrationsFailing: failing.length,
|
||||
generatedAt: now.toISOString(),
|
||||
display: { dateFormat: settings.display.dateFormat, timeFormat: settings.display.timeFormat },
|
||||
};
|
||||
|
||||
if (detail === "names") {
|
||||
out.problems = report.alerts
|
||||
.filter((a): a is typeof a & { severity: "critical" | "warning" } => !a.silenced && a.severity !== "info")
|
||||
.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "critical" ? -1 : 1))
|
||||
.slice(0, MAX_PROBLEMS)
|
||||
.map((a) => ({ id: a.id, severity: a.severity, message: a.message }));
|
||||
const named: { id: number; name: string; endsAt: string }[] = [];
|
||||
for (const w of [...windows].sort((a, b) => a.endsAt.localeCompare(b.endsAt))) {
|
||||
const target = await describeTarget(w.targetType, w.targetId);
|
||||
if (target) named.push({ id: w.id, name: target.name, endsAt: w.endsAt });
|
||||
}
|
||||
out.maintenanceWindows = named.slice(0, MAX_WINDOWS);
|
||||
out.integrations = [...enabled]
|
||||
.sort((a, b) => Number(statusOf(b.type) === "failing") - Number(statusOf(a.type) === "failing") || a.name.localeCompare(b.name))
|
||||
.map((i) => ({ id: i.id, name: i.name, type: i.type, status: statusOf(i.type) }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Share links: an address that opens a read-only wall display without signing in. The address carries a long random secret; only its
|
||||
* SHA-256 is stored, so the secret can't be read back out of the database or a backup, and it is shown once, when the link is made.
|
||||
*/
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { shareLinks, type ShareLinkDetail } from "../db/schema.js";
|
||||
|
||||
export type ShareLinkRow = typeof shareLinks.$inferSelect;
|
||||
|
||||
/** What the public may be told about a link that doesn't work: nothing that tells "never existed" from "ended" or "removed". */
|
||||
export const NOT_FOUND = { error: "not_found", message: "This link doesn't work." } as const;
|
||||
|
||||
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
/** A link isn't recorded as used more than once in this time, so a screen refreshing every few seconds doesn't write the database each time. */
|
||||
const USED_WRITE_GAP_MS = 60_000;
|
||||
|
||||
export async function createShareLink(params: { label: string; detail: ShareLinkDetail; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> {
|
||||
const now = params.now ?? new Date();
|
||||
const token = randomBytes(24).toString("base64url");
|
||||
const [link] = await db
|
||||
.insert(shareLinks)
|
||||
.values({
|
||||
label: params.label,
|
||||
tokenHash: hash(token),
|
||||
tokenPrefix: token.slice(0, 6),
|
||||
detail: params.detail,
|
||||
createdBy: params.createdBy,
|
||||
expiresAt: params.expiresInDays === null ? null : new Date(now.getTime() + params.expiresInDays * 86_400_000).toISOString(),
|
||||
})
|
||||
.returning();
|
||||
return { link, token };
|
||||
}
|
||||
|
||||
/** The link a secret belongs to, if it exists and has not ended. Notes that it was used. */
|
||||
export async function resolveShareLink(token: string, now: Date = new Date()): Promise<ShareLinkRow | null> {
|
||||
if (typeof token !== "string" || token.length < 16 || token.length > 128) return null;
|
||||
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.tokenHash, hash(token))).limit(1);
|
||||
if (!link) return null;
|
||||
if (link.expiresAt && Date.parse(link.expiresAt) <= now.getTime()) return null;
|
||||
if (!link.lastUsedAt || now.getTime() - Date.parse(link.lastUsedAt) >= USED_WRITE_GAP_MS) {
|
||||
await db.update(shareLinks).set({ lastUsedAt: now.toISOString() }).where(eq(shareLinks.id, link.id));
|
||||
}
|
||||
return link;
|
||||
}
|
||||
|
||||
/** A link as the admin list shows it: everything but the hash. */
|
||||
export function publicShareLink(link: ShareLinkRow, now: Date = new Date()) {
|
||||
return {
|
||||
id: link.id,
|
||||
label: link.label,
|
||||
tokenPrefix: link.tokenPrefix,
|
||||
detail: link.detail,
|
||||
createdBy: link.createdBy,
|
||||
createdAt: link.createdAt,
|
||||
expiresAt: link.expiresAt,
|
||||
lastUsedAt: link.lastUsedAt,
|
||||
expired: !!link.expiresAt && Date.parse(link.expiresAt) <= now.getTime(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* 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");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user