Let an administrator set a server's hostname by hand

A Change link on the Identity card sets the hostname (a host name or an
address, written lower case without the trailing dot). It is then kept even
when the agent reports another — marked "set by hand", with what the agent
reports shown beside it — until "Use what the agent reports" gives it up. The
agent's own hostname is always remembered (reported_hostname). PUT and DELETE
/api/servers/:id/hostname, administrators only, audited with from and to.
Migration 0082 adds hostname_pinned and reported_hostname and fills the latter
for servers that have reported. It changes this app's name for the server, not
the machine's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 23:30:31 +01:00
1 parent 6f144b4e36
commit 672c7f2f66
14 files changed
+9020 -7

No files matched your search

+3
View File
@@ -423,6 +423,9 @@ export const servers = sqliteTable("servers", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
hostname: text("hostname"),
// True once somebody set the hostname by hand: a report from the agent then no longer replaces it (it is still kept, in reported_hostname, so the hand-set one can be given up).
hostnamePinned: integer("hostname_pinned", { mode: "boolean" }).notNull().default(false),
reportedHostname: text("reported_hostname"), // what the agent last said its hostname is; null for a server that never reported one
osType: text("os_type").notNull().default("linux"),
description: text("description"),
apiTokenHash: text("api_token_hash").notNull(),
+35
View File
@@ -26,6 +26,7 @@ import { activeSubjects } from "../services/maintenance.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { getSettings, updateSettings } from "../services/settingsStore.js";
import { osSummary } from "../services/osLifecycle.js";
import { normaliseHostname } from "../utils/hostnames.js";
export const serversRouter = Router();
@@ -154,6 +155,40 @@ const updateServerSchema = z
{ message: "proxmoxIntegrationId/proxmoxNode/proxmoxGuestType/proxmoxVmid must be set together or all cleared to null" },
);
const hostnameSchema = z.object({ hostname: z.string().max(300) });
/**
* Sets a server's hostname by hand. It is kept even when the agent reports another (that is still remembered, and shown), until it is given up with DELETE. A host name or an address, in the form
* names are compared (see utils/hostnames.ts); anything else is refused. An administrator's.
*/
serversRouter.put("/:id/hostname", requireRole("admin"), asyncHandler(async (req, res) => {
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN;
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const parsed = hostnameSchema.safeParse(req.body);
const hostname = parsed.success ? normaliseHostname(parsed.data.hostname) : null;
if (hostname === null) return res.status(400).json({ error: "invalid_hostname", message: "That is not a host name: use letters, digits, - and _ (a name such as nas.home.lan), or an address." });
const [existing] = await db.select().from(servers).where(eq(servers.id, id)).limit(1);
if (!existing) return res.status(404).json({ error: "not_found" });
const [updated] = await db.update(servers).set({ hostname, hostnamePinned: true }).where(eq(servers.id, id)).returning();
if (existing.hostname !== hostname || !existing.hostnamePinned) {
await recordAudit({ actor: req.currentUser!, category: "server", action: "set_hostname", targetType: "server", targetId: id, detail: { name: existing.name, from: existing.hostname, to: hostname } });
}
res.json({ server: publicServer(updated) });
}));
/** Gives up a hostname that was set by hand: the server's hostname is what its agent reports again — at once, if it has reported one, otherwise as it is until it does. */
serversRouter.delete("/:id/hostname", requireRole("admin"), asyncHandler(async (req, res) => {
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN;
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [existing] = await db.select().from(servers).where(eq(servers.id, id)).limit(1);
if (!existing) return res.status(404).json({ error: "not_found" });
if (!existing.hostnamePinned) return res.json({ server: publicServer(existing) });
const hostname = existing.reportedHostname ?? existing.hostname;
const [updated] = await db.update(servers).set({ hostname, hostnamePinned: false }).where(eq(servers.id, id)).returning();
await recordAudit({ actor: req.currentUser!, category: "server", action: "reset_hostname", targetType: "server", targetId: id, detail: { name: existing.name, from: existing.hostname, to: hostname } });
res.json({ server: publicServer(updated) });
}));
serversRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
+3 -2
View File
@@ -116,7 +116,7 @@ export async function syncServerTasks(serverId: number, report: AgentReport) {
}
const system = report.system;
const [before] = await db.select({ pendingUpdates: servers.pendingUpdates, updatesPendingSince: servers.updatesPendingSince, hostHealth: servers.hostHealth, agentVersion: servers.agentVersion, portBaseline: servers.portBaseline }).from(servers).where(eq(servers.id, serverId));
const [before] = await db.select({ pendingUpdates: servers.pendingUpdates, updatesPendingSince: servers.updatesPendingSince, hostHealth: servers.hostHealth, agentVersion: servers.agentVersion, portBaseline: servers.portBaseline, hostnamePinned: servers.hostnamePinned }).from(servers).where(eq(servers.id, serverId));
await db
.update(servers)
.set({
@@ -130,7 +130,8 @@ export async function syncServerTasks(serverId: number, report: AgentReport) {
...(system?.hardware?.manufacturer ? { hwManufacturer: system.hardware.manufacturer } : {}),
...(system?.hardware?.model ? { hwModel: system.hardware.model } : {}),
...(system?.hardware?.serial ? { hwSerial: system.hardware.serial } : {}),
...(report.hostname ? { hostname: report.hostname } : {}),
// What the agent says its hostname is is always kept; it is the server's hostname too, unless somebody set that by hand.
...(report.hostname ? { reportedHostname: report.hostname, ...(before?.hostnamePinned ? {} : { hostname: report.hostname }) } : {}),
...(report.agentVersion !== undefined ? { agentVersion: report.agentVersion } : {}),
// An agent knows what it runs on better than whoever registered the server did.
...(report.osType === "linux" || report.osType === "windows" ? { osType: report.osType } : {}),
+15
View File
@@ -0,0 +1,15 @@
/**
* The hostname a server is given by hand. It is how this app names the machine to the rest of the world — to match it to a DNS name or a monitor, and to reach it — so it is a host name
* (letters, digits, `-` and `_`, in labels of up to 63 characters, a name of up to 253) or an address, written the way names are compared: lower case, no dot at the end.
*/
import * as net from "node:net";
const LABEL = /^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$/;
/** The hostname as it is to be kept, or null when it is not one. */
export function normaliseHostname(input: string): string | null {
const s = input.trim().toLowerCase().replace(/\.$/, "");
if (s === "" || s.length > 253) return null;
if (net.isIP(s) !== 0) return s;
return s.split(".").every((label) => LABEL.test(label)) ? s : null;
}