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

+4 -2
View File
@@ -23,7 +23,7 @@ what the app actually creates.
|---|---|
| **File** | `DATABASE_PATH`, default `../data/homelab-manager.sqlite` (relative to `server/`; `/app/data/...` in Docker). The folder is created if missing. |
| **Foreign keys** | Switched on for every connection (`PRAGMA foreign_keys = ON`), so the `ON DELETE` rules below are enforced. |
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0081`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0082`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
| **Tables** | 91 application tables, plus drizzle's own `__drizzle_migrations`. |
**Not in the database, but beside it in the data folder:** the backups of the database itself (`backups/homelab-manager-….sqlite`, taken daily and on request; see [BACKUP.md](BACKUP.md)), and, only while a restore is waiting or has just happened, `restore-pending.sqlite` / `restore-pending.json` and `restore-result.json`.
@@ -244,7 +244,9 @@ what it last reported.
|---|---|---|
| `id` | integer PK | |
| `name` | text NOT NULL | Not unique. |
| `hostname` | text | |
| `hostname` | text | What this app calls the machine to the rest of the world: what the agent reports, or what an administrator set by hand (see `hostname_pinned`). |
| `hostname_pinned` | integer NOT NULL, default 0 | 1 once the hostname was set by hand: a report from the agent then does not replace it. Given up by clearing it, which puts `reported_hostname` back. |
| `reported_hostname` | text | What the agent last said its hostname is (kept even while `hostname` is pinned); null for a server that never reported one. Migration 0082 fills it from `hostname` for servers that have reported. |
| `os_type` | text NOT NULL, default `linux` | |
| `description` | text | |
| `api_token_hash` | text NOT NULL | SHA-256 of the agent's token. |
+5
View File
@@ -87,6 +87,11 @@ All modules from the original plan are built:
through a PowerShell agent (`agent/windows/`, see its README), plus manual
entries for things an agent can't see (Docker jobs, backups). The Servers page itself just lists
registered servers and (admin-only) adds new ones / issues agent tokens;
a server's **hostname** — which an agent replaces with the machine's own at every report — can be
changed by an administrator on its page (*Identity → Change*): 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. It is the name this app has for the server, used to
match it to DNS names and monitors and to reach it; it does not rename the machine itself;
clicking a server opens its detail page with CPU/RAM/disk status, IP
addresses, matching DNS names (looked up from the DNS module's cache), and
its scheduled tasks — live hardware from Proxmox for VM/LXC-backed
+1 -1
View File
@@ -110,7 +110,7 @@ even further, to admin only:
records, etc.), but adding, editing, testing, or deleting an
integration or DNS provider is admin-only. So is **making, editing or deleting a zone** on a DNS provider that can (Technitium): making one makes the server an authority for a name, deleting one takes every record in it, and editing one switches it off or changes who may ask or copy it, so none is an operator's job like adding a record.
- **Servers**: registering a new server, rotating its agent token, and
editing/deleting a server are admin-only; tagging a server and
editing/deleting a server (including setting its hostname by hand, and giving that up) are admin-only; tagging a server and
linking/unlinking it to a Proxmox guest just need operator.
- **Tags**: creating, renaming, recoloring, or deleting a tag is
admin-only (applying an existing tag to a server needs operator).
@@ -0,0 +1,3 @@
ALTER TABLE `servers` ADD `hostname_pinned` integer DEFAULT false NOT NULL;--> statement-breakpoint
ALTER TABLE `servers` ADD `reported_hostname` text;--> statement-breakpoint
UPDATE `servers` SET `reported_hostname` = `hostname` WHERE `last_seen_at` IS NOT NULL AND `hostname` IS NOT NULL;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -575,6 +575,13 @@
"when": 1793564076431,
"tag": "0081_powerful_thing",
"breakpoints": true
},
{
"idx": 82,
"version": "6",
"when": 1793571807053,
"tag": "0082_charming_dark_beast",
"breakpoints": true
}
]
}
+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;
}
+180
View File
@@ -0,0 +1,180 @@
/**
* A server's hostname set by hand: what a hostname is, that the agent's reports no longer replace one that was set by hand (and are still remembered), that giving it up goes back to what the
* agent reports, who may, what is refused and what is written in the audit log.
*
* 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-hostname-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { normaliseHostname } = await import("../src/utils/hostnames.js");
const { serversRouter } = await import("../src/routes/servers.js");
const { agentReportRouter } = await import("../src/routes/agentReport.js");
const { hashToken } = await import("../src/services/tokens.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("what a hostname is", () => {
test("a host name in labels, or an address, in lower case without the dot at the end", () => {
assert.equal(normaliseHostname("NAS.Home.LAN."), "nas.home.lan");
assert.equal(normaliseHostname(" pve1 "), "pve1");
assert.equal(normaliseHostname("web_01.lab"), "web_01.lab");
assert.equal(normaliseHostname("xn--bcher-kva.example"), "xn--bcher-kva.example");
assert.equal(normaliseHostname("192.168.1.20"), "192.168.1.20");
assert.equal(normaliseHostname("FD00::20"), "fd00::20");
});
test("anything else is not: empty, spaces, a leading or doubled dot, a dash at the end of a label, other letters, a path, a port, a label or a name that is too long", () => {
for (const bad of ["", " ", "a b", ".lan", "a..lan", "-a.lan", "a-.lan", "bücher.lan", "a/b", "../x", "host:22", "http://host", "a;b", `${"a".repeat(64)}.lan`, `${"a.".repeat(130)}lan`]) {
assert.equal(normaliseHostname(bad), null, JSON.stringify(bad));
}
});
});
describe("the hostname of a server", () => {
let app: Server;
let base = "";
let id = 0;
let neverReported = 0;
let sub = "admin";
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "operator", name: "Olle", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
id = (await db.insert(servers).values({ name: "elsa", hostname: "elsa-old", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id;
neverReported = (await db.insert(servers).values({ name: "quiet", hostname: "quiet.lan", apiTokenHash: hashToken("tok2"), apiTokenPrefix: "q" }).returning({ id: servers.id }))[0].id;
const a = express();
a.use("/api/agent/report", agentReportRouter);
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub } };
next();
});
a.use("/api/servers", serversRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const report = (hostname: string | undefined) =>
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ ...(hostname ? { hostname } : {}), os_type: "linux", tasks: [] }) });
const put = (serverId: number | string, hostname: unknown) => fetch(`${base}/servers/${serverId}/hostname`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ hostname }) });
const give = (serverId: number | string) => fetch(`${base}/servers/${serverId}/hostname`, { method: "DELETE" });
const row = async (serverId = id) => (await db.select().from(servers).where(eq(servers.id, serverId)))[0];
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
test("an agent's hostname is the server's hostname, and is kept as what the agent reports", async () => {
assert.equal((await report("elsa-agent")).status, 202);
const s = await row();
assert.deepEqual([s.hostname, s.reportedHostname, s.hostnamePinned], ["elsa-agent", "elsa-agent", false]);
assert.equal((await report("elsa-agent-2")).status, 202);
assert.deepEqual([(await row()).hostname, (await row()).reportedHostname], ["elsa-agent-2", "elsa-agent-2"]);
});
test("only an administrator sets a hostname or gives it up", async () => {
for (const who of ["viewer", "operator"]) {
sub = who;
assert.equal((await put(id, "x.lan")).status, 403, who);
assert.equal((await give(id)).status, 403, who);
}
sub = "admin";
assert.equal((await row()).hostname, "elsa-agent-2");
});
test("a hostname set by hand is kept in the form names are compared, pinned, and written in the audit log with what it was", async () => {
const res = await put(id, " NAS.Home.LAN. ");
assert.equal(res.status, 200);
const body = (await res.json()) as { server: { hostname: string; hostnamePinned: boolean; reportedHostname: string | null } };
assert.deepEqual([body.server.hostname, body.server.hostnamePinned, body.server.reportedHostname], ["nas.home.lan", true, "elsa-agent-2"]);
const [entry] = await audit("set_hostname");
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["server", "server", String(id)]);
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { name: "elsa", from: "elsa-agent-2", to: "nas.home.lan" });
});
test("while it is pinned a report does not replace it, but what the agent says is still remembered", async () => {
assert.equal((await report("elsa-renamed")).status, 202);
const s = await row();
assert.deepEqual([s.hostname, s.reportedHostname, s.hostnamePinned], ["nas.home.lan", "elsa-renamed", true]);
assert.equal((await report(undefined)).status, 202, "a report that says no hostname costs nothing");
assert.deepEqual([(await row()).hostname, (await row()).reportedHostname], ["nas.home.lan", "elsa-renamed"]);
});
test("the detail and the list say it is set by hand and what the agent reports", async () => {
const detail = (await (await fetch(`${base}/servers/${id}/detail`)).json()) as { server: { hostname: string; hostnamePinned: boolean; reportedHostname: string } };
assert.deepEqual([detail.server.hostname, detail.server.hostnamePinned, detail.server.reportedHostname], ["nas.home.lan", true, "elsa-renamed"]);
const list = (await (await fetch(`${base}/servers`)).json()) as { servers: { id: number; hostnamePinned: boolean }[] };
assert.equal(list.servers.find((s) => s.id === id)!.hostnamePinned, true);
});
test("setting the same thing again changes nothing and is not written down twice", async () => {
const before = (await audit("set_hostname")).length;
assert.equal((await put(id, "nas.home.lan")).status, 200);
assert.equal((await audit("set_hostname")).length, before);
});
test("giving it up goes back to what the agent reports, at once, and is written in the audit log; and the reports replace it again", async () => {
const res = await give(id);
assert.equal(res.status, 200);
const body = (await res.json()) as { server: { hostname: string; hostnamePinned: boolean } };
assert.deepEqual([body.server.hostname, body.server.hostnamePinned], ["elsa-renamed", false]);
const [entry] = await audit("reset_hostname");
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { name: "elsa", from: "nas.home.lan", to: "elsa-renamed" });
assert.equal((await report("elsa-third")).status, 202);
assert.equal((await row()).hostname, "elsa-third");
});
test("giving up what was not set by hand changes nothing and writes nothing", async () => {
const before = (await audit("reset_hostname")).length;
assert.equal((await give(id)).status, 200);
assert.equal((await audit("reset_hostname")).length, before);
assert.equal((await row()).hostname, "elsa-third");
});
test("a server that never reported keeps its hostname when the one set by hand is given up", async () => {
assert.equal((await put(neverReported, "quiet-new.lan")).status, 200);
const res = await give(neverReported);
assert.equal(((await res.json()) as { server: { hostname: string; hostnamePinned: boolean } }).server.hostname, "quiet-new.lan");
assert.equal((await row(neverReported)).hostnamePinned, false);
});
test("what is not a hostname, a body that is not one, a server that is not there and an id that is no id are refused", async () => {
const before = (await row()).hostname;
for (const bad of ["", "a b", "-x", "http://nas", "host:22", "x".repeat(300), 5, null, undefined]) {
const res = await put(id, bad);
assert.equal(res.status, 400, JSON.stringify(bad));
assert.equal(typeof ((await res.json()) as { message?: string }).message, "string");
}
assert.equal((await row()).hostname, before);
assert.equal((await put(999999, "x.lan")).status, 404);
assert.equal((await give(999999)).status, 404);
assert.equal((await put("abc", "x.lan")).status, 400);
assert.equal((await give("abc")).status, 400);
});
});
+6
View File
@@ -750,6 +750,10 @@ export interface ServerRecord {
id: number;
name: string;
hostname: string | null;
/** Set by hand: a report from the agent does not replace it. */
hostnamePinned: boolean;
/** What the agent last said its hostname is; null if it never said. */
reportedHostname: string | null;
osType: string;
description: string | null;
apiTokenPrefix: string;
@@ -4011,6 +4015,8 @@ export const api = {
request<{ server: ServerRecord }>(`/api/servers/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
summary: () => request<ServerSummary>("/api/servers/summary"),
updates: () => request<{ servers: UpdatesServer[]; agentLatest: AgentLatest }>("/api/servers/updates"),
setHostname: (id: number, hostname: string) => request<{ server: ServerRecord }>(`/api/servers/${id}/hostname`, { method: "PUT", body: JSON.stringify({ hostname }) }),
resetHostname: (id: number) => request<{ server: ServerRecord }>(`/api/servers/${id}/hostname`, { method: "DELETE" }),
detail: (id: number) => request<ServerDetail>(`/api/servers/${id}/detail`),
activity: (id: number) => request<{ events: ServerActivityEvent[] }>(`/api/servers/${id}/activity`),
metrics: (id: number, days: number) => request<{ days: number; series: ServerMetricSeries[] }>(`/api/servers/${id}/metrics?days=${days}`),
+102
View File
@@ -0,0 +1,102 @@
import { useState, type FormEvent } from "react";
import { api, type ServerRecord } from "../api/client";
import { ErrorNotice } from "./Notice";
import { readableError } from "../utils/errors";
/**
* A server's hostname, with (for an administrator) a way to change it by hand. A hostname set by hand is kept even when the agent reports another — the page says so, shows what the agent
* reports, and can go back to it. It is the name this app uses to match the server to a DNS name or a monitor and to reach it; it does not rename the machine itself.
*/
export default function ServerHostname({ server, isAdmin, onChanged }: { server: Pick<ServerRecord, "id" | "hostname" | "hostnamePinned" | "reportedHostname">; isAdmin: boolean; onChanged: () => void | Promise<void> }) {
const [editing, setEditing] = useState(false);
const [value, setValue] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
function start() {
setValue(server.hostname ?? "");
setError(null);
setEditing(true);
}
async function save(e: FormEvent) {
e.preventDefault();
if (busy) return;
setBusy(true);
setError(null);
try {
await api.servers.setHostname(server.id, value);
setEditing(false);
await onChanged();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function giveUp() {
setBusy(true);
setError(null);
try {
await api.servers.resetHostname(server.id);
await onChanged();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
const differs = server.hostnamePinned && server.reportedHostname && server.reportedHostname !== server.hostname;
return (
<>
<dt className="col-5">Hostname</dt>
<dd className="col-7">
{editing ? (
<form onSubmit={save}>
<ErrorNotice error={error} />
<input className="form-control form-control-sm mb-1" autoFocus required maxLength={300} autoComplete="off" aria-label="Hostname" placeholder="nas.home.lan" value={value} onChange={(e) => setValue(e.target.value)} />
<div className="text-secondary small mb-1">A host name or an address. It is kept even if the agent reports another.</div>
<div className="d-flex gap-2">
<button type="submit" className="btn btn-sm btn-primary" disabled={busy || value.trim() === ""}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={() => setEditing(false)} disabled={busy}>
Cancel
</button>
</div>
</form>
) : (
<>
<span>{server.hostname ?? "—"}</span>
{server.hostnamePinned && (
<span className="badge bg-blue-lt text-blue ms-2" title="Set by hand: a report from the agent does not replace it.">
set by hand
</span>
)}
{isAdmin && (
<button type="button" className="btn btn-sm btn-link py-0" onClick={start}>
Change
</button>
)}
{differs && (
<div className="small text-secondary">
The agent reports <strong>{server.reportedHostname}</strong>.
</div>
)}
{isAdmin && server.hostnamePinned && (
<div>
<button type="button" className="btn btn-sm btn-link px-0 py-0" onClick={() => void giveUp()} disabled={busy}>
{server.reportedHostname ? "Use what the agent reports" : "Stop keeping it by hand"}
</button>
</div>
)}
{!editing && error && <ErrorNotice error={error} />}
</>
)}
</dd>
</>
);
}
+2 -2
View File
@@ -13,6 +13,7 @@ import {
type TaskRecord,
} from "../api/client";
import ServerPorts from "../components/ServerPorts";
import ServerHostname from "../components/ServerHostname";
import ServerTrends from "../components/ServerTrends";
import UptimeHistory from "../components/UptimeHistory";
import NotesCard from "../components/NotesCard";
@@ -704,8 +705,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div>
<div className="card-body">
<dl className="row mb-0">
<dt className="col-5">Hostname</dt>
<dd className="col-7">{server.hostname ?? "—"}</dd>
<ServerHostname server={server} isAdmin={isAdmin} onChanged={loadDetail} />
<dt className="col-5">OS type</dt>
<dd className="col-7">{server.osType}</dd>
<dt className="col-5">Token</dt>