UniFi: servers plugged into switches; server page in sections; My work; settings search and undo

UniFi: the controller's client list is matched to servers by IP address, so a
server is connected through a switch or access point (and port). That is a
dependency made by itself, shown on the server page, the Network devices page
and the Connections map. IP Addresses can sync the devices' addresses.

A server's page is split into Overview, Health, Network, History, Tasks and
Settings, by ?view=; alerts link to the section they are about.

My work lists what has your name on it: alerts you have, maintenance you
started (extend, end with undo) and update runs you started, with a badge.

Settings has a search box (and the command palette lists every setting).
Removing a dependency, admin link, runbook, hand-made IP address, port opening
or restore test is undone from the message instead of asked about first.

Two backup tests used a fixed date and failed as days passed; they follow the
real clock now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 19:35:45 +02:00
1 parent 396e074108
commit 5e26e77340
45 files changed
+6224 -194

No files matched your search

+17
View File
@@ -57,6 +57,8 @@ erDiagram
integration_credentials ||--o{ integrations : "credential (set null)" integration_credentials ||--o{ integrations : "credential (set null)"
integrations ||--o{ network_devices : "cascade" integrations ||--o{ network_devices : "cascade"
integrations ||--o{ network_segments : "cascade" integrations ||--o{ network_segments : "cascade"
integrations ||--o{ network_server_links : "cascade"
servers ||--o{ network_server_links : "cascade"
integration_credentials ||--o{ dns_providers : "credential (set null)" integration_credentials ||--o{ dns_providers : "credential (set null)"
dns_providers ||--o{ dns_zones_cache : "cascade" dns_providers ||--o{ dns_zones_cache : "cascade"
dns_providers ||--o{ dns_records_cache : "cascade" dns_providers ||--o{ dns_records_cache : "cascade"
@@ -678,6 +680,21 @@ Switches, access points and gateways read from a UniFi controller (see INTEGRATI
A device the controller no longer lists is deleted on the next read. Dependencies written by hand that mention a removed device are ignored. A device the controller no longer lists is deleted on the next read. Dependencies written by hand that mention a removed device are ignored.
#### `network_server_links`
Which server is plugged into which network device, worked out on every UniFi read: a client the controller lists whose IP address is exactly one server's own. Replaced as a whole on a read that lists any clients; kept as it was when it lists none.
| Column | Type | Notes |
|---|---|---|
| `id` | integer PK | |
| `integration_id` | integer NOT NULL → `integrations.id`, **cascade** | Unique together with `server_id` and `client_mac`. |
| `server_id` | integer NOT NULL → `servers.id`, **cascade** | |
| `device_external_id` | text NOT NULL | The MAC of the switch or access point (`network_devices.external_id`). |
| `client_mac` | text NOT NULL | The server's own MAC as the controller sees it. |
| `port` | integer | The switch port, where the controller says. |
| `wired` | bool NOT NULL | False for a client on Wi-Fi. |
| `updated_at` | text NOT NULL | ISO. |
#### `network_segments` #### `network_segments`
The networks (VLANs) and Wi-Fi names of a UniFi controller, replaced as a whole on every read. Passphrases are never stored. The networks (VLANs) and Wi-Fi names of a UniFi controller, replaced as a whole on every read. Passphrases are never stored.
+2
View File
@@ -241,6 +241,8 @@ the dashboard views themselves load fine. (UniFi only ever reads.)
others by hand (a server needs the switch it is plugged into). others by hand (a server needs the switch it is plugged into).
- A device the controller has not seen online for longer than **Settings → Notifications → Alert when a network device is offline for** (10 minutes) is a critical **offline** alert about it. What needs it, and what - A device the controller has not seen online for longer than **Settings → Notifications → Alert when a network device is offline for** (10 minutes) is a critical **offline** alert about it. What needs it, and what
it is connected through if that is down too, is folded under it, like a guest under its host. It can be silenced with a maintenance window, and has runbooks like any target. it is connected through if that is down too, is folded under it, like a guest under its host. It can be silenced with a maintenance window, and has runbooks like any target.
- **Servers plugged in:** the controller's list of what is connected is matched to servers by IP address (exact, and only when one server has that address). A server is then *connected through* the switch or access point
it is on — a dependency made by itself, shown on the server's page and on the Connections map. A key or account that may not read clients costs only this; devices, networks and Wi-Fi names are unaffected.
- If the controller cannot be read for twenty minutes its devices are neither raised nor cleared, and the Alerts page says it could not check; the integration itself is raised as failing like any other. - If the controller cannot be read for twenty minutes its devices are neither raised nor cleared, and the Alerts page says it could not check; the integration itself is raised as failing like any other.
- **Not verified against a live controller** — built from Ubiquiti's published Integration API and the long-documented classic API (and tried against a pretend controller that answers the way those documents say), - **Not verified against a live controller** — built from Ubiquiti's published Integration API and the long-documented classic API (and tried against a pretend controller that answers the way those documents say),
but nobody has run it against real hardware yet. Every field is read defensively, so one a version renames is left blank rather than breaking the read. If a read fails or comes back empty, the **Diagnostic Log** has but nobody has run it against real hardware yet. Every field is read defensively, so one a version renames is left blank rather than breaking the read. If a read fails or comes back empty, the **Diagnostic Log** has
+16
View File
@@ -811,6 +811,22 @@ join the **dependency map** (Map → Dependencies): what each is connected throu
its alert — "Hallway AP has been offline for 45 min — also takes down pi". A device offline for longer than a set time (Settings → Notifications, 10 minutes) is a critical *Server down* alert, can be silenced with maintenance its alert — "Hallway AP has been offline for 45 min — also takes down pi". A device offline for longer than a set time (Settings → Notifications, 10 minutes) is a critical *Server down* alert, can be silenced with maintenance
(also in the Maintenance page and the command palette), and can have runbooks. Not yet tried against a real controller — see INTEGRATIONS.md. (also in the Maintenance page and the command palette), and can have runbooks. Not yet tried against a real controller — see INTEGRATIONS.md.
**Which switch a server is plugged into.** Every read also asks the controller what is connected, and a client whose IP address is exactly one of a server's own (and only one server's) is taken to be that server: the server is then
*connected through* that switch or access point (and port, where the controller says; Wi-Fi if it is on an access point). That is a dependency made by itself — when the switch is down, the server's offline alert is folded under
the switch's. It shows on the server's page (Network section), on the Network devices page (*Plugged in:* under each device), and on **Map → Connections**, where a switch or access point with servers on it is drawn next to them.
**IP Addresses → Sync from UniFi** adds the devices' addresses (label from the device name, the model and MAC in the notes); an entry made by hand or by another sync is left alone.
**My work** (the menu, for operators and administrators; also a line on the Dashboard when something wants a look). Everything with your name on it: the alerts you acknowledged or were handed (what runs out first at the top, with *Change…* to
edit the acknowledgement), the maintenance windows you started (*+1 h*, *+4 h*, *End now* with an Undo), and the update runs you started that are still going or finished in the last day. What runs out within a day (acknowledgements), ends within two
hours (maintenance), is handed to you or is still going is counted in the badge beside the menu entry.
**A server's page in sections.** Overview (links, hardware, identity, runbooks), Health, Network (what it is connected through, ports), History (trends, activity), Tasks (scheduled tasks, run a playbook) and Settings (Proxmox link, its own alert limits),
switched by `?view=`, so a section can be linked to: an alert about a failing service opens the Health section, a new-port alert the Network section.
**Finding a setting, and undo instead of asking.** Settings has a *Find a setting* box (and the command palette lists every setting too) that goes straight to where it is set — it knows what each is for, so "quiet", "prometheus" or "disk full"
all find something. Removing a dependency, an admin link, a runbook, a hand-made IP address (one or several), a port opening or a restore test no longer asks first: it is gone at once, with an **Undo** on the message for fifteen seconds that makes it again from
what was on screen. Things that could not come back as they were — a secret, a check with its history, a share link or token, a DNS record, a hardware entry that has labels printed with its number — still ask first.
**Flapping alerts and the noise report.** An alert that is raised and clears again and again is more tiring than one that stays: each raise and each recovery is a message. When the same **Flapping alerts and the noise report.** An alert that is raised and clears again and again is more tiring than one that stays: each raise and each recovery is a message. When the same
alert has been **raised three times within an hour** (Settings → Notifications → *Servers and disks* → *Call an alert flapping after*; 0 turns it off) it is called **flapping**: one message says alert has been **raised three times within an hour** (Settings → Notifications → *Servers and disks* → *Call an alert flapping after*; 0 turns it off) it is called **flapping**: one message says
so — "raised 3 times within an hour" — and its further raise and recovery messages are held back. The alert itself is still on the Alerts page, with a *flapping* badge, and keeps counting for the badge in the menu and for /metrics. so — "raised 3 times within an hour" — and its further raise and recovery messages are held back. The alert itself is still on the Alerts page, with a *flapping* badge, and keeps counting for the badge in the menu and for /metrics.
+2
View File
@@ -99,6 +99,8 @@ even further, to admin only:
operator, and so does *Refresh from agent*; the price of power used for the running cost is admin-only. operator, and so does *Refresh from agent*; the price of power used for the running cost is admin-only.
- **Bulk actions** (the bar that appears when rows are ticked) need the same role as the single action: operator to acknowledge, silence, tag, change hardware and undo any of those; administrator for *Runs on…* on several servers - **Bulk actions** (the bar that appears when rows are ticked) need the same role as the single action: operator to acknowledge, silence, tag, change hardware and undo any of those; administrator for *Runs on…* on several servers
(and its undo). Viewers do not see the tick boxes. The **Noise** tab of Alerts is for everyone signed in. (and its undo). Viewers do not see the tick boxes. The **Noise** tab of Alerts is for everyone signed in.
- **My work** is shown to operators and administrators and only ever lists their own alerts, maintenance and update runs; the buttons on it (change an acknowledgement, extend or end a window) need operator, like the pages they come from.
**Settings search** is part of Settings, which is administrators'.
- **Network devices** (Network → Network devices): everyone can see the devices, networks and Wi-Fi names read from UniFi controllers; **Read now** and putting a device under maintenance need operator; adding the UniFi - **Network devices** (Network → Network devices): everyone can see the devices, networks and Wi-Fi names read from UniFi controllers; **Read now** and putting a device under maintenance need operator; adding the UniFi
integration itself (a key or login) is an administrator's job, like any integration. integration itself (a key or login) is an administrator's job, like any integration.
- **Dependencies**: everyone can see what needs what; adding and removing one needs operator. - **Dependencies**: everyone can see what needs what; adding and removing one needs operator.
+14
View File
@@ -0,0 +1,14 @@
CREATE TABLE `network_server_links` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`integration_id` integer NOT NULL,
`server_id` integer NOT NULL,
`device_external_id` text NOT NULL,
`client_mac` text NOT NULL,
`port` integer,
`wired` integer DEFAULT true NOT NULL,
`updated_at` text NOT NULL,
FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`server_id`) REFERENCES `servers`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE UNIQUE INDEX `network_server_links_unique` ON `network_server_links` (`integration_id`,`server_id`,`client_mac`);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -316,6 +316,13 @@
"when": 1792447584218, "when": 1792447584218,
"tag": "0044_sparkling_scourge", "tag": "0044_sparkling_scourge",
"breakpoints": true "breakpoints": true
},
{
"idx": 45,
"version": "6",
"when": 1792516305790,
"tag": "0045_military_exodus",
"breakpoints": true
} }
] ]
} }
+2
View File
@@ -46,6 +46,7 @@ import { portsRouter } from "./routes/ports.js";
import { alertsRouter } from "./routes/alerts.js"; import { alertsRouter } from "./routes/alerts.js";
import { mapRouter } from "./routes/map.js"; import { mapRouter } from "./routes/map.js";
import { networkRouter } from "./routes/network.js"; import { networkRouter } from "./routes/network.js";
import { myWorkRouter } from "./routes/myWork.js";
import { generatorRouter } from "./routes/generator.js"; import { generatorRouter } from "./routes/generator.js";
import { alertTicketsRouter } from "./routes/alertTickets.js"; import { alertTicketsRouter } from "./routes/alertTickets.js";
import { avatarsRouter } from "./routes/avatars.js"; import { avatarsRouter } from "./routes/avatars.js";
@@ -163,6 +164,7 @@ export function createApp() {
app.use("/api/alerts", alertsRouter); app.use("/api/alerts", alertsRouter);
app.use("/api/map", mapRouter); app.use("/api/map", mapRouter);
app.use("/api/network", networkRouter); app.use("/api/network", networkRouter);
app.use("/api/my-work", myWorkRouter);
app.use("/api/generator", generatorRouter); app.use("/api/generator", generatorRouter);
app.use("/api/alert-tickets", alertTicketsRouter); app.use("/api/alert-tickets", alertTicketsRouter);
+21
View File
@@ -564,6 +564,27 @@ export const networkDevices = sqliteTable(
(t) => [uniqueIndex("network_devices_unique").on(t.integrationId, t.externalId)], (t) => [uniqueIndex("network_devices_unique").on(t.integrationId, t.externalId)],
); );
// Which server is plugged into which network device, worked out on every read from what the controller says is connected (matched by the server's IP address).
// A server needs the device it is connected through, as far as the dependency map is concerned.
export const networkServerLinks = sqliteTable(
"network_server_links",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
deviceExternalId: text("device_external_id").notNull(), // the MAC of the switch or access point
clientMac: text("client_mac").notNull(),
port: integer("port"), // the switch port, when the controller says (the classic API does)
wired: integer("wired", { mode: "boolean" }).notNull().default(true),
updatedAt: text("updated_at").notNull(),
},
(t) => [uniqueIndex("network_server_links_unique").on(t.integrationId, t.serverId, t.clientMac)],
);
// The networks (VLANs) and Wi-Fi names (SSIDs) a UniFi controller has set up, kept beside the devices. Passphrases are never read. // The networks (VLANs) and Wi-Fi names (SSIDs) a UniFi controller has set up, kept beside the devices. Passphrases are never read.
export const networkSegments = sqliteTable( export const networkSegments = sqliteTable(
"network_segments", "network_segments",
+43 -2
View File
@@ -75,12 +75,27 @@ export interface UnifiSsid {
siteName: string; siteName: string;
} }
/** Something connected to the network (a computer, a phone, a server), and the device it is connected through. */
export interface UnifiClient {
mac: string;
ip: string | null;
name: string | null;
wired: boolean;
/** The MAC of the switch or access point it is on, when the controller says. */
uplinkExternalId: string | null;
/** The switch port, for a wired client on the classic API. */
port: number | null;
siteName: string;
}
export interface UnifiInventory { export interface UnifiInventory {
mode: "api_key" | "login"; mode: "api_key" | "login";
sites: string[]; sites: string[];
devices: UnifiDevice[]; devices: UnifiDevice[];
networks: UnifiNetwork[]; networks: UnifiNetwork[];
ssids: UnifiSsid[]; ssids: UnifiSsid[];
/** Everything connected right now; [] when the controller would not say (an account or key that may not read clients). */
clients: UnifiClient[];
} }
export interface UnifiAdapter { export interface UnifiAdapter {
@@ -236,6 +251,22 @@ export function networkFromLegacy(raw: unknown, siteName: string): UnifiNetwork
}; };
} }
export function clientFromApi(raw: unknown, macById: Map<string, string>, siteName: string): UnifiClient | null {
const d = obj(raw);
const mac = normaliseMac(d.macAddress);
if (!mac) return null;
const uplinkId = str(d.uplinkDeviceId);
return { mac, ip: str(d.ipAddress), name: str(d.name), wired: String(d.type ?? "").toUpperCase() === "WIRED", uplinkExternalId: uplinkId ? (macById.get(uplinkId) ?? null) : null, port: null, siteName };
}
export function clientFromLegacy(raw: unknown, siteName: string): UnifiClient | null {
const d = obj(raw);
const mac = normaliseMac(d.mac);
if (!mac) return null;
const wired = d.is_wired === true;
return { mac, ip: str(d.ip), name: str(d.name) ?? str(d.hostname), wired, uplinkExternalId: normaliseMac(wired ? d.sw_mac : d.ap_mac), port: wired ? num(d.sw_port) : null, siteName };
}
const API_SECURITY: Record<string, string> = { OPEN: "Open", WPA2_PERSONAL: "WPA2", WPA3_PERSONAL: "WPA3", WPA2_WPA3_PERSONAL: "WPA2/WPA3", WPA2_ENTERPRISE: "WPA2 Enterprise", WPA3_ENTERPRISE: "WPA3 Enterprise" }; const API_SECURITY: Record<string, string> = { OPEN: "Open", WPA2_PERSONAL: "WPA2", WPA3_PERSONAL: "WPA3", WPA2_WPA3_PERSONAL: "WPA2/WPA3", WPA2_ENTERPRISE: "WPA2 Enterprise", WPA3_ENTERPRISE: "WPA3 Enterprise" };
export function ssidFromApi(raw: unknown, networkNames: Map<string, string>, siteName: string): UnifiSsid | null { export function ssidFromApi(raw: unknown, networkNames: Map<string, string>, siteName: string): UnifiSsid | null {
@@ -406,7 +437,7 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
sites = sites.filter((s) => s.name.toLowerCase() === wantSite); sites = sites.filter((s) => s.name.toLowerCase() === wantSite);
if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`); if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`);
} }
const inventory: UnifiInventory = { mode: "api_key", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] }; const inventory: UnifiInventory = { mode: "api_key", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [], clients: [] };
for (const site of sites) { for (const site of sites) {
const base = `/sites/${site.id}`; const base = `/sites/${site.id}`;
const entries = await apiPaged(prefix, `${base}/devices`); const entries = await apiPaged(prefix, `${base}/devices`);
@@ -428,6 +459,12 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
if (d) inventory.devices.push(d); if (d) inventory.devices.push(d);
}); });
// What is connected where. A key that may not read clients costs only the links from servers to the devices they are plugged into.
for (const raw of await apiPaged(prefix, `${base}/clients`).catch(() => [])) {
const c = clientFromApi(raw, macById, site.name);
if (c) inventory.clients.push(c);
}
const netEntries = await apiPaged(prefix, `${base}/networks`).catch(() => []); const netEntries = await apiPaged(prefix, `${base}/networks`).catch(() => []);
const netDetails = await pooled(netEntries, async (e) => { const netDetails = await pooled(netEntries, async (e) => {
const id = str(obj(e).id); const id = str(obj(e).id);
@@ -508,12 +545,16 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
sites = sites.filter((s) => s.name.toLowerCase() === wantSite || s.key.toLowerCase() === wantSite); sites = sites.filter((s) => s.name.toLowerCase() === wantSite || s.key.toLowerCase() === wantSite);
if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`); if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`);
} }
const inventory: UnifiInventory = { mode: "login", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] }; const inventory: UnifiInventory = { mode: "login", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [], clients: [] };
for (const site of sites) { for (const site of sites) {
for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/device`)) { for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/device`)) {
const d = deviceFromLegacy(raw, site.name); const d = deviceFromLegacy(raw, site.name);
if (d) inventory.devices.push(d); if (d) inventory.devices.push(d);
} }
for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/sta`).catch(() => [])) {
const c = clientFromLegacy(raw, site.name);
if (c) inventory.clients.push(c);
}
const networkNames = new Map<string, string>(); const networkNames = new Map<string, string>();
for (const raw of await legacyGet(session, `/api/s/${site.key}/rest/networkconf`).catch(() => [])) { for (const raw of await legacyGet(session, `/api/s/${site.key}/rest/networkconf`).catch(() => [])) {
const n = networkFromLegacy(raw, site.name); const n = networkFromLegacy(raw, site.name);
+1 -1
View File
@@ -64,7 +64,7 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => {
for (const [needing, needed] of graph.edges) { for (const [needing, needed] of graph.edges) {
for (const n of needed) { for (const n of needed) {
// A device connected through another is an uplink (the controller says so); a server's "runs on" is the other kind of link nobody wrote. // A device connected through another is an uplink (the controller says so); a server's "runs on" is the other kind of link nobody wrote.
edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : needing.startsWith("device:") && n.startsWith("device:") ? "uplink" : "runs-on" }); edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : n.startsWith("device:") ? "uplink" : "runs-on" });
taking.add(needing); taking.add(needing);
taking.add(n); taking.add(n);
} }
+27 -1
View File
@@ -3,7 +3,7 @@ import { isIP } from "node:net";
import { and, eq, inArray } from "drizzle-orm"; import { and, eq, inArray } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { ipamEntries, integrations, dnsRecordsCache } from "../db/schema.js"; import { ipamEntries, integrations, dnsRecordsCache, networkDevices } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js"; import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js"; import { recordAudit } from "../services/audit.js";
import { asyncHandler } from "../utils/asyncHandler.js"; import { asyncHandler } from "../utils/asyncHandler.js";
@@ -290,6 +290,32 @@ ipamRouter.post("/sync-proxmox", requireRole("operator"), asyncHandler(async (re
res.json({ added, updated, skipped, skippedIps, errors }); res.json({ added, updated, skipped, skippedIps, errors });
})); }));
ipamRouter.post("/sync-unifi", requireRole("operator"), asyncHandler(async (req, res) => {
const controllers = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "unifi"), eq(integrations.enabled, true)));
if (controllers.length === 0) {
return res.status(400).json({ error: "no_unifi_integration" });
}
let added = 0;
let updated = 0;
let skipped = 0;
const skippedIps: string[] = [];
// What was last read from the controllers (the page's own copy), not a new call: a device is as current as the Network devices page says.
for (const d of await db.select().from(networkDevices)) {
if (!d.ip) continue;
const kind = d.kind.replace("_", " ");
const notes = [`${kind}${d.model ? `, ${d.model}` : ""}`, d.mac ? `MAC ${d.mac}` : null].filter((v): v is string => !!v).join(" — ");
const result = await upsertSyncedEntry(d.ip, d.name, "UniFi", notes, d.siteName && d.siteName !== "Default" ? d.siteName : null, "unifi");
if (result === "added") added++;
else if (result === "updated") updated++;
else {
skipped++;
skippedIps.push(d.ip);
}
}
await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_unifi", detail: { added, updated, skipped } });
res.json({ added, updated, skipped, skippedIps, errors: [] });
}));
ipamRouter.post("/sync-phpipam", requireRole("operator"), asyncHandler(async (req, res) => { ipamRouter.post("/sync-phpipam", requireRole("operator"), asyncHandler(async (req, res) => {
const phpIpamIntegrations = await db const phpIpamIntegrations = await db
.select() .select()
+14
View File
@@ -0,0 +1,14 @@
import { Router } from "express";
import { requireAuth } from "../auth/middleware.js";
import { buildMyWork } from "../services/myWork.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const myWorkRouter = Router();
myWorkRouter.use(requireAuth);
// What the signed-in person has taken on. Only ever their own: the answer is worked out from who is asking.
myWorkRouter.get("/", asyncHandler(async (req, res) => {
const user = req.currentUser!;
res.json(await buildMyWork({ id: user.id, name: user.name ?? null, email: user.email ?? null, oidcSub: user.oidcSub }));
}));
+17 -2
View File
@@ -2,7 +2,7 @@ import { Router } from "express";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { integrations, networkDevices, networkSegments } from "../db/schema.js"; import { integrations, networkDevices, networkSegments, networkServerLinks, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js"; import { requireAuth, requireRole } from "../auth/middleware.js";
import { invalidateAlertsCache } from "../services/alerts.js"; import { invalidateAlertsCache } from "../services/alerts.js";
import { dependentsOf, loadGraph, needsOfNode, nodeKey } from "../services/dependencies.js"; import { dependentsOf, loadGraph, needsOfNode, nodeKey } from "../services/dependencies.js";
@@ -19,17 +19,31 @@ networkRouter.use(requireAuth);
* names. Everyone signed in can see it (it is the same picture the dependency map and the alerts draw on); only starting a fresh read needs more. * names. Everyone signed in can see it (it is the same picture the dependency map and the alerts draw on); only starting a fresh read needs more.
*/ */
networkRouter.get("/", asyncHandler(async (_req, res) => { networkRouter.get("/", asyncHandler(async (_req, res) => {
const [intRows, devices, segments, statuses, graph, silenced] = await Promise.all([ const [intRows, devices, segments, statuses, graph, silenced, linkRows, serverRows] = await Promise.all([
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "unifi")), db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "unifi")),
db.select().from(networkDevices), db.select().from(networkDevices),
db.select().from(networkSegments), db.select().from(networkSegments),
syncStatuses(), syncStatuses(),
loadGraph(), loadGraph(),
activeSubjects(), activeSubjects(),
db.select().from(networkServerLinks),
db.select({ id: servers.id, name: servers.name }).from(servers),
]); ]);
const serverName = new Map(serverRows.map((s) => [s.id, s.name]));
const intName = new Map(intRows.map((i) => [i.id, i.name])); const intName = new Map(intRows.map((i) => [i.id, i.name]));
const byExternal = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d])); const byExternal = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d]));
// The servers plugged into each device, by what the controller says is connected (see unifiSync.matchClientsToServers).
const plugged = new Map<number, { serverId: number; serverName: string; port: number | null; wired: boolean }[]>();
const serverLinks: { serverId: number; serverName: string; deviceId: number; deviceName: string; port: number | null; wired: boolean }[] = [];
for (const l of linkRows) {
const device = byExternal.get(`${l.integrationId}:${l.deviceExternalId}`);
const name = serverName.get(l.serverId);
if (!device || !name) continue;
plugged.set(device.id, [...(plugged.get(device.id) ?? []), { serverId: l.serverId, serverName: name, port: l.port, wired: l.wired }]);
serverLinks.push({ serverId: l.serverId, serverName: name, deviceId: device.id, deviceName: device.name, port: l.port, wired: l.wired });
}
res.json({ res.json({
serverLinks,
integrations: intRows.map((i) => ({ id: i.id, name: i.name, enabled: i.enabled, status: statuses[i.id] ?? null })), integrations: intRows.map((i) => ({ id: i.id, name: i.name, enabled: i.enabled, status: statuses[i.id] ?? null })),
devices: devices devices: devices
.map((d) => { .map((d) => {
@@ -57,6 +71,7 @@ networkRouter.get("/", asyncHandler(async (_req, res) => {
dependents: dependentsOf(graph.edges, key).length, dependents: dependentsOf(graph.edges, key).length,
needs: needsOfNode(graph.edges, key).length, needs: needsOfNode(graph.edges, key).length,
inMaintenance: silenced.has(key), inMaintenance: silenced.has(key),
servers: (plugged.get(d.id) ?? []).sort((a, b) => a.serverName.localeCompare(b.serverName)),
}; };
}) })
.sort((a, b) => a.name.localeCompare(b.name)), .sort((a, b) => a.name.localeCompare(b.name)),
+1 -1
View File
@@ -212,7 +212,7 @@ export async function collectAlerts(): Promise<AlertsReport> {
type: origin.type, type: origin.type,
message: c.message, message: c.message,
key: c.key, key: c.key,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}` : origin.type === "unifi" ? "/network/devices" : undefined, link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : ""}` : origin.type === "unifi" ? "/network/devices" : undefined,
silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject), silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject),
}); });
} }
+16 -3
View File
@@ -11,7 +11,7 @@
*/ */
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { dependencies, integrations, networkDevices, servers } from "../db/schema.js"; import { dependencies, integrations, networkDevices, networkServerLinks, servers } from "../db/schema.js";
import { getInternalFlag } from "./settingsStore.js"; import { getInternalFlag } from "./settingsStore.js";
import { listActiveWindows } from "./maintenance.js"; import { listActiveWindows } from "./maintenance.js";
import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js"; import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js";
@@ -129,12 +129,13 @@ export interface Graph {
} }
export async function loadGraph(): Promise<Graph> { export async function loadGraph(): Promise<Graph> {
const [serverRows, intRows, depRows, parentRows, deviceRows] = await Promise.all([ const [serverRows, intRows, depRows, parentRows, deviceRows, linkRows] = await Promise.all([
db.select({ id: servers.id, name: servers.name }).from(servers), db.select({ id: servers.id, name: servers.name }).from(servers),
db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations), db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations),
db.select().from(dependencies), db.select().from(dependencies),
loadParentRows(), loadParentRows(),
db.select({ id: networkDevices.id, name: networkDevices.name, integrationId: networkDevices.integrationId, externalId: networkDevices.externalId, uplinkExternalId: networkDevices.uplinkExternalId }).from(networkDevices), db.select({ id: networkDevices.id, name: networkDevices.name, integrationId: networkDevices.integrationId, externalId: networkDevices.externalId, uplinkExternalId: networkDevices.uplinkExternalId }).from(networkDevices),
db.select({ integrationId: networkServerLinks.integrationId, serverId: networkServerLinks.serverId, deviceExternalId: networkServerLinks.deviceExternalId }).from(networkServerLinks),
]); ]);
const names = new Map<string, string>(); const names = new Map<string, string>();
for (const s of serverRows) names.set(nodeKey("server", s.id), s.name); for (const s of serverRows) names.set(nodeKey("server", s.id), s.name);
@@ -144,7 +145,8 @@ export async function loadGraph(): Promise<Graph> {
const instances = new Map<string, number[]>(); const instances = new Map<string, number[]>();
for (const i of intRows) if (i.enabled) instances.set(i.type, [...(instances.get(i.type) ?? []), i.id]); for (const i of intRows) if (i.enabled) instances.set(i.type, [...(instances.get(i.type) ?? []), i.id]);
// A device needs the one it is connected through: the controller says so, and nobody has to write it. // A device needs the one it is connected through: the controller says so, and nobody has to write it.
const uplinks = uplinkEdges(deviceRows); // And a server needs the device it is plugged into, as the controller says.
const uplinks = [...uplinkEdges(deviceRows), ...serverLinkEdges(linkRows, deviceRows)];
return { edges: buildEdges(resolveParents(parentRows), [...rows, ...uplinks], (k) => names.has(k)), names, rows, instances, intRows }; return { edges: buildEdges(resolveParents(parentRows), [...rows, ...uplinks], (k) => names.has(k)), names, rows, instances, intRows };
} }
@@ -160,6 +162,17 @@ export function uplinkEdges(devices: { id: number; integrationId: number; extern
return out; return out;
} }
/** The edges from each server to the devices it is plugged into. */
export function serverLinkEdges(links: { integrationId: number; serverId: number; deviceExternalId: string }[], devices: { id: number; integrationId: number; externalId: string }[]): DependencyEdge[] {
const idOf = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d.id]));
const out: DependencyEdge[] = [];
for (const l of links) {
const to = idOf.get(`${l.integrationId}:${l.deviceExternalId}`);
if (to !== undefined) out.push({ fromType: "server", fromId: l.serverId, toType: "device", toId: to });
}
return out;
}
/** The id of the alert about a node being down, when it has one (a server's "offline", a kind of service's "failing"). */ /** The id of the alert about a node being down, when it has one (a server's "offline", a kind of service's "failing"). */
export function alertIdOfNode(key: string, graph: Graph): string | null { export function alertIdOfNode(key: string, graph: Graph): string | null {
const m = /^(server|integration|device):(\d+)$/.exec(key); const m = /^(server|integration|device):(\d+)$/.exec(key);
+116
View File
@@ -0,0 +1,116 @@
/**
* "My work": what one person has taken on, in one place — the alerts handed to them, the acknowledgements about to run out, the maintenance windows they
* started that are about to end, and the update runs they started that are still going (or just finished). Everything here already exists elsewhere in the app;
* this only gathers the parts that have this person's name on them, and says which of them need a look soon.
*
* Who did what is recorded as a label — the person's name, or their email, or their sign-in id — so those three are what are matched.
*/
import { and, eq, gte, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { servers, updateRuns } from "../db/schema.js";
import { getAlerts } from "./alerts.js";
import { loadAcks } from "./alertAcks.js";
import { describeTarget, listActiveWindows } from "./maintenance.js";
/** An acknowledgement that runs out within this long is flagged. */
export const ACK_ENDS_SOON_MS = 24 * 3600_000;
/** A maintenance window that ends within this long is flagged. */
export const WINDOW_ENDS_SOON_MS = 2 * 3600_000;
/** A finished update run stays on the list this long, so the result is seen. */
export const RUN_KEPT_MS = 24 * 3600_000;
export interface MyWorkUser {
id: number;
name: string | null;
email: string | null;
oidcSub: string;
}
export interface MyWork {
/** Alerts that are on the Alerts page now and that this person has acknowledged or been handed, worst-first-ending first. */
alerts: {
alertId: string;
message: string;
severity: string;
source: string;
link: string | null;
note: string;
/** "handed" = somebody gave it to them (or they gave it to themselves); "acked" = they acknowledged it for nobody in particular. */
role: "handed" | "acked";
ackedBy: string;
ackedAt: string;
until: string | null;
endsSoon: boolean;
}[];
windows: { id: number; targetType: string; targetId: number; targetName: string; targetKind: string; reason: string | null; startedAt: string; endsAt: string; endsSoon: boolean }[];
updateRuns: { id: number; serverId: number; serverName: string; templateName: string; status: string; message: string | null; startedAt: string; finishedAt: string | null; running: boolean; updatesBefore: number | null; updatesAfter: number | null; rebootRequired: boolean }[];
/** How many of the above want a look: acknowledgements and windows that end soon, alerts handed to them, update runs still going. */
needsAttention: number;
}
/** The labels an action by this person may have been recorded under. */
export function labelsOf(user: MyWorkUser): string[] {
return [...new Set([user.name, user.email, user.oidcSub].filter((v): v is string => typeof v === "string" && v !== ""))];
}
export async function buildMyWork(user: MyWorkUser, now: Date = new Date()): Promise<MyWork> {
const labels = new Set(labelsOf(user));
const nowMs = now.getTime();
const report = await getAlerts(false);
const acks = await loadAcks(now);
const alerts: MyWork["alerts"] = [];
for (const a of report.alerts) {
const ack = acks.get(a.id);
if (!ack || !ack.active) continue;
const handed = ack.assignee?.id === user.id;
const acked = labels.has(ack.ackedBy);
if (!handed && !acked) continue;
alerts.push({
alertId: a.id,
message: a.message,
severity: a.severity,
source: a.source,
link: a.link,
note: ack.note,
role: handed ? "handed" : "acked",
ackedBy: ack.ackedBy,
ackedAt: ack.ackedAt,
until: ack.until,
endsSoon: ack.until !== null && Date.parse(ack.until) - nowMs <= ACK_ENDS_SOON_MS,
});
}
// What runs out first, first; then what has no end, worst first.
const SEV: Record<string, number> = { critical: 0, warning: 1, info: 2 };
alerts.sort((a, b) => (a.until === null ? Infinity : Date.parse(a.until)) - (b.until === null ? Infinity : Date.parse(b.until)) || (SEV[a.severity] ?? 3) - (SEV[b.severity] ?? 3) || a.message.localeCompare(b.message));
const windows: MyWork["windows"] = [];
for (const w of await listActiveWindows(now)) {
if (!w.createdBy || !labels.has(w.createdBy)) continue;
const target = await describeTarget(w.targetType, w.targetId);
if (!target) continue;
windows.push({ id: w.id, targetType: w.targetType, targetId: w.targetId, targetName: target.name, targetKind: target.kind, reason: w.reason, startedAt: w.startedAt, endsAt: w.endsAt, endsSoon: Date.parse(w.endsAt) - nowMs <= WINDOW_ENDS_SOON_MS });
}
windows.sort((a, b) => a.endsAt.localeCompare(b.endsAt));
const labelList = [...labels];
const runRows =
labelList.length === 0
? []
: await db
.select({ run: updateRuns, serverName: servers.name })
.from(updateRuns)
.innerJoin(servers, eq(servers.id, updateRuns.serverId))
.where(and(inArray(updateRuns.startedBy, labelList), gte(updateRuns.startedAt, new Date(nowMs - 7 * 86_400_000).toISOString())));
const runs: MyWork["updateRuns"] = [];
for (const { run, serverName } of runRows) {
const running = run.finishedAt === null;
// Still going, or finished recently enough that its result is news.
if (!running && nowMs - Date.parse(run.finishedAt!) > RUN_KEPT_MS) continue;
runs.push({ id: run.id, serverId: run.serverId, serverName, templateName: run.templateName, status: run.status, message: run.message, startedAt: run.startedAt, finishedAt: run.finishedAt, running, updatesBefore: run.updatesBefore, updatesAfter: run.updatesAfter, rebootRequired: run.rebootRequired });
}
runs.sort((a, b) => Number(b.running) - Number(a.running) || b.startedAt.localeCompare(a.startedAt));
const needsAttention = alerts.filter((a) => a.role === "handed" || a.endsSoon).length + windows.filter((w) => w.endsSoon).length + runs.filter((r) => r.running).length;
return { alerts, windows, updateRuns: runs, needsAttention };
}
+22 -2
View File
@@ -6,7 +6,7 @@
*/ */
import { and, eq, inArray } from "drizzle-orm"; import { and, eq, inArray } from "drizzle-orm";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { dnsRecordsCache, dnsZonesCache, integrations, servers } from "../db/schema.js"; import { dnsRecordsCache, dnsZonesCache, integrations, networkDevices, networkServerLinks, servers } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js"; import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import { getSettings } from "./settingsStore.js"; import { getSettings } from "./settingsStore.js";
@@ -17,7 +17,7 @@ export type MapStatus = "ok" | "bad" | "warn" | "unknown";
export interface MapNode { export interface MapNode {
id: string; id: string;
kind: "host" | "server" | "dns" | "monitor"; kind: "host" | "server" | "dns" | "monitor" | "device";
label: string; label: string;
sub: string | null; sub: string | null;
status: MapStatus; status: MapStatus;
@@ -91,6 +91,26 @@ export async function buildTopology(now: Date = new Date()): Promise<MapData> {
} }
} }
// The switches and access points servers are plugged into, as a UniFi controller says. Only devices with a server on them are drawn: the rest of the
// network is on the dependency map.
const links = await db.select().from(networkServerLinks);
if (links.length > 0) {
const devices = await db.select().from(networkDevices);
const deviceOf = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d]));
const serverIds = new Set(serverRows.map((s) => s.id));
const drawn = new Set<number>();
for (const l of links) {
const d = deviceOf.get(`${l.integrationId}:${l.deviceExternalId}`);
if (!d || !serverIds.has(l.serverId)) continue;
if (!drawn.has(d.id)) {
drawn.add(d.id);
const status: MapStatus = d.state === "online" ? "ok" : d.state === "offline" ? "bad" : d.state === "updating" ? "warn" : "unknown";
nodes.push({ id: `device:${d.id}`, kind: "device", label: d.name, sub: [d.kind.replace("_", " "), d.model].filter(Boolean).join(" · "), status, href: "/network/devices" });
}
if (!edges.some((e) => e.from === `device:${d.id}` && e.to === `server:${l.serverId}`)) edges.push({ from: `device:${d.id}`, to: `server:${l.serverId}` });
}
}
// DNS names that point at a server's own address. // DNS names that point at a server's own address.
const serversByIp = new Map<string, number[]>(); const serversByIp = new Map<string, number[]>();
for (const s of serverRows) for (const ip of parseIps(s.ipAddresses)) serversByIp.set(ip, [...(serversByIp.get(ip) ?? []), s.id]); for (const s of serverRows) for (const ip of parseIps(s.ipAddresses)) serversByIp.set(ip, [...(serversByIp.get(ip) ?? []), s.id]);
+47 -2
View File
@@ -7,9 +7,9 @@
*/ */
import { and, eq, inArray, or } from "drizzle-orm"; import { and, eq, inArray, or } from "drizzle-orm";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { dependencies, integrations, networkDevices, networkSegments } from "../db/schema.js"; import { dependencies, integrations, networkDevices, networkSegments, networkServerLinks, servers } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUnifiAdapter, type UnifiDevice, type UnifiInventory } from "../integrations/unifi/adapter.js"; import { createUnifiAdapter, type UnifiClient, type UnifiDevice, type UnifiInventory } from "../integrations/unifi/adapter.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js"; import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 5 * 60_000; export const SYNC_INTERVAL_MS = 5 * 60_000;
@@ -39,6 +39,43 @@ export function trackOffline(previous: { offlineSince: string | null; lastOnline
return { offlineSince: previous?.offlineSince ?? null, lastOnlineAt }; return { offlineSince: previous?.offlineSince ?? null, lastOnlineAt };
} }
export interface ServerLink {
serverId: number;
deviceExternalId: string;
clientMac: string;
port: number | null;
wired: boolean;
}
/**
* Which servers are plugged into which device: a client the controller lists whose IP address is one of a server's own. Only an exact, unambiguous address counts
* (an address two servers both report matches neither), and only a client whose switch or access point is a device that is known. Pure.
*/
export function matchClientsToServers(clients: UnifiClient[], serverRows: { id: number; ipAddresses: string | null }[], deviceMacs: Set<string>): ServerLink[] {
const owners = new Map<string, number[]>();
for (const s of serverRows) {
let ips: unknown = [];
try {
ips = s.ipAddresses ? JSON.parse(s.ipAddresses) : [];
} catch {
// a malformed list matches nothing
}
for (const ip of Array.isArray(ips) ? ips : []) if (typeof ip === "string") owners.set(ip, [...new Set([...(owners.get(ip) ?? []), s.id])]);
}
const out: ServerLink[] = [];
const seen = new Set<string>();
for (const c of clients) {
if (!c.ip || !c.uplinkExternalId || !deviceMacs.has(c.uplinkExternalId)) continue;
const who = owners.get(c.ip);
if (!who || who.length !== 1) continue;
const key = `${who[0]}|${c.mac}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ serverId: who[0], deviceExternalId: c.uplinkExternalId, clientMac: c.mac, port: c.port, wired: c.wired });
}
return out;
}
async function readStatuses(): Promise<Record<string, SyncStatus>> { async function readStatuses(): Promise<Record<string, SyncStatus>> {
try { try {
const raw = await getInternalFlag(STATUS_FLAG); const raw = await getInternalFlag(STATUS_FLAG);
@@ -91,6 +128,13 @@ export async function storeInventory(integrationId: number, inventory: UnifiInve
const gone = existing.filter((r) => !seen.has(r.externalId)).map((r) => r.id); const gone = existing.filter((r) => !seen.has(r.externalId)).map((r) => r.id);
if (gone.length > 0) await db.delete(networkDevices).where(inArray(networkDevices.id, gone)); if (gone.length > 0) await db.delete(networkDevices).where(inArray(networkDevices.id, gone));
// Which servers are plugged into which device. A controller that listed no clients at all (a key that may not read them) says nothing, so what was known stays.
if (inventory.clients.length > 0) {
const links = matchClientsToServers(inventory.clients, await db.select({ id: servers.id, ipAddresses: servers.ipAddresses }).from(servers), new Set(inventory.devices.map((d) => d.externalId)));
await db.delete(networkServerLinks).where(eq(networkServerLinks.integrationId, integrationId));
if (links.length > 0) await db.insert(networkServerLinks).values(links.map((l) => ({ integrationId, ...l, updatedAt: nowIso })));
}
const segments: (typeof networkSegments.$inferInsert)[] = [ const segments: (typeof networkSegments.$inferInsert)[] = [
...inventory.networks.map((n) => ({ integrationId, kind: "network" as const, externalId: n.externalId, siteName: n.siteName, name: n.name, enabled: n.enabled, vlanId: n.vlanId, subnet: n.subnet, purpose: n.purpose, security: null, networkName: null, updatedAt: nowIso })), ...inventory.networks.map((n) => ({ integrationId, kind: "network" as const, externalId: n.externalId, siteName: n.siteName, name: n.name, enabled: n.enabled, vlanId: n.vlanId, subnet: n.subnet, purpose: n.purpose, security: null, networkName: null, updatedAt: nowIso })),
...inventory.ssids.map((s) => ({ integrationId, kind: "ssid" as const, externalId: s.externalId, siteName: s.siteName, name: s.name, enabled: s.enabled, vlanId: s.vlanId, subnet: null, purpose: null, security: s.security, networkName: s.networkName, updatedAt: nowIso })), ...inventory.ssids.map((s) => ({ integrationId, kind: "ssid" as const, externalId: s.externalId, siteName: s.siteName, name: s.name, enabled: s.enabled, vlanId: s.vlanId, subnet: null, purpose: null, security: s.security, networkName: s.networkName, updatedAt: nowIso })),
@@ -140,6 +184,7 @@ export async function removeIntegrationData(integrationId: number): Promise<void
await db.delete(networkDevices).where(inArray(networkDevices.id, ids)); await db.delete(networkDevices).where(inArray(networkDevices.id, ids));
} }
await db.delete(networkSegments).where(eq(networkSegments.integrationId, integrationId)); await db.delete(networkSegments).where(eq(networkSegments.integrationId, integrationId));
await db.delete(networkServerLinks).where(eq(networkServerLinks.integrationId, integrationId));
const all = await readStatuses(); const all = await readStatuses();
if (String(integrationId) in all) { if (String(integrationId) in all) {
delete all[String(integrationId)]; delete all[String(integrationId)];
+2 -1
View File
@@ -27,7 +27,8 @@ const { buildDigest } = await import("../src/services/weeklyDigest.js");
await runMigrations(); await runMigrations();
const NOW = new Date("2026-10-17T12:00:00Z"); // The routes read the real clock, so the fixtures are laid out from it: a fixed date made these tests fail once enough days had passed.
const NOW = new Date(Math.floor(Date.now() / 1000) * 1000); // whole seconds, as snapshot times are
const HOUR = 3600_000; const HOUR = 3600_000;
const guest = (vmid: number, name: string, type: "qemu" | "lxc" = "qemu", node = "pve1") => ({ vmid, name, node, type, status: "running", cpu: null, maxmem: null, mem: null, uptime: null }); const guest = (vmid: number, name: string, type: "qemu" | "lxc" = "qemu", node = "pve1") => ({ vmid, name, node, type, status: "running", cpu: null, maxmem: null, mem: null, uptime: null });
const allJob = { id: "j1", enabled: true, schedule: "02:00", storage: "pbs", node: null, allGuests: true, vmids: null, exclude: null }; const allJob = { id: "j1", enabled: true, schedule: "02:00", storage: "pbs", node: null, allGuests: true, vmids: null, exclude: null };
+1 -1
View File
@@ -168,7 +168,7 @@ describe("through the report, the alerts, the figures and the page", () => {
const services = alerts.find((a) => a.id.startsWith("services:failed-units")); const services = alerts.find((a) => a.id.startsWith("services:failed-units"));
assert.ok(services, JSON.stringify(alerts.map((a) => a.id))); assert.ok(services, JSON.stringify(alerts.map((a) => a.id)));
assert.equal(services.category, "services"); assert.equal(services.category, "services");
assert.equal(services.link, `/servers/${id}`); assert.equal(services.link, `/servers/${id}?view=health`, "it opens the Health section of the server page");
assert.equal(services.silenced, false); assert.equal(services.silenced, false);
const disk = alerts.find((a) => a.id.startsWith("disk:smart")); const disk = alerts.find((a) => a.id.startsWith("disk:smart"));
assert.ok(disk && disk.severity === "critical", "a failing disk is critical, in the disk category"); assert.ok(disk && disk.severity === "critical", "a failing disk is critical, in the disk category");
+143
View File
@@ -0,0 +1,143 @@
/**
* "My work": what has one person's name on it — alerts handed to them or acknowledged by them, their maintenance windows, their update runs — and which of those
* are about to run out.
*
* 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-mywork-"));
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, updateRuns } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { setAck } = await import("../src/services/alertAcks.js");
const { startOrExtendWindow } = await import("../src/services/maintenance.js");
const { invalidateAlertsCache } = await import("../src/services/alerts.js");
const { buildMyWork, labelsOf } = await import("../src/services/myWork.js");
const { myWorkRouter } = await import("../src/routes/myWork.js");
await runMigrations();
const HOUR = 3600_000;
let app: Server;
let base = "";
let who = "olga";
const ids: Record<string, number> = {};
const olga = { id: 0, name: "Olga", email: "olga@example.lan", oidcSub: "olga" };
before(async () => {
const rows = await db
.insert(users)
.values([
{ oidcSub: "ada", name: "Ada", role: "admin" },
{ oidcSub: "olga", name: "Olga", email: "olga@example.lan", role: "operator" },
{ oidcSub: "vic", name: "Vic", role: "viewer" },
])
.returning({ id: users.id, oidcSub: users.oidcSub });
for (const r of rows) ids[r.oidcSub] = r.id;
olga.id = ids.olga;
// four servers that have stopped reporting: four standing alerts
for (const name of ["web", "db", "nas", "pi"]) {
ids[name] = (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, lastSeenAt: new Date(Date.now() - 6 * HOUR).toISOString() }).returning({ id: servers.id }))[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/my-work", myWorkRouter);
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/my-work`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
const alertOf = (name: string) => `offline:offline:server:${ids[name]}`;
describe("my work", () => {
test("the labels a person's actions are recorded under are their name, email and sign-in id", () => {
assert.deepEqual(labelsOf(olga).sort(), ["Olga", "olga", "olga@example.lan"].sort());
assert.deepEqual(labelsOf({ id: 1, name: null, email: null, oidcSub: "x" }), ["x"]);
});
test("nothing has their name on it: nothing is listed", async () => {
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual([mine.alerts.length, mine.windows.length, mine.updateRuns.length, mine.needsAttention], [0, 0, 0, 0]);
});
test("alerts handed to them, or acknowledged by them, and nobody else's; the one that runs out first is first", async () => {
await setAck({ alertId: alertOf("web"), note: "Looking at the PSU", assigneeId: ids.olga, hours: 72, actor: "Ada" });
await setAck({ alertId: alertOf("db"), note: "Waiting for the disk", assigneeId: null, hours: 4, actor: "Olga" });
await setAck({ alertId: alertOf("nas"), note: "Not mine", assigneeId: ids.ada, hours: 2, actor: "Ada" });
await setAck({ alertId: alertOf("pi"), note: "", assigneeId: ids.olga, hours: null, actor: "Olga" });
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual(
mine.alerts.map((a) => [a.alertId, a.role, a.endsSoon]),
[
[alertOf("db"), "acked", true],
[alertOf("web"), "handed", false],
[alertOf("pi"), "handed", false],
],
"ending in 4 hours, in 3 days, and never; the one for Ada is not here",
);
assert.equal(mine.alerts[0].note, "Waiting for the disk");
// handed to me (2) + one that runs out within a day (1, which is not also handed to me)
assert.equal(mine.needsAttention, 3);
});
test("a maintenance window they started, that ends soon; one that was started by somebody else is not theirs", async () => {
await startOrExtendWindow("server", ids.web, 45, "PSU swap", "Olga");
await startOrExtendWindow("server", ids.db, 600, "Disk replacement", "Olga");
await startOrExtendWindow("server", ids.nas, 30, "Somebody else's", "Ada");
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual(mine.windows.map((w) => [w.targetName, w.endsSoon, w.reason]), [["web", true, "PSU swap"], ["db", false, "Disk replacement"]], "the one that ends first first");
assert.equal(mine.needsAttention, 4);
});
test("update runs they started that are still going, or finished within a day; an older one, and somebody else's, are not listed", async () => {
const run = (serverId: number, startedBy: string, startedAt: Date, finishedAt: Date | null, status: string) =>
db.insert(updateRuns).values({ serverId, integrationId: 1, projectId: 1, templateId: 1, templateName: "Apply updates", hostLimit: "x", status, startedBy, startedAt: startedAt.toISOString(), finishedAt: finishedAt ? finishedAt.toISOString() : null, updatesBefore: 6, updatesAfter: finishedAt ? 0 : null });
const now = Date.now();
await run(ids.web, "Olga", new Date(now - 10 * 60_000), null, "running");
await run(ids.db, "Olga", new Date(now - 5 * HOUR), new Date(now - 4 * HOUR), "done");
await run(ids.nas, "Olga", new Date(now - 3 * 24 * HOUR), new Date(now - 3 * 24 * HOUR + HOUR), "done");
await run(ids.pi, "Ada", new Date(now - 10 * 60_000), null, "running");
const mine = await buildMyWork(olga);
assert.deepEqual(mine.updateRuns.map((r) => [r.serverName, r.running]), [["web", true], ["db", false]], "the running one first");
assert.equal(mine.needsAttention, 5);
});
test("over the route: only the signed-in person's own", async () => {
who = "olga";
const body = (await (await fetch(base)).json()) as any;
assert.equal(body.alerts.length, 3);
assert.equal(body.windows.length, 2);
who = "vic";
const vic = (await (await fetch(base)).json()) as any;
assert.deepEqual([vic.alerts.length, vic.windows.length, vic.updateRuns.length, vic.needsAttention], [0, 0, 0, 0]);
});
});
+1 -1
View File
@@ -42,7 +42,7 @@ const px = (guests: ReturnType<typeof guest>[]) => [{ integrationId: 1, integrat
const snapAgo = (now: number, vmid: number, hours: number) => ({ backupType: "vm", backupId: String(vmid), backupTime: Math.floor((now - hours * HOUR) / 1000), verification: "ok" as const }); const snapAgo = (now: number, vmid: number, hours: number) => ({ backupType: "vm", backupId: String(vmid), backupTime: Math.floor((now - hours * HOUR) / 1000), verification: "ok" as const });
describe("when a guest is stale", () => { describe("when a guest is stale", () => {
const NOW = new Date("2026-10-17T12:00:00Z"); const NOW = new Date(); // the real clock: the routes under test read it too
const now = NOW.getTime(); const now = NOW.getTime();
const input = (hoursAgo: number, extra: { servers?: Parameters<typeof buildCoverage>[0]["servers"]; staleHours?: number } = {}) => ({ const input = (hoursAgo: number, extra: { servers?: Parameters<typeof buildCoverage>[0]["servers"]; staleHours?: number } = {}) => ({
proxmox: px([guest(100, "web")]), proxmox: px([guest(100, "web")]),
+103 -5
View File
@@ -20,12 +20,14 @@ process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default; const express = (await import("express")).default;
const { db } = await import("../src/db/client.js"); const { db } = await import("../src/db/client.js");
const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, dependencies, maintenanceWindows } = await import("../src/db/schema.js"); const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, networkServerLinks, ipamEntries, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js"); const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js"); const { encryptSecret } = await import("../src/crypto.js");
const adapterModule = await import("../src/integrations/unifi/adapter.js"); const adapterModule = await import("../src/integrations/unifi/adapter.js");
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy } = adapterModule; const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy, clientFromApi, clientFromLegacy } = adapterModule;
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses } = await import("../src/services/unifiSync.js"); const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses, matchClientsToServers } = await import("../src/services/unifiSync.js");
const { buildTopology } = await import("../src/services/topology.js");
const { ipamRouter } = await import("../src/routes/ipam.js");
const { evaluateHealth } = await import("../src/services/healthMonitor.js"); const { evaluateHealth } = await import("../src/services/healthMonitor.js");
const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js"); const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js");
const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js"); const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js");
@@ -69,6 +71,21 @@ const wifiList = {
], ],
}; };
const clientList = {
offset: 0,
limit: 200,
count: 3,
totalCount: 3,
data: [
{ id: "c1", type: "WIRED", name: "web", ipAddress: "192.168.1.50", macAddress: "aa:bb:cc:00:00:50", uplinkDeviceId: "d-sw" },
{ id: "c2", type: "WIRELESS", name: "phone", ipAddress: "192.168.1.60", macAddress: "aa:bb:cc:00:00:60", uplinkDeviceId: "d-ap" },
{ id: "c3", type: "WIRED", name: "stranger", ipAddress: "192.168.1.99", macAddress: "aa:bb:cc:00:00:99", uplinkDeviceId: "d-gone" },
],
};
const legacyClients = [
{ mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", hostname: "web", is_wired: true, sw_mac: "00:11:22:33:44:02", sw_port: 7 },
{ mac: "aa:bb:cc:00:00:60", ip: "192.168.1.60", name: "phone", is_wired: false, ap_mac: "00:11:22:33:44:03" },
];
const legacyDevices = [ const legacyDevices = [
{ _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false }, { _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false },
{ _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } }, { _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } },
@@ -93,6 +110,7 @@ function handleApi(url: URL, res: ServerResponse, strip: string) {
const path = url.pathname.slice(strip.length); const path = url.pathname.slice(strip.length);
const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path); const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path);
if (path === "/sites") return reply(res, 200, siteList); if (path === "/sites") return reply(res, 200, siteList);
if (path === "/sites/site-1/clients") return reply(res, 200, clientList);
if (!m) return reply(res, 404, { message: "no such endpoint" }); if (!m) return reply(res, 404, { message: "no such endpoint" });
if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList); if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList);
if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList); if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList);
@@ -103,6 +121,7 @@ function handleLegacy(url: URL, res: ServerResponse, strip: string) {
const path = url.pathname.slice(strip.length); const path = url.pathname.slice(strip.length);
if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] }); if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] });
if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices }); if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices });
if (path === "/api/s/default/stat/sta") return reply(res, 200, { data: legacyClients });
if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks }); if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks });
if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans }); if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans });
return reply(res, 404, {}); return reply(res, 404, {});
@@ -206,6 +225,23 @@ describe("normalising what a controller says", () => {
}); });
}); });
describe("what is connected where", () => {
test("a client from either API: its address, whether it is wired, and the device it is on (and the port, on the classic one)", () => {
const macById = new Map([["d-sw", MAC.sw]]);
assert.deepEqual(clientFromApi(clientList.data[0], macById, "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: null, siteName: "Default" });
assert.equal(clientFromApi(clientList.data[2], macById, "Default")!.uplinkExternalId, null, "an unknown device is no uplink");
assert.deepEqual(clientFromLegacy(legacyClients[0], "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: 7, siteName: "Default" });
assert.deepEqual([clientFromLegacy(legacyClients[1], "Default")!.wired, clientFromLegacy(legacyClients[1], "Default")!.uplinkExternalId], [false, MAC.ap]);
});
test("a server is plugged into a device only by an exact, unambiguous address on a device that is known", () => {
const servers = [{ id: 1, ipAddresses: JSON.stringify(["10.0.0.1", "10.0.0.2"]) }, { id: 2, ipAddresses: JSON.stringify(["10.0.0.2", "10.0.0.3"]) }, { id: 3, ipAddresses: "not json" }, { id: 4, ipAddresses: null }];
const c = (mac: string, ip: string | null, up: string | null) => ({ mac, ip, name: null, wired: true, uplinkExternalId: up, port: 3, siteName: "Default" });
const links = matchClientsToServers([c("m1", "10.0.0.1", MAC.sw), c("m2", "10.0.0.2", MAC.sw), c("m3", "10.0.0.3", MAC.ap), c("m4", "10.0.0.1", "ff:ff:ff:ff:ff:ff"), c("m5", null, MAC.sw), c("m1", "10.0.0.1", MAC.sw)], servers, new Set([MAC.sw, MAC.ap]));
assert.deepEqual(links.map((l) => [l.serverId, l.deviceExternalId, l.clientMac]), [[1, MAC.sw, "m1"], [2, MAC.ap, "m3"]], "10.0.0.2 belongs to two servers, so to neither; an unknown device and no address count for nothing; a repeat is one link");
});
});
describe("reading a controller", () => { describe("reading a controller", () => {
const cfg = (extra: Record<string, unknown>) => ({ url: controllerUrl, ...extra }) as never; const cfg = (extra: Record<string, unknown>) => ({ url: controllerUrl, ...extra }) as never;
@@ -321,7 +357,7 @@ describe("a controller in the database", () => {
const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning(); const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning();
const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning(); const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning();
integrationId = row.id; integrationId = row.id;
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id; webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString(), ipAddresses: JSON.stringify(["192.168.1.50"]) }).returning({ id: servers.id }))[0].id;
}); });
test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => { test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => {
@@ -361,6 +397,33 @@ describe("a controller in the database", () => {
assert.equal((await syncUnifiIntegration(integrationId)).ok, true); assert.equal((await syncUnifiIntegration(integrationId)).ok, true);
}); });
test("the server whose address is on the controller's client list is plugged into the switch the controller says, and needs it", async () => {
const links = await db.select().from(networkServerLinks);
assert.equal(links.length, 1, "the phone and the stranger match no server");
assert.deepEqual([links[0].serverId, links[0].deviceExternalId, links[0].wired, links[0].clientMac], [webId, MAC.sw, true, "aa:bb:cc:00:00:50"]);
const graph = await loadGraph();
assert.ok(graph.edges.get(`server:${webId}`)?.includes(`device:${swId}`));
// the switch is down: the server (offline too) is explained by it, with nothing written by hand
const cover = await dependencyCover([webId], [], [swId]);
assert.equal(cover.cause.get(`server:${webId}`), `device:${swId}`);
});
test("a controller that lists no clients says nothing, so what was known stays", async () => {
const [row] = await db.select().from(integrations);
const before = (await db.select().from(networkServerLinks)).length;
const { storeInventory } = await import("../src/services/unifiSync.js");
await storeInventory(row.id, { mode: "api_key", sites: ["Default"], devices: [], networks: [], ssids: [], clients: [] });
assert.equal((await db.select().from(networkServerLinks)).length, before);
assert.equal((await db.select().from(networkDevices)).length, 0, "the devices, on the other hand, are gone from it");
assert.equal((await syncUnifiIntegration(row.id)).ok, true, "and come back on the next read");
// device ids are new now: look them up again
const rows = await db.select().from(networkDevices);
gwId = rows.find((r) => r.name === "Gateway")!.id;
swId = rows.find((r) => r.name === "Rack switch")!.id;
apId = rows.find((r) => r.name === "Hallway AP")!.id;
await db.delete(dependencies);
});
test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => { test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => {
const graph = await loadGraph(); const graph = await loadGraph();
assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]); assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]);
@@ -433,6 +496,15 @@ describe("a controller in the database", () => {
invalidateAlertsCache(); invalidateAlertsCache();
}); });
test("the Connections map draws a device that has a server on it, with its state", async () => {
const map = await buildTopology();
const sw = map.nodes.find((n) => n.kind === "device");
assert.ok(sw, "the switch is on the map");
assert.deepEqual([sw!.label, sw!.status, sw!.href], ["Rack switch", "ok", "/network/devices"]);
assert.ok(map.edges.some((e) => e.from === sw!.id && e.to === `server:${webId}`));
assert.equal(map.nodes.filter((n) => n.kind === "device").length, 1, "the access point and gateway have no server on them");
});
describe("the page's data", () => { describe("the page's data", () => {
let app: Server; let app: Server;
let base = ""; let base = "";
@@ -459,7 +531,9 @@ describe("a controller in the database", () => {
const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d])); const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d]));
assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]); assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]);
assert.equal(by["Hallway AP"].state, "offline"); assert.equal(by["Hallway AP"].state, "offline");
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind them"); assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind it");
assert.deepEqual(by["Rack switch"].servers.map((x: any) => [x.serverName, x.port, x.wired]), [["web", null, true]]);
assert.deepEqual(body.serverLinks.map((l: any) => [l.serverName, l.deviceName]), [["web", "Rack switch"]]);
assert.equal(by["Hallway AP"].needs, 2); assert.equal(by["Hallway AP"].needs, 2);
assert.equal(by["Rack switch"].inMaintenance, true); assert.equal(by["Rack switch"].inMaintenance, true);
assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]); assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
@@ -468,6 +542,29 @@ describe("a controller in the database", () => {
assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE)); assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE));
}); });
test("the devices' addresses can be added to the IP addresses, and a hand-made entry is left alone", async () => {
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "operator" } };
next();
});
a.use("/api/ipam", ipamRouter);
const s = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
const ipam = `http://127.0.0.1:${(s.address() as AddressInfo).port}/api/ipam/sync-unifi`;
await db.insert(ipamEntries).values({ ipAddress: "192.168.1.3", label: "mine" });
const res = await fetch(ipam, { method: "POST" });
const body = (await res.json()) as any;
assert.deepEqual([body.added, body.skipped, body.skippedIps], [2, 1, ["192.168.1.3"]]);
const rows = await db.select().from(ipamEntries);
assert.deepEqual(rows.find((r) => r.ipAddress === "192.168.1.2")!.label, "Rack switch");
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.3")!.label, "mine");
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.1")!.source, "unifi");
s.close();
});
test("reading again needs an operator", async () => { test("reading again needs an operator", async () => {
who = "viewer"; who = "viewer";
assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403); assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403);
@@ -484,6 +581,7 @@ describe("a controller in the database", () => {
await removeIntegrationData(integrationId); await removeIntegrationData(integrationId);
assert.equal((await db.select().from(networkDevices)).length, 0); assert.equal((await db.select().from(networkDevices)).length, 0);
assert.equal((await db.select().from(networkSegments)).length, 0); assert.equal((await db.select().from(networkSegments)).length, 0);
assert.equal((await db.select().from(networkServerLinks)).length, 0);
assert.equal((await db.select().from(dependencies)).length, 0); assert.equal((await db.select().from(dependencies)).length, 0);
assert.equal((await syncStatuses())[integrationId], undefined); assert.equal((await syncStatuses())[integrationId], undefined);
}); });
+2
View File
@@ -7,6 +7,7 @@ import Users from "./pages/Users";
import Secrets from "./pages/Secrets"; import Secrets from "./pages/Secrets";
import Ipam from "./pages/Ipam"; import Ipam from "./pages/Ipam";
import NetworkDevices from "./pages/NetworkDevices"; import NetworkDevices from "./pages/NetworkDevices";
import MyWorkPage from "./pages/MyWork";
import Ports from "./pages/Ports"; import Ports from "./pages/Ports";
import Dns from "./pages/Dns"; import Dns from "./pages/Dns";
import Servers from "./pages/Servers"; import Servers from "./pages/Servers";
@@ -134,6 +135,7 @@ function Shelled({ user }: { user: CurrentUser }) {
<AppShell user={user}> <AppShell user={user}>
<Routes> <Routes>
<Route path="/" element={<Dashboard user={user} />} /> <Route path="/" element={<Dashboard user={user} />} />
<Route path="/my-work" element={<MyWorkPage user={user} />} />
<Route path="/map" element={<MapPage user={user} />} /> <Route path="/map" element={<MapPage user={user} />} />
<Route path="/servers" element={<Servers user={user} />} /> <Route path="/servers" element={<Servers user={user} />} />
<Route path="/servers/compare" element={<ServerCompare />} /> <Route path="/servers/compare" element={<ServerCompare />} />
+17 -1
View File
@@ -276,7 +276,7 @@ export interface SecretInput {
export interface MapNode { export interface MapNode {
id: string; id: string;
kind: "host" | "server" | "dns" | "monitor"; kind: "host" | "server" | "dns" | "monitor" | "device";
label: string; label: string;
sub: string | null; sub: string | null;
status: "ok" | "bad" | "warn" | "unknown"; status: "ok" | "bad" | "warn" | "unknown";
@@ -1156,6 +1156,14 @@ export interface DependenciesResponse {
nodes: DependencyNode[]; nodes: DependencyNode[];
} }
/** What one person has taken on (GET /api/my-work). */
export interface MyWork {
alerts: { alertId: string; message: string; severity: string; source: string; link: string | null; note: string; role: "handed" | "acked"; ackedBy: string; ackedAt: string; until: string | null; endsSoon: boolean }[];
windows: { id: number; targetType: string; targetId: number; targetName: string; targetKind: string; reason: string | null; startedAt: string; endsAt: string; endsSoon: boolean }[];
updateRuns: { id: number; serverId: number; serverName: string; templateName: string; status: string; message: string | null; startedAt: string; finishedAt: string | null; running: boolean; updatesBefore: number | null; updatesAfter: number | null; rebootRequired: boolean }[];
needsAttention: number;
}
export type NetworkDeviceKind = "gateway" | "switch" | "access_point" | "other"; export type NetworkDeviceKind = "gateway" | "switch" | "access_point" | "other";
export type NetworkDeviceState = "online" | "offline" | "updating" | "pending" | "other"; export type NetworkDeviceState = "online" | "offline" | "updating" | "pending" | "other";
@@ -1183,6 +1191,8 @@ export interface NetworkDevice {
dependents: number; dependents: number;
needs: number; needs: number;
inMaintenance: boolean; inMaintenance: boolean;
/** The servers plugged into it, as the controller says. */
servers: { serverId: number; serverName: string; port: number | null; wired: boolean }[];
} }
/** A network (VLAN) or a Wi-Fi name a controller has set up. */ /** A network (VLAN) or a Wi-Fi name a controller has set up. */
@@ -1215,6 +1225,8 @@ export interface UnifiSyncStatus {
} }
export interface NetworkOverview { export interface NetworkOverview {
/** Which server is plugged into which device. */
serverLinks: { serverId: number; serverName: string; deviceId: number; deviceName: string; port: number | null; wired: boolean }[];
integrations: { id: number; name: string; enabled: boolean; status: UnifiSyncStatus | null }[]; integrations: { id: number; name: string; enabled: boolean; status: UnifiSyncStatus | null }[];
devices: NetworkDevice[]; devices: NetworkDevice[];
networks: NetworkSegment[]; networks: NetworkSegment[];
@@ -2223,6 +2235,9 @@ export const api = {
request<{ minSeverity: string | null; categories: AlertCategory[] | null }>(`/api/push/${id}`, { method: "PATCH", body: JSON.stringify(data) }), request<{ minSeverity: string | null; categories: AlertCategory[] | null }>(`/api/push/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
test: () => request<{ sent: number; removed: number; failed: number }>("/api/push/test", { method: "POST" }), test: () => request<{ sent: number; removed: number; failed: number }>("/api/push/test", { method: "POST" }),
}, },
myWork: {
get: () => request<MyWork>("/api/my-work"),
},
network: { network: {
overview: () => request<NetworkOverview>("/api/network"), overview: () => request<NetworkOverview>("/api/network"),
sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }), sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }),
@@ -2360,6 +2375,7 @@ export const api = {
syncTailscale: () => request<IpamSyncResult>("/api/ipam/sync-tailscale", { method: "POST" }), syncTailscale: () => request<IpamSyncResult>("/api/ipam/sync-tailscale", { method: "POST" }),
syncProxmox: () => request<IpamSyncResult>("/api/ipam/sync-proxmox", { method: "POST" }), syncProxmox: () => request<IpamSyncResult>("/api/ipam/sync-proxmox", { method: "POST" }),
syncPhpIpam: () => request<IpamSyncResult>("/api/ipam/sync-phpipam", { method: "POST" }), syncPhpIpam: () => request<IpamSyncResult>("/api/ipam/sync-phpipam", { method: "POST" }),
syncUnifi: () => request<IpamSyncResult>("/api/ipam/sync-unifi", { method: "POST" }),
}, },
generator: { generator: {
themes: () => request<{ themes: NameTheme[]; builtinIds: string[] }>("/api/generator/themes"), themes: () => request<{ themes: NameTheme[]; builtinIds: string[] }>("/api/generator/themes"),
+5
View File
@@ -22,6 +22,7 @@ import { SHOW_SHORTCUTS_EVENT, shortcutHintFor } from "../layout/shortcuts";
import { DENSITIES, type Density } from "../utils/density"; import { DENSITIES, type Density } from "../utils/density";
import { readableError } from "../utils/errors"; import { readableError } from "../utils/errors";
import { toast } from "../utils/toast"; import { toast } from "../utils/toast";
import { SETTINGS_INDEX } from "../utils/settingsIndex";
import { SHOW_SETUP_EVENT } from "./SetupGuide"; import { SHOW_SETUP_EVENT } from "./SetupGuide";
const SECRET_TYPE_LABELS: Record<SecretType, string> = { const SECRET_TYPE_LABELS: Record<SecretType, string> = {
@@ -323,6 +324,10 @@ export default function CommandPalette({
} }
items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" }); items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" });
if (user.role === "admin") { if (user.role === "admin") {
// Each setting, so "quiet hours" or "flapping" finds the place it is set.
for (const [i, s] of SETTINGS_INDEX.entries()) {
items.push({ key: `setting-${i}`, category: "Settings", title: s.title, subtitle: s.where, path: s.to, keywords: `settings ${s.words}` });
}
items.push({ items.push({
key: "act-setup", key: "act-setup",
category: "Actions", category: "Actions",
+65
View File
@@ -0,0 +1,65 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type NetworkOverview } from "../api/client";
/**
* What a server is plugged into, as a UniFi controller says (matched by the server's IP address): the switch and port, or the access point it is on over Wi-Fi.
* Says nothing when there is no UniFi controller; says so, plainly, when there is one and the server is not on its list.
*/
export default function ConnectedThrough({ serverId }: { serverId: number }) {
const [data, setData] = useState<NetworkOverview | null>(null);
useEffect(() => {
let alive = true;
api.network
.overview()
.then((res) => alive && setData(res))
.catch(() => {});
return () => {
alive = false;
};
}, []);
if (!data || data.integrations.length === 0) return null;
const mine = data.serverLinks.filter((l) => l.serverId === serverId);
const device = (id: number) => data.devices.find((d) => d.id === id);
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Connected through</h3>
<div className="card-actions">
<Link to="/network/devices" className="small">
Network devices
</Link>
</div>
</div>
<div className="card-body">
{mine.length === 0 ? (
<div className="text-secondary">
The UniFi controller does not list anything with this server&rsquo;s IP address as connected, so it is not known which switch or access point it is on. (A server is matched by an address it reports; one that is
off, or on a network the controller does not manage, will not be.)
</div>
) : (
<ul className="list-unstyled mb-0">
{mine.map((l) => {
const d = device(l.deviceId);
return (
<li key={`${l.deviceId}-${l.port ?? "x"}`} className="mb-1">
<Link to="/network/devices">{l.deviceName}</Link>
<span className="text-secondary">
{" "}
— {l.port !== null ? `port ${l.port}` : l.wired ? "wired" : "Wi-Fi"}
{d ? ` · ${d.kind.replace("_", " ")}${d.model ? `, ${d.model}` : ""}` : ""}
</span>
{d && d.state !== "online" && <span className="badge bg-red-lt text-red ms-2">{d.state === "offline" ? "offline" : d.state}</span>}
</li>
);
})}
</ul>
)}
{mine.length > 0 && <div className="text-secondary small mt-2">If it goes down, this server&rsquo;s own offline alert is folded under the device&rsquo;s.</div>}
</div>
</div>
);
}
+9 -7
View File
@@ -1,7 +1,7 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { api, type AlertCategory, type MaintenanceTargetType, type Runbook } from "../api/client"; import { api, type AlertCategory, type MaintenanceTargetType, type Runbook } from "../api/client";
import { RUNBOOKS_CHANGED } from "../hooks/useRunbooks"; import { RUNBOOKS_CHANGED } from "../hooks/useRunbooks";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors"; import { readableError } from "../utils/errors";
import { toast } from "../utils/toast"; import { toast } from "../utils/toast";
import { BlockSkeleton } from "./Skeleton"; import { BlockSkeleton } from "./Skeleton";
@@ -85,14 +85,16 @@ export default function RunbookPanel({
} }
async function remove(n: Runbook) { async function remove(n: Runbook) {
if (!(await confirmDialog({ title: "Remove runbook", message: `Remove "${n.title}"?`, confirmLabel: "Remove", danger: true }))) return; const changed = () => {
try {
await api.runbooks.remove(n.id);
load(); load();
window.dispatchEvent(new Event(RUNBOOKS_CHANGED)); window.dispatchEvent(new Event(RUNBOOKS_CHANGED));
} catch (err) { };
toast.error(readableError(err)); await removeWithUndo({
} remove: () => api.runbooks.remove(n.id),
restore: () => api.runbooks.create({ targetType: n.targetType, targetId: n.targetId, title: n.title, body: n.body, category: n.category }),
message: `Removed the runbook "${n.title}".`,
reload: changed,
});
} }
if (failed) return <div className="text-secondary">Couldn't load the runbooks.</div>; if (failed) return <div className="text-secondary">Couldn't load the runbooks.</div>;
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useSyncExternalStore } from "react";
import { api, type MyWork } from "../api/client";
/**
* What the signed-in person has taken on, shared by everything that shows it (the menu badge, the dashboard strip, the My work page), so one request every
* couple of minutes serves them all. Asked again at once when something that changes it is done (an acknowledgement, a maintenance window).
*/
let current: MyWork | null = null;
const listeners = new Set<() => void>();
let timer: ReturnType<typeof setInterval> | null = null;
let inFlight = false;
const POLL_MS = 120_000;
async function refresh(): Promise<void> {
if (inFlight) return;
inFlight = true;
try {
current = await api.myWork.get();
for (const l of listeners) l();
} catch {
// keep what there was: a failed look is not "nothing to do"
} finally {
inFlight = false;
}
}
/** Looks again now — after something was acknowledged, handed over, extended or ended. */
export function refreshMyWork(): void {
if (listeners.size > 0) void refresh();
}
if (typeof window !== "undefined") {
window.addEventListener("maintenance-changed", refreshMyWork);
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
if (listeners.size === 1) {
void refresh();
timer = setInterval(() => void refresh(), POLL_MS);
}
return () => {
listeners.delete(listener);
if (listeners.size === 0 && timer) {
clearInterval(timer);
timer = null;
}
};
}
/** The current "My work", or null until it has been read (and always null when `enabled` is false: viewers have no work to follow). */
export function useMyWork(enabled = true): { work: MyWork | null; reload: () => void } {
const work = useSyncExternalStore(
(listener) => (enabled ? subscribe(listener) : () => {}),
() => (enabled ? current : null),
);
useEffect(() => {
if (enabled) refreshMyWork();
}, [enabled]);
return { work, reload: refreshMyWork };
}
+10
View File
@@ -12,6 +12,7 @@ import { DENSITIES, getDensity, setDensity, type Density } from "../utils/densit
import CommandPalette from "../components/CommandPalette"; import CommandPalette from "../components/CommandPalette";
import { isLightColor, useEnvironment } from "../utils/environment"; import { isLightColor, useEnvironment } from "../utils/environment";
import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport"; import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport";
import { useMyWork } from "../hooks/useMyWork";
import { useStackedTables } from "../hooks/useStackedTables"; import { useStackedTables } from "../hooks/useStackedTables";
import { useShortcuts } from "../hooks/useShortcuts"; import { useShortcuts } from "../hooks/useShortcuts";
import { useFormLabels } from "../hooks/useFormLabels"; import { useFormLabels } from "../hooks/useFormLabels";
@@ -87,6 +88,8 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
const firstRoute = useRef(true); const firstRoute = useRef(true);
const breadcrumbTail = useBreadcrumbTailValue(); const breadcrumbTail = useBreadcrumbTailValue();
const { report } = useAlertsReport(); const { report } = useAlertsReport();
// Viewers have nothing to follow, so nothing is asked for them.
const { work: myWork } = useMyWork(user.role === "admin" || user.role === "operator");
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
@@ -186,6 +189,13 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
title: `${alerts.count} active alert${alerts.count === 1 ? "" : "s"}`, title: `${alerts.count} active alert${alerts.count === 1 ? "" : "s"}`,
}; };
} }
if (myWork && myWork.needsAttention > 0) {
badges["/my-work"] = {
text: String(myWork.needsAttention),
className: "bg-blue text-blue-fg",
title: `${myWork.needsAttention} ${myWork.needsAttention === 1 ? "thing" : "things"} of yours want a look: handed to you, about to run out, or still going`,
};
}
if (maintenance.length > 0) { if (maintenance.length > 0) {
badges["/maintenance"] = { badges["/maintenance"] = {
text: String(maintenance.length), text: String(maintenance.length),
+2
View File
@@ -5,6 +5,7 @@ import {
IconWorld, IconWorld,
IconNetwork, IconNetwork,
IconRouter, IconRouter,
IconChecklist,
IconKey, IconKey,
IconPlugConnected, IconPlugConnected,
IconBrandDocker, IconBrandDocker,
@@ -63,6 +64,7 @@ export const isGroup = (entry: NavEntry): entry is NavGroup => "items" in entry;
export const NAV: NavEntry[] = [ export const NAV: NavEntry[] = [
{ to: "/", label: "Dashboard", icon: <IconLayoutDashboard size={20} /> }, { to: "/", label: "Dashboard", icon: <IconLayoutDashboard size={20} /> },
{ to: "/my-work", label: "My work", icon: <IconChecklist size={20} />, minRole: "operator" },
{ {
id: "infrastructure", id: "infrastructure",
label: "Infrastructure", label: "Infrastructure",
+8 -8
View File
@@ -1,3 +1,4 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useMemo, useState, type FormEvent } from "react"; import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { api, type AdminLink, type CurrentUser, type PortEntry, type ServerRecord } from "../api/client"; import { api, type AdminLink, type CurrentUser, type PortEntry, type ServerRecord } from "../api/client";
@@ -5,7 +6,6 @@ import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh"; import SortableTh from "../components/SortableTh";
import { downloadCsv } from "../utils/csv"; import { downloadCsv } from "../utils/csv";
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl"; import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import TableToolbar from "../components/TableToolbar"; import TableToolbar from "../components/TableToolbar";
import { EmptyRow, LoadingRow } from "../components/EmptyState"; import { EmptyRow, LoadingRow } from "../components/EmptyState";
@@ -137,14 +137,14 @@ export default function AdminLinks({ user }: { user: CurrentUser }) {
} }
async function remove(link: AdminLink) { async function remove(link: AdminLink) {
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link from ${link.serverName}?`, confirmLabel: "Remove", danger: true }))) return;
setError(null); setError(null);
try { await removeWithUndo({
await api.servers.removeLink(link.serverId, link.id); remove: () => api.servers.removeLink(link.serverId, link.id),
load(); restore: () => api.servers.addLink(link.serverId, { label: link.label, url: link.url }),
} catch (err) { message: `Removed the "${link.label}" link from ${link.serverName}.`,
setError(err instanceof Error ? err.message : String(err)); reload: load,
} onError: setError,
});
} }
const showForm = adding || editing; const showForm = adding || editing;
+11 -9
View File
@@ -1,7 +1,7 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Link, useSearchParams } from "react-router-dom"; import { Link, useSearchParams } from "react-router-dom";
import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus, type CurrentUser, type RestoreInfo, type RestoreResult, type RestoreStatus, type RestoreTestEntry } from "../api/client"; import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus, type CurrentUser, type RestoreInfo, type RestoreResult, type RestoreStatus, type RestoreTestEntry } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { toast } from "../utils/toast"; import { toast } from "../utils/toast";
import Pagination from "../components/Pagination"; import Pagination from "../components/Pagination";
import SortableTh from "../components/SortableTh"; import SortableTh from "../components/SortableTh";
@@ -96,14 +96,16 @@ export default function Backups({ user }: { user?: CurrentUser }) {
} }
async function removeTest(t: RestoreTestEntry) { async function removeTest(t: RestoreTestEntry) {
if (!(await confirmDialog({ title: "Remove a restore test", message: `Remove the test of "${t.label}" from ${t.testedAt}?`, confirmLabel: "Remove", danger: true }))) return; await removeWithUndo({
try { remove: () => api.backups.removeRestoreTest(t.id),
await api.backups.removeRestoreTest(t.id); restore: () => api.backups.recordRestoreTest({ key: t.subjectKey, label: t.label, testedAt: t.testedAt, result: t.result, note: t.note ?? undefined }),
loadTests(); message: `Removed the test of "${t.label}" from ${t.testedAt}.`,
load(); reload: () => {
} catch (err) { loadTests();
setError(readableError(err)); load();
} },
onError: setError,
});
} }
const [params, setParams] = useSearchParams(); const [params, setParams] = useSearchParams();
+18
View File
@@ -1,3 +1,4 @@
import { useMyWork } from "../hooks/useMyWork";
import { isValidElement, useEffect, useState, type ReactNode } from "react"; import { isValidElement, useEffect, useState, type ReactNode } from "react";
import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react"; import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react";
import TimeAgo from "../components/TimeAgo"; import TimeAgo from "../components/TimeAgo";
@@ -324,6 +325,22 @@ function formatBytes(bytes: number | null): string {
return `${value.toFixed(1)} ${units[unit]}`; return `${value.toFixed(1)} ${units[unit]}`;
} }
/** One line above the cards for those who follow things: how many of theirs want a look, and where to see them. Says nothing when none do. */
function MyWorkStrip() {
const { work } = useMyWork();
if (!work || work.needsAttention === 0) return null;
return (
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2 py-2" role="status">
<span>
<strong>{work.needsAttention}</strong> {work.needsAttention === 1 ? "thing" : "things"} of yours {work.needsAttention === 1 ? "wants" : "want"} a look — alerts handed to you or about to run out, maintenance about to end, update runs still going.
</span>
<Link to="/my-work" className="btn btn-sm btn-primary ms-auto">
My work
</Link>
</div>
);
}
export default function Dashboard({ user }: { user: CurrentUser }) { export default function Dashboard({ user }: { user: CurrentUser }) {
const { editing } = useDashboardLayout(); const { editing } = useDashboardLayout();
const problemsFirst = useProblemsFirst(); const problemsFirst = useProblemsFirst();
@@ -687,6 +704,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
Welcome back, {user.name ?? user.email ?? user.sub}. Welcome back, {user.name ?? user.email ?? user.sub}.
</p> </p>
<StatusStrip /> <StatusStrip />
{(user.role === "admin" || user.role === "operator") && <MyWorkStrip />}
<WhatChanged role={user.role} /> <WhatChanged role={user.role} />
{isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && ( {isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && (
<SetupGuide steps={setupSteps} /> <SetupGuide steps={setupSteps} />
+45 -11
View File
@@ -1,3 +1,5 @@
import { toast } from "../utils/toast";
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom"; import { useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client"; import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client";
@@ -33,7 +35,7 @@ export default function Ipam({ user }: { user: CurrentUser }) {
const [adding, setAdding] = useState(false); const [adding, setAdding] = useState(false);
const [form, setForm] = useState<IpamInput>(emptyForm); const [form, setForm] = useState<IpamInput>(emptyForm);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | null>(null); const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | "unifi" | null>(null);
const [syncResult, setSyncResult] = useState<string | null>(null); const [syncResult, setSyncResult] = useState<string | null>(null);
const selection = useSelection<number>(); const selection = useSelection<number>();
const [bulkDeleting, setBulkDeleting] = useState(false); const [bulkDeleting, setBulkDeleting] = useState(false);
@@ -146,47 +148,76 @@ export default function Ipam({ user }: { user: CurrentUser }) {
} }
} }
/** What is needed to make an entry again; one that a sync made would come back as a hand-made one, so those are still asked about. */
const asInput = (e: IpamEntry): IpamInput => ({ ipAddress: e.ipAddress, label: e.label ?? undefined, vendor: e.vendor ?? undefined, location: e.location ?? undefined, notes: e.notes ?? undefined });
async function remove(entry: IpamEntry) { async function remove(entry: IpamEntry) {
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"?`, confirmLabel: "Delete", danger: true }))) return;
setError(null); setError(null);
try { if (entry.source) {
await api.ipam.remove(entry.id); if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"? A sync can bring it back.`, confirmLabel: "Delete", danger: true }))) return;
load(); try {
} catch (err) { await api.ipam.remove(entry.id);
setError(err instanceof Error ? err.message : String(err)); load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
return;
} }
await removeWithUndo({
remove: () => api.ipam.remove(entry.id),
restore: () => api.ipam.create(asInput(entry)),
message: `Deleted ${entry.ipAddress}.`,
reload: load,
onError: setError,
});
} }
async function bulkDelete() { async function bulkDelete() {
const ids = Array.from(selection.selected); const ids = Array.from(selection.selected);
if (ids.length === 0) return; if (ids.length === 0) return;
if (!(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}?`, confirmLabel: "Delete", danger: true }))) return; const picked = (entries ?? []).filter((e) => ids.includes(e.id));
const plain = picked.length === ids.length && picked.every((e) => !e.source);
if (!plain && !(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}? Those a sync made can be brought back by it.`, confirmLabel: "Delete", danger: true }))) return;
setError(null); setError(null);
setBulkDeleting(true); setBulkDeleting(true);
try { try {
const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id))); const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id)));
const failed = results.filter((r) => r.status === "rejected").length; const failed = results.filter((r) => r.status === "rejected").length;
if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`); if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`);
const gone = picked.filter((_, i) => results[ids.indexOf(picked[i].id)]?.status === "fulfilled");
selection.clear(); selection.clear();
load(); load();
if (plain && gone.length > 0) {
toast.success(`Deleted ${gone.length} IP address${gone.length !== 1 ? "es" : ""}.`, {
label: "Undo",
onClick: async () => {
const back = await Promise.allSettled(gone.map((e) => api.ipam.create(asInput(e))));
const lost = back.filter((r) => r.status === "rejected").length;
if (lost > 0) toast.error(`${lost} could not be put back.`);
else toast.info("Put back.");
load();
},
});
}
} finally { } finally {
setBulkDeleting(false); setBulkDeleting(false);
} }
} }
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam", string> = { const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam" | "unifi", string> = {
tailscale: "Tailscale", tailscale: "Tailscale",
proxmox: "Proxmox", proxmox: "Proxmox",
phpipam: "phpIPAM", phpipam: "phpIPAM",
unifi: "UniFi",
}; };
async function runSync(source: "tailscale" | "proxmox" | "phpipam") { async function runSync(source: "tailscale" | "proxmox" | "phpipam" | "unifi") {
setError(null); setError(null);
setSyncResult(null); setSyncResult(null);
setSyncing(source); setSyncing(source);
try { try {
const res = const res =
source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : await api.ipam.syncPhpIpam(); source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : source === "unifi" ? await api.ipam.syncUnifi() : await api.ipam.syncPhpIpam();
const parts = [`${res.added} added`, `${res.updated} updated`]; const parts = [`${res.added} added`, `${res.updated} updated`];
if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`); if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`);
setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`); setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`);
@@ -378,6 +409,9 @@ export default function Ipam({ user }: { user: CurrentUser }) {
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("phpipam")} disabled={!!syncing}> <button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("phpipam")} disabled={!!syncing}>
{syncing === "phpipam" ? "Syncing…" : "Sync from phpIPAM"} {syncing === "phpipam" ? "Syncing…" : "Sync from phpIPAM"}
</button> </button>
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("unifi")} disabled={!!syncing}>
{syncing === "unifi" ? "Syncing…" : "Sync from UniFi"}
</button>
</> </>
)} )}
</> </>
+14 -7
View File
@@ -15,7 +15,7 @@ const COL_GAP = 130;
const STATUS_SYMBOL: Record<MapNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" }; const STATUS_SYMBOL: Record<MapNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" };
const STATUS_WORD: Record<MapNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" }; const STATUS_WORD: Record<MapNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" };
const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor" }; const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor", device: "Network device" };
interface Placed extends MapNode { interface Placed extends MapNode {
x: number; x: number;
@@ -30,15 +30,22 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
neighbours.set(e.to, [...(neighbours.get(e.to) ?? []), e.from]); neighbours.set(e.to, [...(neighbours.get(e.to) ?? []), e.from]);
} }
const byKind = (kinds: MapNode["kind"][]) => data.nodes.filter((n) => kinds.includes(n.kind)); const byKind = (kinds: MapNode["kind"][]) => data.nodes.filter((n) => kinds.includes(n.kind));
const hosts = byKind(["host"]).sort((a, b) => a.label.localeCompare(b.label)); // Proxmox hosts and the switches and access points servers are plugged into share the left-hand column.
const hosts = byKind(["host", "device"]).sort((a, b) => a.label.localeCompare(b.label));
const serverNodes = byKind(["server"]); const serverNodes = byKind(["server"]);
const rightNodes = byKind(["dns", "monitor"]); const rightNodes = byKind(["dns", "monitor"]);
// Servers grouped under their host, then those with none. // Servers grouped under their host, then those with none.
const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:")); const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:")) ?? (neighbours.get(s.id) ?? []).find((id) => id.startsWith("device:"));
const servers: MapNode[] = []; const servers: MapNode[] = [];
for (const h of hosts) servers.push(...serverNodes.filter((s) => hostOf(s) === h.id).sort((a, b) => a.label.localeCompare(b.label))); const placedServers = new Set<string>();
servers.push(...serverNodes.filter((s) => !hostOf(s)).sort((a, b) => a.label.localeCompare(b.label))); for (const h of hosts) {
for (const s of serverNodes.filter((s) => hostOf(s) === h.id && !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label))) {
servers.push(s);
placedServers.add(s.id);
}
}
servers.push(...serverNodes.filter((s) => !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label)));
const step = NODE_H + GAP_Y; const step = NODE_H + GAP_Y;
const placed = new Map<string, Placed>(); const placed = new Map<string, Placed>();
@@ -69,7 +76,7 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
const height = all.length ? Math.max(...all.map((p) => p.y)) + NODE_H : 0; const height = all.length ? Math.max(...all.map((p) => p.y)) + NODE_H : 0;
const width = Math.max(...all.map((p) => p.x), 0) + NODE_W; const width = Math.max(...all.map((p) => p.x), 0) + NODE_W;
const columns = [ const columns = [
...(hasHosts ? [{ x: colX[0], title: "Proxmox hosts" }] : []), ...(hasHosts ? [{ x: colX[0], title: byKind(["host"]).length > 0 && byKind(["device"]).length > 0 ? "Proxmox hosts & network devices" : byKind(["device"]).length > 0 ? "Network devices" : "Proxmox hosts" }] : []),
...(servers.length > 0 ? [{ x: colX[1], title: "Servers" }] : []), ...(servers.length > 0 ? [{ x: colX[1], title: "Servers" }] : []),
...(hasRight ? [{ x: colX[2], title: "DNS names & monitors" }] : []), ...(hasRight ? [{ x: colX[2], title: "DNS names & monitors" }] : []),
]; ];
@@ -146,7 +153,7 @@ function ConnectionsMap() {
return ( return (
<> <>
<p className="text-secondary"> <p className="text-secondary">
How things connect: which Proxmox host a server runs on, which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is How things connect: which Proxmox host a server runs on, which switch or access point it is plugged into (from a UniFi controller), which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is
connected to. connected to.
</p> </p>
<ErrorNotice error={error} /> <ErrorNotice error={error} />
+241
View File
@@ -0,0 +1,241 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { api, type AlertItem, type CurrentUser, type MyWork } from "../api/client";
import AckDrawer from "../components/AckDrawer";
import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import TimeAgo from "../components/TimeAgo";
import { useAlertsReport } from "../hooks/useAlertsReport";
import { useMyWork } from "../hooks/useMyWork";
import { formatRemaining } from "../utils/duration";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const SEVERITY: Record<string, string> = { critical: "bg-red-lt text-red", warning: "bg-yellow-lt text-yellow", info: "bg-blue-lt text-blue" };
type Win = MyWork["windows"][number];
/**
* Everything with your name on it, in one place: the alerts you have taken or been handed, the acknowledgements about to run out, the maintenance you started that
* is about to end, and the update runs you are following. What is about to run out is marked, and comes first.
*/
export default function MyWorkPage({ user }: { user: CurrentUser }) {
const { work, reload } = useMyWork();
const { report, reload: reloadAlerts } = useAlertsReport();
const [acking, setAcking] = useState<AlertItem | null>(null);
const [busy, setBusy] = useState<number | null>(null);
const alertById = new Map((report?.alerts ?? []).map((a) => [a.id, a]));
function changed() {
reload();
reloadAlerts();
window.dispatchEvent(new Event("maintenance-changed"));
}
/** Minutes from now that a window should last to end `extra` minutes later than it does now (the server restarts the clock from now). */
const minutesFor = (w: Win, extra: number) => Math.min(7 * 24 * 60, Math.max(5, Math.ceil((Date.parse(w.endsAt) - Date.now()) / 60_000)) + extra);
async function extend(w: Win, extra: number, words: string) {
setBusy(w.id);
try {
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, extra), reason: w.reason ?? undefined });
toast.success(`${w.targetName}: ${words} more.`);
changed();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(null);
}
}
async function end(w: Win) {
setBusy(w.id);
try {
await api.maintenance.end(w.id);
toast.success(`Maintenance on ${w.targetName} ended.`, {
label: "Undo",
onClick: async () => {
try {
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, 0), reason: w.reason ?? undefined });
toast.info("Put back.");
} catch (err) {
toast.error(readableError(err));
} finally {
changed();
}
},
});
changed();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(null);
}
}
const nothing = work !== null && work.alerts.length === 0 && work.windows.length === 0 && work.updateRuns.length === 0;
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">My work</h2>
</div>
<div className="text-secondary mb-3">
What has your name on it: alerts you acknowledged or were handed, maintenance you started and update runs you started. Whatever is about to run out is marked, and listed first.
</div>
{work === null && <BlockSkeleton lines={4} />}
{nothing && (
<div className="card">
<EmptyState title="Nothing on your plate" hint="When you acknowledge an alert, are handed one, put something under maintenance or start an update run, it is listed here until it is done." />
</div>
)}
{work && work.alerts.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Alerts you have</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.alerts.map((a) => {
const full = alertById.get(a.alertId);
return (
<tr key={a.alertId}>
<td className="w-1">
<span className={`badge ${SEVERITY[a.severity] ?? ""}`}>{a.severity}</span>
</td>
<td className="stack-wide">
{a.link ? <Link to={a.link}>{a.message}</Link> : a.message}
<div className="small text-secondary">
{a.role === "handed" ? (a.ackedBy === (user.name ?? user.email ?? user.sub) ? "You took it" : `Handed to you by ${a.ackedBy}`) : "You acknowledged it"}
{a.note ? ` — ${a.note}` : ""}
</div>
</td>
<td className="stack-label text-nowrap" data-label="Lasts">
{a.until ? (
<span className={a.endsSoon ? "text-yellow" : "text-secondary"} title="When the acknowledgement runs out and the alert counts as nobody's again">
{a.endsSoon ? "Runs out " : "Until "}
<TimeAgo value={a.until} />
</span>
) : (
<span className="text-secondary">until the alert is gone</span>
)}
</td>
<td className="stack-wide text-nowrap">
<div className="btn-list flex-nowrap">
{full && (
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => setAcking(full)}>
Change…
</button>
)}
<Link to="/alerts" className="btn btn-sm btn-outline-secondary">
Alerts
</Link>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
{work && work.windows.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Maintenance you started</h3>
<div className="card-actions">
<Link to="/maintenance" className="small">
Maintenance
</Link>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.windows.map((w) => (
<tr key={w.id}>
<td className="stack-wide">
<strong>{w.targetName}</strong> <span className="text-secondary small">{w.targetKind}</span>
{w.reason && <div className="small text-secondary">{w.reason}</div>}
</td>
<td className="stack-label text-nowrap" data-label="Ends">
<span className={w.endsSoon ? "text-yellow" : "text-secondary"}>
Ends in {formatRemaining(w.endsAt)}
</span>
</td>
<td className="stack-wide text-nowrap">
<div className="btn-list flex-nowrap">
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 60, "1 hour")}>
+1 h
</button>
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 240, "4 hours")}>
+4 h
</button>
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy === w.id} onClick={() => void end(w)}>
End now
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{work && work.updateRuns.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Update runs you started</h3>
<div className="card-actions">
<Link to="/updates" className="small">
Updates
</Link>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.updateRuns.map((r) => (
<tr key={r.id}>
<td className="stack-wide">
<Link to={`/servers/${r.serverId}`}>{r.serverName}</Link> <span className="text-secondary small">{r.templateName}</span>
{r.message && !r.running && <div className="small text-secondary">{r.message}</div>}
</td>
<td className="stack-label" data-label="State">
{r.running ? (
<span className="badge bg-blue-lt text-blue">Running</span>
) : r.status === "done" ? (
<span className="badge bg-green-lt text-green">Done</span>
) : (
<span className="badge bg-red-lt text-red">{r.status}</span>
)}
{!r.running && r.updatesBefore !== null && r.updatesAfter !== null && (
<span className="text-secondary small ms-2">
{r.updatesBefore} → {r.updatesAfter} waiting{r.rebootRequired ? ", restart needed" : ""}
</span>
)}
</td>
<td className="stack-label text-nowrap" data-label="Started">
<TimeAgo value={r.startedAt} />
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{acking && <AckDrawer alert={acking} me={user} onClose={() => setAcking(null)} onSaved={changed} />}
</>
);
}
+12
View File
@@ -277,6 +277,18 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
{d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""} {d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""}
</div> </div>
{d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>} {d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>}
{d.servers.length > 0 && (
<div className="small" title="Servers the controller says are plugged into this, matched by their IP address">
Plugged in:{" "}
{d.servers.map((s, i) => (
<span key={`${s.serverId}-${i}`}>
{i > 0 && ", "}
<Link to={`/servers/${s.serverId}`}>{s.serverName}</Link>
{s.port !== null ? ` (port ${s.port})` : s.wired ? "" : " (Wi-Fi)"}
</span>
))}
</div>
)}
</td> </td>
<td className="stack-label" data-label="IP address"> <td className="stack-label" data-label="IP address">
{d.ip ? ( {d.ip ? (
+9 -8
View File
@@ -1,3 +1,4 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState, type FormEvent } from "react"; import { useEffect, useState, type FormEvent } from "react";
import TimeAgo from "../components/TimeAgo"; import TimeAgo from "../components/TimeAgo";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
@@ -15,7 +16,6 @@ import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination"; import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv"; import { downloadCsv } from "../utils/csv";
import { formatAgo } from "../utils/duration"; import { formatAgo } from "../utils/duration";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { EmptyRow, LoadingRow } from "../components/EmptyState"; import { EmptyRow, LoadingRow } from "../components/EmptyState";
@@ -167,14 +167,15 @@ export default function Ports({ user }: { user: CurrentUser }) {
} }
async function remove(fwd: PortForward) { async function remove(fwd: PortForward) {
if (!(await confirmDialog({ title: "Delete port opening", message: `Delete port opening "${fwd.label}"?`, confirmLabel: "Delete", danger: true }))) return;
setForwardError(null); setForwardError(null);
try { await removeWithUndo({
await api.ports.forwards.remove(fwd.id); remove: () => api.ports.forwards.remove(fwd.id),
loadForwards(); restore: () =>
} catch (err) { api.ports.forwards.create({ label: fwd.label, externalPort: fwd.externalPort, protocol: fwd.protocol, serverId: fwd.serverId, destination: fwd.destination, internalPort: fwd.internalPort, source: fwd.source, comment: fwd.comment }),
setForwardError(err instanceof Error ? err.message : String(err)); message: `Deleted the port opening "${fwd.label}".`,
} reload: loadForwards,
onError: setForwardError,
});
} }
const showForm = adding || editing; const showForm = adding || editing;
+161 -109
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom"; import { Link, useParams, useSearchParams } from "react-router-dom";
import { import {
api, api,
type CurrentUser, type CurrentUser,
@@ -32,9 +32,12 @@ import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskT
import { formatDateTime } from "../utils/date"; import { formatDateTime } from "../utils/date";
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl"; import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs"; import { confirmDialog } from "../utils/dialogs";
import { removeWithUndo } from "../utils/undoable";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { useBreadcrumbTail } from "../utils/breadcrumb"; import { useBreadcrumbTail } from "../utils/breadcrumb";
import { PageSkeleton } from "../components/Skeleton"; import { PageSkeleton } from "../components/Skeleton";
import ViewTabs from "../components/ViewTabs";
import ConnectedThrough from "../components/ConnectedThrough";
const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map( const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map(
([value, label]) => ({ value: value as ScheduleType, label }), ([value, label]) => ({ value: value as ScheduleType, label }),
@@ -101,8 +104,22 @@ const emptyTaskForm = {
enabled: true, enabled: true,
}; };
/** The sections of a server's page, switched by `?view=`: what it is, how it is doing, how it is connected, how it has been, what runs on it, and how it is set up. */
const SECTIONS = [
{ key: "overview", label: "Overview" },
{ key: "health", label: "Health" },
{ key: "network", label: "Network" },
{ key: "history", label: "History" },
{ key: "tasks", label: "Tasks" },
{ key: "settings", label: "Settings" },
] as const;
type SectionKey = (typeof SECTIONS)[number]["key"];
export default function ServerDetail({ user }: { user: CurrentUser }) { export default function ServerDetail({ user }: { user: CurrentUser }) {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const [searchParams] = useSearchParams();
const requested = searchParams.get("view");
const view: SectionKey = SECTIONS.some((t) => t.key === requested) ? (requested as SectionKey) : "overview";
const serverId = Number(id); const serverId = Number(id);
const isAdmin = user.role === "admin"; const isAdmin = user.role === "admin";
const canEditTasks = user.role === "admin" || user.role === "operator"; const canEditTasks = user.role === "admin" || user.role === "operator";
@@ -349,13 +366,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
} }
async function removeAdminLink(link: ServerLink) { async function removeAdminLink(link: ServerLink) {
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link?`, confirmLabel: "Remove", danger: true }))) return; await removeWithUndo({
try { remove: () => api.servers.removeLink(serverId, link.id),
await api.servers.removeLink(serverId, link.id); restore: () => api.servers.addLink(serverId, { label: link.label, url: link.url }),
await loadDetail(); message: `Removed the "${link.label}" link.`,
} catch (err) { reload: () => void loadDetail(),
setAdminLinkError(err instanceof Error ? err.message : String(err)); onError: setAdminLinkError,
} });
} }
if (loading) return <PageSkeleton />; if (loading) return <PageSkeleton />;
@@ -418,6 +435,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
onSaved={(tags) => setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))} onSaved={(tags) => setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))}
/> />
<ViewTabs
label="Sections of this server's page"
tabs={SECTIONS.map((t) => ({ to: t.key === "overview" ? `/servers/${serverId}` : `/servers/${serverId}?view=${t.key}`, label: t.key === "tasks" && tasks && tasks.length > 0 ? `Tasks (${tasks.length})` : t.label, active: view === t.key }))}
/>
{view === "overview" && (
<>
<div className="card mb-3"> <div className="card mb-3">
<div className="card-header"> <div className="card-header">
<h3 className="card-title">Admin Links</h3> <h3 className="card-title">Admin Links</h3>
@@ -510,91 +534,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div> </div>
</div> </div>
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Proxmox link</h3>
{!server.proxmoxIntegrationId && (
<div className="card-actions">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
Not a VM? Hide this
</button>
</div>
)}
</div>
<div className="card-body">
{server.proxmoxIntegrationId ? (
<div className="d-flex align-items-center gap-3">
<span className="text-secondary">
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
{server.proxmoxNode}
</span>
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
Unlink
</button>
</div>
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
) : (
<div className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">Proxmox integration</label>
<select
className="form-select"
value={pickedIntegrationId ?? ""}
onChange={(e) => {
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
setPickedGuestKey("");
}}
>
<option value="">Choose…</option>
{proxmoxIntegrations?.map((i) => (
<option key={i.id} value={i.id}>
{i.name}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label">VM / LXC</label>
<select
className="form-select"
value={pickedGuestKey}
disabled={!proxmoxGuests}
onChange={(e) => setPickedGuestKey(e.target.value)}
>
<option value="">Choose…</option>
{proxmoxGuests?.map((g) => (
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
{g.name} ({g.type} #{g.vmid} on {g.node})
</option>
))}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
{linking ? "Linking…" : "Link"}
</button>
</div>
{linkError && (
<div className="col-12">
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
</div>
)}
</div>
)}
</div>
</div>
) : (
isAdmin && (
<div className="mb-3">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
+ Show Proxmox link options
</button>
</div>
)
)}
<div className="row row-cards mb-3"> <div className="row row-cards mb-3">
<div className="col-lg-7"> <div className="col-lg-7">
<div className="card h-100"> <div className="card h-100">
@@ -604,7 +543,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
<div className="card-body"> <div className="card-body">
{hardware.source === "none" && ( {hardware.source === "none" && (
<div className="text-secondary"> <div className="text-secondary">
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC above. No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).
</div> </div>
)} )}
{hardware.error && <div className="alert alert-danger">{hardware.error}</div>} {hardware.error && <div className="alert alert-danger">{hardware.error}</div>}
@@ -812,6 +751,19 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div> </div>
</div> </div>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Runbooks</h3>
</div>
<div className="card-body">
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
</div>
</div>
</>
)}
{view === "health" && (
<>
<HostHealthCard <HostHealthCard
health={server.hostHealth} health={server.hostHealth}
ignored={server.thresholds?.ignoreServices ?? []} ignored={server.thresholds?.ignoreServices ?? []}
@@ -831,17 +783,30 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
} }
/> />
<AgentDiagnostics notes={detail.diagnostics ?? []} /> <AgentDiagnostics notes={detail.diagnostics ?? []} />
</>
)}
{view === "network" && (
<>
<ConnectedThrough serverId={serverId} />
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
canEdit={canEditTasks}
/>
</>
)}
{view === "history" && (
<>
{hardware.source === "agent" && <ServerTrends serverId={serverId} />} {hardware.source === "agent" && <ServerTrends serverId={serverId} />}
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />} {(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
<div className="card mb-3"> </>
<div className="card-header"> )}
<h3 className="card-title">Runbooks</h3>
</div> {view === "tasks" && (
<div className="card-body"> <>
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
</div>
</div>
{canEditTasks && ( {canEditTasks && (
<div className="card mb-3"> <div className="card mb-3">
<div className="card-header"> <div className="card-header">
@@ -853,12 +818,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div> </div>
)} )}
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
canEdit={canEditTasks}
/>
<div className="d-flex align-items-center mb-3"> <div className="d-flex align-items-center mb-3">
<h3 className="mb-0">Tasks</h3> <h3 className="mb-0">Tasks</h3>
{canEditTasks && ( {canEditTasks && (
@@ -956,6 +915,99 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
<ServerTaskTable tasks={tasks} canEditTasks={canEditTasks} onEdit={openEditTask} onDelete={deleteTask} /> <ServerTaskTable tasks={tasks} canEditTasks={canEditTasks} onEdit={openEditTask} onDelete={deleteTask} />
)} )}
</div> </div>
</>
)}
{view === "settings" && (
<>
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Proxmox link</h3>
{!server.proxmoxIntegrationId && (
<div className="card-actions">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
Not a VM? Hide this
</button>
</div>
)}
</div>
<div className="card-body">
{server.proxmoxIntegrationId ? (
<div className="d-flex align-items-center gap-3">
<span className="text-secondary">
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
{server.proxmoxNode}
</span>
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
Unlink
</button>
</div>
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
) : (
<div className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">Proxmox integration</label>
<select
className="form-select"
value={pickedIntegrationId ?? ""}
onChange={(e) => {
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
setPickedGuestKey("");
}}
>
<option value="">Choose…</option>
{proxmoxIntegrations?.map((i) => (
<option key={i.id} value={i.id}>
{i.name}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label">VM / LXC</label>
<select
className="form-select"
value={pickedGuestKey}
disabled={!proxmoxGuests}
onChange={(e) => setPickedGuestKey(e.target.value)}
>
<option value="">Choose…</option>
{proxmoxGuests?.map((g) => (
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
{g.name} ({g.type} #{g.vmid} on {g.node})
</option>
))}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
{linking ? "Linking…" : "Link"}
</button>
</div>
{linkError && (
<div className="col-12">
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
</div>
)}
</div>
)}
</div>
</div>
) : (
isAdmin && (
<div className="mb-3">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
+ Show Proxmox link options
</button>
</div>
)
)}
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
</>
)}
</> </>
); );
} }
+37 -2
View File
@@ -1,5 +1,6 @@
import type { CSSProperties } from "react"; import { useMemo, useState, type CSSProperties } from "react";
import { NavLink, Outlet } from "react-router-dom"; import { Link, NavLink, Outlet } from "react-router-dom";
import { searchSettings } from "../utils/settingsIndex";
const SUB_NAV = [ const SUB_NAV = [
{ to: "/settings/notifications", label: "Notifications" }, { to: "/settings/notifications", label: "Notifications" },
@@ -12,10 +13,44 @@ const SUB_NAV = [
{ to: "/settings/data", label: "Data" }, { to: "/settings/data", label: "Data" },
]; ];
/** A box that finds a setting by what it does ("quiet hours", "prometheus", "disk full") and goes to where it is set. */
function SettingsSearch() {
const [query, setQuery] = useState("");
const results = useMemo(() => searchSettings(query), [query]);
return (
<div className="mb-3 position-relative" style={{ maxWidth: 520 }}>
<input
type="search"
className="form-control"
placeholder="Find a setting…"
aria-label="Find a setting"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === "Escape" && setQuery("")}
/>
{query.trim() !== "" && (
<div className="list-group position-absolute w-100 shadow" style={{ zIndex: 20, top: "100%" }} role="listbox" aria-label="Matching settings">
{results.length === 0 ? (
<div className="list-group-item text-secondary">No setting matches that.</div>
) : (
results.map((r) => (
<Link key={r.title + r.to} to={r.to} className="list-group-item list-group-item-action" role="option" aria-selected={false} onClick={() => setQuery("")}>
<div>{r.title}</div>
<div className="small text-secondary">{r.where}</div>
</Link>
))
)}
</div>
)}
</div>
);
}
export default function Settings() { export default function Settings() {
return ( return (
<> <>
<h2 className="page-title mb-3">Settings</h2> <h2 className="page-title mb-3">Settings</h2>
<SettingsSearch />
<div className="row"> <div className="row">
<div className="col-12 col-md-3 col-lg-2 mb-3 mb-md-0"> <div className="col-12 col-md-3 col-lg-2 mb-3 mb-md-0">
<div className="card"> <div className="card">
+82
View File
@@ -0,0 +1,82 @@
/**
* Every setting worth looking for, and where it is: used by the search box on the Settings page and by the command palette. It is kept by hand — add a line when a
* setting is added — and `words` are the other ways somebody might ask for it (what it does, what it is called elsewhere).
*/
export interface SettingsEntry {
title: string;
/** Where it is, in words: "Notifications › What to send". */
where: string;
/** The address that opens it. */
to: string;
words: string;
}
const N = "/settings/notifications";
export const SETTINGS_INDEX: SettingsEntry[] = [
// Notifications
{ title: "Gotify, ntfy, email and webhook channels", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "gotify ntfy smtp email mail webhook push channel test send where notifications go" },
{ title: "Browser and phone push", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "web push browser phone device subscribe pwa notify vapid" },
{ title: "Server offline after (minutes)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "offline stopped reporting silent agent threshold limit minutes" },
{ title: "Disk usage alert at (percent)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "disk full storage percent threshold space" },
{ title: "Warn when a disk will fill within (days)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "disk forecast fill growth trend days" },
{ title: "Warn when a server starts listening on a new port", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "new port baseline listening tcp monitoring" },
{ title: "Call an alert flapping after (raises in an hour)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "flapping flap noise repeat raised cleared again hold back" },
{ title: "Alert when a network device is offline for (minutes)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "unifi network device switch access point gateway offline" },
{ title: "Secret, Tailscale key and domain expiry reminders", where: "Notifications › What to send › Secrets, keys and domains", to: `${N}?tab=events`, words: "expiry expire secrets certificate tailscale key domain renew warn days" },
{ title: "Backups too old, and restore tests", where: "Notifications › What to send › Backups and updates", to: `${N}?tab=events`, words: "backup stale old restore test guest proxmox updates docker image" },
{ title: "Integration, automation and ticket alerts", where: "Notifications › What to send › Integrations and automation", to: `${N}?tab=events`, words: "integration failing semaphore gitea automation failed osticket tickets uptime kuma" },
{ title: "DNS change notifications", where: "Notifications › What to send › DNS changes", to: `${N}?tab=events`, words: "dns changes record added removed" },
{ title: "Routing rules: which channel gets which alert", where: "Notifications › Who hears what", to: `${N}?tab=routing`, words: "routing rules route channel tags severity kinds mute" },
{ title: "Escalation: tell more people if nobody acts", where: "Notifications › Who hears what", to: `${N}?tab=routing`, words: "escalation escalate unacknowledged steps neglected" },
{ title: "Time zone and daily reminders", where: "Notifications › When", to: `${N}?tab=when`, words: "timezone time zone daily reminder time of day" },
{ title: "Quiet hours", where: "Notifications › When", to: `${N}?tab=when`, words: "quiet hours night hold queue do not disturb" },
{ title: "Monthly report", where: "Notifications › When", to: `${N}?tab=when`, words: "monthly report day of month send availability" },
{ title: "Weekly digest", where: "Notifications › When", to: `${N}?tab=when`, words: "weekly digest summary email day" },
{ title: "Open osTicket tickets from alerts", where: "Notifications › Alert tickets", to: `${N}?view=tickets`, words: "osticket ticket alert open api key which problems" },
// Sign-in
{ title: "Roles from groups", where: "Sign-in", to: "/settings/sign-in", words: "roles groups authentik oidc admin operator viewer claim map" },
{ title: "Profile pictures (Gravatar)", where: "Sign-in", to: "/settings/sign-in", words: "profile picture avatar gravatar photo identity provider" },
// Display
{ title: "Date and time format", where: "Display › Dates, times and tables", to: "/settings/display", words: "date time format 24 hour 12 hour locale clock" },
{ title: "Table pagination (rows per page)", where: "Display › Dates, times and tables", to: "/settings/display", words: "table rows per page pagination size" },
{ title: "Badge colours for integrations and DNS providers", where: "Display › Badge colours", to: "/settings/display?view=badges", words: "badge colour color integration dns provider" },
// Names, tags, share
{ title: "Name lists for the name generator", where: "Names", to: "/settings/names", words: "names generator themes list server names" },
{ title: "Tags and tag colours", where: "Tags", to: "/settings/tags", words: "tags colour color label add delete" },
{ title: "Share links: wall display, status page, calendar", where: "Share links", to: "/settings/share", words: "share link public wall status page calendar ics token address" },
// API and webhooks
{ title: "Metrics for Prometheus (tokens)", where: "API and webhooks", to: "/settings/api", words: "prometheus metrics token scrape grafana /metrics" },
{ title: "Event webhooks", where: "API and webhooks", to: "/settings/api", words: "webhook event alert opened resolved maintenance hmac secret home assistant" },
// Data
{ title: "Export and import configuration", where: "Data › Backup", to: "/settings/data", words: "backup export import configuration move restore database self backup" },
{ title: "Log retention and purge", where: "Data › Logs", to: "/settings/data?view=logs", words: "logs purge retention diagnostic audit delete old days" },
{ title: "DNS record cache", where: "Data › Cache", to: "/settings/data?view=cache", words: "dns cache clear zones records resync" },
];
const norm = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "");
/** The settings that match every word typed, best first (a word in the title beats one only in the description). */
export function searchSettings(query: string, limit = 8): SettingsEntry[] {
const words = norm(query).split(/\s+/).filter(Boolean);
if (words.length === 0) return [];
const scored: { entry: SettingsEntry; score: number }[] = [];
for (const entry of SETTINGS_INDEX) {
const title = norm(entry.title);
const where = norm(entry.where);
const rest = norm(entry.words);
let score = 0;
let all = true;
for (const w of words) {
if (title.includes(w)) score += title.startsWith(w) || title.includes(` ${w}`) ? 4 : 3;
else if (where.includes(w)) score += 2;
else if (rest.includes(w)) score += 1;
else {
all = false;
break;
}
}
if (all) scored.push({ entry, score });
}
return scored.sort((a, b) => b.score - a.score || a.entry.title.localeCompare(b.entry.title)).slice(0, limit).map((s) => s.entry);
}
+32
View File
@@ -0,0 +1,32 @@
import { readableError } from "./errors";
import { toast } from "./toast";
/**
* "Removed — Undo": take something away at once and offer to put it back, instead of asking first. Only for things that can be put back as they were by making them
* again from what is on screen (a link, a note, a written dependency) — not for anything whose history, secret or address would not come back with it.
*
* Returns whether it was removed. `reload` is called after the removal and again after an undo, so the page shows what is true.
*/
export async function removeWithUndo(options: { remove: () => Promise<unknown>; restore: () => Promise<unknown>; message: string; reload: () => void; onError?: (message: string) => void }): Promise<boolean> {
try {
await options.remove();
} catch (err) {
(options.onError ?? toast.error)(readableError(err));
return false;
}
toast.success(options.message, {
label: "Undo",
onClick: async () => {
try {
await options.restore();
toast.info("Put back.");
} catch (err) {
toast.error(`Couldn't put it back: ${readableError(err)}`);
} finally {
options.reload();
}
},
});
options.reload();
return true;
}
+10 -10
View File
@@ -3,7 +3,7 @@ import { Link } from "react-router-dom";
import { api, type CurrentUser, type DependenciesResponse, type DependencyNode } from "../api/client"; import { api, type CurrentUser, type DependenciesResponse, type DependencyNode } from "../api/client";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton"; import { BlockSkeleton } from "../components/Skeleton";
import { confirmDialog } from "../utils/dialogs"; import { removeWithUndo } from "../utils/undoable";
import { readableError } from "../utils/errors"; import { readableError } from "../utils/errors";
import { toast } from "../utils/toast"; import { toast } from "../utils/toast";
import { EmptyRow } from "../components/EmptyState"; import { EmptyRow } from "../components/EmptyState";
@@ -84,13 +84,13 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
} }
async function remove(d: DependenciesResponse["dependencies"][number]) { async function remove(d: DependenciesResponse["dependencies"][number]) {
if (!(await confirmDialog({ title: "Remove a dependency", message: `${d.from.name} no longer needs ${d.to.name}?`, confirmLabel: "Remove", danger: true }))) return; await removeWithUndo({
try { remove: () => api.dependencies.remove(d.id),
await api.dependencies.remove(d.id); restore: () => api.dependencies.create({ fromType: d.from.type, fromId: d.from.id, toType: d.to.type, toId: d.to.id }),
load(); message: `${d.from.name} no longer needs ${d.to.name}.`,
} catch (err) { reload: load,
setError(readableError(err)); onError: setError,
} });
} }
return ( return (
@@ -174,7 +174,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
<h3 className="card-title">Set elsewhere</h3> <h3 className="card-title">Set elsewhere</h3>
</div> </div>
<div className="card-body text-secondary small pb-0"> <div className="card-body text-secondary small pb-0">
A server&rsquo;s &ldquo;runs on&rdquo; is set on the server itself, or worked out from the Proxmox node it is a guest of. A network device&rsquo;s &ldquo;connected through&rdquo; is what its UniFi controller says. They count here too. A server&rsquo;s &ldquo;runs on&rdquo; is set on the server itself, or worked out from the Proxmox node it is a guest of. What a network device or a server is &ldquo;connected through&rdquo; is what its UniFi controller says (a server is matched by its IP address). They count here too.
</div> </div>
<div className="table-responsive"> <div className="table-responsive">
<table className="table table-vcenter card-table"> <table className="table table-vcenter card-table">
@@ -182,7 +182,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
{data.runsOn.map((r) => ( {data.runsOn.map((r) => (
<tr key={`${r.from.key}>${r.to.key}`}> <tr key={`${r.from.key}>${r.to.key}`}>
<td>{r.from.name}</td> <td>{r.from.name}</td>
<td className="text-secondary">{r.from.key.startsWith("device:") && r.to.key.startsWith("device:") ? "is connected through" : "runs on"}</td> <td className="text-secondary">{r.to.key.startsWith("device:") ? "is connected through" : "runs on"}</td>
<td>{r.to.name}</td> <td>{r.to.name}</td>
</tr> </tr>
))} ))}