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>
514 lines
21 KiB
TypeScript
514 lines
21 KiB
TypeScript
import { toast } from "../utils/toast";
|
|
import { removeWithUndo } from "../utils/undoable";
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { useSearchParams } from "react-router-dom";
|
|
import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client";
|
|
import { downloadCsv } from "../utils/csv";
|
|
import { useSortable } from "../hooks/useSortable";
|
|
import SortableTh from "../components/SortableTh";
|
|
import { usePagination } from "../hooks/usePagination";
|
|
import Pagination from "../components/Pagination";
|
|
import { useSelection } from "../hooks/useSelection";
|
|
import { confirmDialog, promptDialog } from "../utils/dialogs";
|
|
import { ErrorNotice } from "../components/Notice";
|
|
import TableToolbar from "../components/TableToolbar";
|
|
import { EmptyRow, LoadingRow } from "../components/EmptyState";
|
|
|
|
const emptyForm: IpamInput = { ipAddress: "", label: "", vendor: "", location: "", notes: "" };
|
|
|
|
function isIpv6(ip: string) {
|
|
return ip.includes(":");
|
|
}
|
|
|
|
export default function Ipam({ user }: { user: CurrentUser }) {
|
|
const canEdit = user.role === "admin" || user.role === "operator";
|
|
const [entries, setEntries] = useState<IpamEntry[] | null>(null);
|
|
const [excludedRanges, setExcludedRanges] = useState<string[]>([]);
|
|
const [hideExcluded, setHideExcluded] = useState(true);
|
|
const [showRanges, setShowRanges] = useState(false);
|
|
const [newRange, setNewRange] = useState("");
|
|
const [savingRanges, setSavingRanges] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [searchParams] = useSearchParams();
|
|
const [search, setSearch] = useState(() => searchParams.get("q") ?? "");
|
|
const [editing, setEditing] = useState<IpamEntry | null>(null);
|
|
const [adding, setAdding] = useState(false);
|
|
const [form, setForm] = useState<IpamInput>(emptyForm);
|
|
const [saving, setSaving] = useState(false);
|
|
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | "unifi" | null>(null);
|
|
const [syncResult, setSyncResult] = useState<string | null>(null);
|
|
const selection = useSelection<number>();
|
|
const [bulkDeleting, setBulkDeleting] = useState(false);
|
|
|
|
function load() {
|
|
api.ipam
|
|
.list()
|
|
.then((res) => {
|
|
setEntries(res.entries);
|
|
setExcludedRanges(res.excludedRanges);
|
|
// Deep-link from global search (?editId=) — jump straight to that entry's edit form.
|
|
const editId = Number(searchParams.get("editId"));
|
|
const target = res.entries.find((e) => e.id === editId);
|
|
if (target && canEdit) startEdit(target);
|
|
})
|
|
.catch((err) => setError(String(err)));
|
|
}
|
|
|
|
useEffect(load, []);
|
|
|
|
/** Saves the whole list (the server validates and normalises it) and reloads — shared with the Consistency page. */
|
|
async function saveRanges(ranges: string[]): Promise<boolean> {
|
|
setSavingRanges(true);
|
|
setError(null);
|
|
try {
|
|
await api.consistency.setExcludedRanges(ranges);
|
|
load();
|
|
return true;
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : String(err));
|
|
return false;
|
|
} finally {
|
|
setSavingRanges(false);
|
|
}
|
|
}
|
|
|
|
async function addRange(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
if (!newRange.trim()) return;
|
|
if (await saveRanges([...excludedRanges, newRange.trim()])) setNewRange("");
|
|
}
|
|
|
|
async function excludeAround(entry: IpamEntry) {
|
|
const suggestion = isIpv6(entry.ipAddress) ? `${entry.ipAddress}/64` : `${entry.ipAddress.split(".").slice(0, 3).join(".")}.0/24`;
|
|
const range = await promptDialog({
|
|
title: "Exclude a range",
|
|
message: "Hide this range from IP Addresses and the Consistency report — every address in it, not just this one.",
|
|
label: "Range (a network like 172.17.0.0/16, or a single address)",
|
|
defaultValue: suggestion,
|
|
confirmLabel: "Exclude",
|
|
required: true,
|
|
});
|
|
if (range === null || !range.trim()) return;
|
|
await saveRanges([...excludedRanges, range.trim()]);
|
|
}
|
|
|
|
const excludedCount = useMemo(() => entries?.filter((e) => e.excluded).length ?? 0, [entries]);
|
|
|
|
const filtered = useMemo(() => {
|
|
if (!entries) return [];
|
|
const base = hideExcluded ? entries.filter((e) => !e.excluded) : entries;
|
|
const q = search.trim().toLowerCase();
|
|
if (!q) return base;
|
|
return base.filter((e) =>
|
|
[e.ipAddress, e.label, e.vendor, e.location].some((v) => (v ?? "").toLowerCase().includes(q)),
|
|
);
|
|
}, [entries, hideExcluded, search]);
|
|
|
|
function startAdd() {
|
|
setAdding(true);
|
|
setEditing(null);
|
|
setForm(emptyForm);
|
|
}
|
|
|
|
function startEdit(entry: IpamEntry) {
|
|
setEditing(entry);
|
|
setAdding(false);
|
|
setForm({
|
|
ipAddress: entry.ipAddress,
|
|
label: entry.label ?? "",
|
|
vendor: entry.vendor ?? "",
|
|
location: entry.location ?? "",
|
|
notes: entry.notes ?? "",
|
|
});
|
|
}
|
|
|
|
function cancelForm() {
|
|
setAdding(false);
|
|
setEditing(null);
|
|
setForm(emptyForm);
|
|
}
|
|
|
|
async function submit(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
setError(null);
|
|
setSaving(true);
|
|
try {
|
|
if (editing) {
|
|
const { ipAddress: _ip, ...rest } = form;
|
|
await api.ipam.update(editing.id, rest);
|
|
} else {
|
|
await api.ipam.create(form);
|
|
}
|
|
cancelForm();
|
|
load();
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : String(err));
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
/** 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) {
|
|
setError(null);
|
|
if (entry.source) {
|
|
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"? A sync can bring it back.`, confirmLabel: "Delete", danger: true }))) return;
|
|
try {
|
|
await api.ipam.remove(entry.id);
|
|
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() {
|
|
const ids = Array.from(selection.selected);
|
|
if (ids.length === 0) 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);
|
|
setBulkDeleting(true);
|
|
try {
|
|
const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id)));
|
|
const failed = results.filter((r) => r.status === "rejected").length;
|
|
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();
|
|
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 {
|
|
setBulkDeleting(false);
|
|
}
|
|
}
|
|
|
|
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam" | "unifi", string> = {
|
|
tailscale: "Tailscale",
|
|
proxmox: "Proxmox",
|
|
phpipam: "phpIPAM",
|
|
unifi: "UniFi",
|
|
};
|
|
|
|
async function runSync(source: "tailscale" | "proxmox" | "phpipam" | "unifi") {
|
|
setError(null);
|
|
setSyncResult(null);
|
|
setSyncing(source);
|
|
try {
|
|
const res =
|
|
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`];
|
|
if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`);
|
|
setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`);
|
|
if (res.errors.length > 0) setError(res.errors.join("; "));
|
|
load();
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : String(err));
|
|
} finally {
|
|
setSyncing(null);
|
|
}
|
|
}
|
|
|
|
const { sorted, sortKey, sortDir, requestSort } = useSortable(filtered);
|
|
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
|
|
|
function exportCsv() {
|
|
downloadCsv(
|
|
"ip-addresses.csv",
|
|
["IP Address", "Label", "Vendor", "Location", "Notes", "DNS Records"],
|
|
(sorted ?? []).map((e) => [
|
|
e.ipAddress,
|
|
e.label ?? "",
|
|
e.vendor ?? "",
|
|
e.location ?? "",
|
|
e.notes ?? "",
|
|
e.matchingDnsRecords.join("; "),
|
|
]),
|
|
);
|
|
}
|
|
|
|
const showForm = adding || editing;
|
|
|
|
return (
|
|
<>
|
|
<h2 className="page-title mb-3">IP Addresses</h2>
|
|
<ErrorNotice error={error} />
|
|
{syncResult && <div className="alert alert-success">Synced from {syncResult}</div>}
|
|
|
|
<div className="card mb-3">
|
|
<div className="card-body">
|
|
<div className="d-flex flex-wrap align-items-center gap-2">
|
|
<label className="form-check mb-0">
|
|
<input
|
|
type="checkbox"
|
|
className="form-check-input"
|
|
checked={hideExcluded}
|
|
onChange={(e) => setHideExcluded(e.target.checked)}
|
|
/>
|
|
<span className="form-check-label">
|
|
Hide excluded addresses{excludedCount > 0 && ` (${excludedCount})`}
|
|
</span>
|
|
</label>
|
|
<button type="button" className="btn btn-link btn-sm p-0 ms-2" onClick={() => setShowRanges((s) => !s)}>
|
|
{showRanges ? "Hide" : "Manage"} excluded ranges
|
|
</button>
|
|
</div>
|
|
{showRanges && (
|
|
<div className="mt-2">
|
|
<div className="text-secondary small mb-2">
|
|
Addresses in these ranges are left out here and on the Consistency report — the same setting either
|
|
page manages. Meant for networks that aren't part of your LAN, like Docker's, which repeat the same
|
|
subnet on many hosts.
|
|
</div>
|
|
<div className="d-flex flex-wrap gap-1 mb-2">
|
|
{excludedRanges.length === 0 && <span className="text-secondary small">Nothing excluded.</span>}
|
|
{excludedRanges.map((r) => (
|
|
<span key={r} className="badge bg-secondary-lt text-secondary d-inline-flex align-items-center">
|
|
<code className="bg-transparent p-0">{r}</code>
|
|
{canEdit && (
|
|
<button
|
|
type="button"
|
|
className="btn-close ms-1"
|
|
style={{ fontSize: "0.5rem" }}
|
|
aria-label={`Stop excluding ${r}`}
|
|
disabled={savingRanges}
|
|
onClick={() => void saveRanges(excludedRanges.filter((x) => x !== r))}
|
|
/>
|
|
)}
|
|
</span>
|
|
))}
|
|
</div>
|
|
{canEdit && (
|
|
<form onSubmit={addRange} className="d-flex gap-2" style={{ maxWidth: 460 }}>
|
|
<input
|
|
className="form-control form-control-sm"
|
|
placeholder="e.g. 172.17.0.0/16 or 10.1.2.3"
|
|
value={newRange}
|
|
onChange={(e) => setNewRange(e.target.value)}
|
|
/>
|
|
<button type="submit" className="btn btn-sm btn-primary" disabled={savingRanges || !newRange.trim()}>
|
|
Exclude
|
|
</button>
|
|
</form>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{canEdit && showForm && (
|
|
<div className="card mb-3">
|
|
<div className="card-header">
|
|
<h3 className="card-title">{editing ? `Edit ${editing.ipAddress}` : "Add an IP address"}</h3>
|
|
</div>
|
|
<form onSubmit={submit}>
|
|
<div className="card-body row g-3">
|
|
<div className="col-md-3">
|
|
<label className="form-label">IP address</label>
|
|
<input
|
|
className="form-control"
|
|
required
|
|
disabled={!!editing}
|
|
placeholder="203.0.113.10 or 2001:db8::1"
|
|
value={form.ipAddress}
|
|
onChange={(e) => setForm({ ...form, ipAddress: e.target.value })}
|
|
/>
|
|
{!editing && <div className="form-hint">Cannot be changed after creation.</div>}
|
|
</div>
|
|
<div className="col-md-3">
|
|
<label className="form-label">Label</label>
|
|
<input
|
|
className="form-control"
|
|
placeholder="Web Server 1"
|
|
value={form.label}
|
|
onChange={(e) => setForm({ ...form, label: e.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="col-md-2">
|
|
<label className="form-label">Vendor / provider</label>
|
|
<input
|
|
className="form-control"
|
|
placeholder="Hetzner"
|
|
value={form.vendor}
|
|
onChange={(e) => setForm({ ...form, vendor: e.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="col-md-2">
|
|
<label className="form-label">Location</label>
|
|
<input
|
|
className="form-control"
|
|
placeholder="Frankfurt"
|
|
value={form.location}
|
|
onChange={(e) => setForm({ ...form, location: e.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="col-md-2">
|
|
<label className="form-label">Notes</label>
|
|
<input
|
|
className="form-control"
|
|
value={form.notes}
|
|
onChange={(e) => setForm({ ...form, notes: e.target.value })}
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="card-footer d-flex gap-2">
|
|
<button type="submit" className="btn btn-primary" disabled={saving}>
|
|
{editing ? "Save changes" : "Add IP address"}
|
|
</button>
|
|
<button type="button" className="btn" onClick={cancelForm}>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
)}
|
|
|
|
<div className="card">
|
|
<TableToolbar
|
|
search={search}
|
|
onSearch={setSearch}
|
|
placeholder="Search IP, label, vendor, location…"
|
|
shown={filtered.length}
|
|
total={entries?.length}
|
|
actions={
|
|
<>
|
|
{canEdit && !showForm && (
|
|
<button className="btn btn-sm btn-primary" onClick={startAdd}>
|
|
Add IP address
|
|
</button>
|
|
)}
|
|
{canEdit && (
|
|
<>
|
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("tailscale")} disabled={!!syncing}>
|
|
{syncing === "tailscale" ? "Syncing…" : "Sync from Tailscale"}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("proxmox")} disabled={!!syncing}>
|
|
{syncing === "proxmox" ? "Syncing…" : "Sync from Proxmox"}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("phpipam")} disabled={!!syncing}>
|
|
{syncing === "phpipam" ? "Syncing…" : "Sync from phpIPAM"}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("unifi")} disabled={!!syncing}>
|
|
{syncing === "unifi" ? "Syncing…" : "Sync from UniFi"}
|
|
</button>
|
|
</>
|
|
)}
|
|
</>
|
|
}
|
|
onExport={exportCsv}
|
|
/>
|
|
{canEdit && selection.count > 0 && (
|
|
<div className="card-header bg-blue-lt d-flex align-items-center gap-2">
|
|
<span>{selection.count} selected</span>
|
|
<button className="btn btn-sm btn-outline-danger" onClick={bulkDelete} disabled={bulkDeleting}>
|
|
{bulkDeleting ? "Deleting…" : "Delete selected"}
|
|
</button>
|
|
<button className="btn btn-sm btn-link" onClick={selection.clear}>
|
|
Clear selection
|
|
</button>
|
|
</div>
|
|
)}
|
|
<div className="table-responsive">
|
|
<table className="table table-vcenter card-table">
|
|
<thead>
|
|
<tr>
|
|
{canEdit && (
|
|
<th className="w-1">
|
|
<input
|
|
type="checkbox"
|
|
className="form-check-input m-0"
|
|
checked={(pageItems ?? []).length > 0 && (pageItems ?? []).every((e) => selection.isSelected(e.id))}
|
|
onChange={() => selection.toggleAll((pageItems ?? []).map((e) => e.id))}
|
|
/>
|
|
</th>
|
|
)}
|
|
<SortableTh<IpamEntry> label="IP address" sortKeyName="ipAddress" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IpamEntry> label="Label" sortKeyName="label" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IpamEntry> label="Vendor" sortKeyName="vendor" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<IpamEntry> label="Location" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<th>DNS records</th>
|
|
{canEdit && <th className="w-1">Actions</th>}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{(pageItems ?? []).map((entry) => (
|
|
<tr key={entry.id}>
|
|
{canEdit && (
|
|
<td>
|
|
<input
|
|
type="checkbox"
|
|
className="form-check-input m-0"
|
|
checked={selection.isSelected(entry.id)}
|
|
onChange={() => selection.toggle(entry.id)}
|
|
/>
|
|
</td>
|
|
)}
|
|
<td>
|
|
<span className={`badge ${isIpv6(entry.ipAddress) ? "bg-purple-lt" : "bg-blue-lt"} me-2`}>
|
|
{isIpv6(entry.ipAddress) ? "IPv6" : "IPv4"}
|
|
</span>
|
|
{entry.ipAddress}
|
|
{entry.excluded && <span className="badge bg-secondary-lt text-secondary ms-2">excluded</span>}
|
|
</td>
|
|
<td>{entry.label ?? "—"}</td>
|
|
<td>
|
|
{entry.vendor ?? "—"}
|
|
{entry.source && <span className="badge bg-cyan-lt ms-2">synced from {entry.source}</span>}
|
|
</td>
|
|
<td>{entry.location ?? "—"}</td>
|
|
<td className="text-secondary">
|
|
{entry.matchingDnsRecords.length > 0 ? entry.matchingDnsRecords.join(", ") : "—"}
|
|
</td>
|
|
{canEdit && (
|
|
<td>
|
|
<div className="btn-list flex-nowrap">
|
|
<button className="btn btn-sm" onClick={() => startEdit(entry)}>
|
|
Edit
|
|
</button>
|
|
{!entry.excluded && (
|
|
<button className="btn btn-sm" onClick={() => excludeAround(entry)} title="Hide this and every address in the same range">
|
|
Exclude…
|
|
</button>
|
|
)}
|
|
<button className="btn btn-sm btn-outline-danger" onClick={() => remove(entry)}>
|
|
Delete
|
|
</button>
|
|
</div>
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))}
|
|
{entries === null && <LoadingRow colSpan={canEdit ? 7 : 5} />}
|
|
{entries !== null && (sorted ?? []).length === 0 && (
|
|
<EmptyRow colSpan={canEdit ? 7 : 5} {...(entries && entries.length > 0 ? { filtered: () => { setSearch(""); setHideExcluded(false); }, hint: "Every tracked address is excluded or filtered out. Show the excluded ones, or clear the search, to see them." } : { title: "No IP addresses tracked yet", hint: "Track the addresses you hand out, so you can see what is taken, what is free and what clashes.", action: canEdit ? { label: "Add an address", onClick: startAdd } : undefined })} />
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
|
|
</div>
|
|
</>
|
|
);
|
|
}
|