New integration kinds adguard (status, statistics, filter lists and a real DNS question over UDP; alerts for DNS down/not running, protection left off, stale lists) and grafana (alert rules firing or failing, data-source health). Optional warning for running Docker images built more than N days ago (off by default). A server's overview cards can be folded and arranged, kept per user. Migrations 0075-0077; docs, metrics and tests included. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
155 lines
7.2 KiB
TypeScript
155 lines
7.2 KiB
TypeScript
import { Router } from "express";
|
|
import { eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.js";
|
|
import { users } from "../db/schema.js";
|
|
import { requireAuth } from "../auth/middleware.js";
|
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
import { FIRST_LOOKBACK_MS, getChangesSince } from "../services/changesSince.js";
|
|
import { avatarUrlFor } from "../services/avatars.js";
|
|
import { getSettings } from "../services/settingsStore.js";
|
|
|
|
export const meRouter = Router();
|
|
|
|
/** The most pages anyone can pin: enough for a working set, not a second menu. */
|
|
export const MAX_FAVORITES = 24;
|
|
|
|
/** What is stored, read back as a list. Anything that isn't one is no favourites rather than an error. */
|
|
export function parseFavorites(stored: string | null): string[] {
|
|
if (!stored) return [];
|
|
try {
|
|
const value = JSON.parse(stored);
|
|
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string").slice(0, MAX_FAVORITES) : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/** 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, asyncHandler(async (req, res) => {
|
|
const me = req.currentUser!;
|
|
const { id, email, name, role, oidcSub, favorites, dashboardLayout, serverPageLayout } = me;
|
|
const avatarUrl = avatarUrlFor(me, (await getSettings()).profilePictures);
|
|
res.json({ user: { id, sub: oidcSub, email, name, role, avatarUrl, favorites: parseFavorites(favorites), dashboard: parseDashboardLayout(dashboardLayout), serverPage: parsePageLayout(serverPageLayout) } });
|
|
}));
|
|
|
|
// 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}(\?[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"),
|
|
});
|
|
|
|
export interface PageLayout {
|
|
/** Blocks (cards) the person folded: only their header shows. */
|
|
folded: string[];
|
|
/** Position of a block among the others on the page; lower comes first. */
|
|
order: Record<string, number>;
|
|
}
|
|
|
|
const blockName = z.string().regex(/^[a-z0-9-]{1,40}$/);
|
|
const pageLayoutSchema = z.object({
|
|
folded: z.array(blockName).max(MAX_LAYOUT_CARDS),
|
|
order: z.record(blockName, z.number().int().min(0).max(1000)).refine((o) => Object.keys(o).length <= MAX_LAYOUT_CARDS, "Too many blocks"),
|
|
});
|
|
|
|
/** What is stored for a page, read back as a layout. Anything that isn't one is the page as drawn rather than an error. */
|
|
export function parsePageLayout(stored: string | null): PageLayout {
|
|
const empty: PageLayout = { folded: [], order: {} };
|
|
if (!stored) return empty;
|
|
try {
|
|
const parsed = pageLayoutSchema.safeParse(JSON.parse(stored));
|
|
return parsed.success ? parsed.data : empty;
|
|
} catch {
|
|
return empty;
|
|
}
|
|
}
|
|
|
|
// Replaces the signed-in person's pinned pages. Only ever their own.
|
|
meRouter.put("/favorites", requireAuth, asyncHandler(async (req, res) => {
|
|
const parsed = favoritesSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: `Pin up to ${MAX_FAVORITES} pages, by their path.`, details: parsed.error.flatten() });
|
|
}
|
|
const paths = [...new Set(parsed.data.paths)];
|
|
await db.update(users).set({ favorites: JSON.stringify(paths) }).where(eq(users.id, req.currentUser!.id));
|
|
res.json({ favorites: paths });
|
|
}));
|
|
|
|
const CHANGES_SHOWN = 8;
|
|
|
|
// What happened since this person last pressed "Got it" on the dashboard (or in the last day, the first time). Only reads.
|
|
meRouter.get("/changes", requireAuth, asyncHandler(async (req, res) => {
|
|
const user = req.currentUser!;
|
|
const now = new Date();
|
|
const stored = user.lastLookedAt ? Date.parse(user.lastLookedAt) : NaN;
|
|
const since = new Date(Number.isFinite(stored) ? stored : now.getTime() - FIRST_LOOKBACK_MS);
|
|
const report = await getChangesSince({ since, now, actorId: user.id, canSeeAudit: user.role === "admin" || user.role === "operator" });
|
|
res.json({
|
|
since: report.since,
|
|
firstTime: !Number.isFinite(stored),
|
|
events: report.events.slice(0, CHANGES_SHOWN),
|
|
moreEvents: Math.max(0, report.events.length - CHANGES_SHOWN),
|
|
changesByOthers: report.changesByOthers,
|
|
});
|
|
}));
|
|
|
|
// "Got it": the next summary starts from now. Only ever for the signed-in person.
|
|
meRouter.post("/changes/seen", requireAuth, asyncHandler(async (req, res) => {
|
|
const at = new Date().toISOString();
|
|
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 a server's overview page. Only ever their own.
|
|
meRouter.put("/server-page", requireAuth, asyncHandler(async (req, res) => {
|
|
const parsed = pageLayoutSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: "Name the blocks to fold and the order of the rest.", details: parsed.error.flatten() });
|
|
}
|
|
const layout: PageLayout = { folded: [...new Set(parsed.data.folded)], order: parsed.data.order };
|
|
const empty = layout.folded.length === 0 && Object.keys(layout.order).length === 0;
|
|
await db.update(users).set({ serverPageLayout: empty ? null : JSON.stringify(layout) }).where(eq(users.id, req.currentUser!.id));
|
|
res.json({ serverPage: layout });
|
|
}));
|
|
|
|
// 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 });
|
|
}));
|