Port presets: name ports automatically, scan many hosts for a preset, apply names in bulk

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-30 22:39:52 +01:00
1 parent 93aaf5476d
commit fca2dc0338
24 files changed
+9764 -40

No files matched your search

+50
View File
@@ -396,6 +396,8 @@ export interface AgentPortRow {
process: string | null;
localOnly: boolean;
lastSeenAt: string | null;
/** What a port preset calls this port (22 → SSH); null when no preset has it. */
service: string | null;
}
export interface AgentPortsResponse {
@@ -2596,6 +2598,46 @@ export interface PortEntry {
state: "open" | "reserved";
/** Began listening after the first report and nobody has noted it: a "new port" alert is on. */
isNew: boolean;
/** What a port preset calls this port (3389 → RDP); null when no preset has it. */
service: string | null;
}
export interface PresetPort {
port: number;
protocol: "tcp" | "udp";
label: string;
}
export interface PortPreset {
id: number;
name: string;
ports: PresetPort[];
updatedAt: string;
}
export interface PresetHostResult {
serverId: number;
name: string;
address: string | null;
state: "scanned" | "no_answer" | "skipped" | "error" | "busy";
message: string | null;
open: number[];
closed: number[];
filtered: number;
}
export interface PresetScanResponse {
preset: { id: number; name: string };
/** The TCP ports looked at, in order. */
ports: number[];
/** Port (as text) → the preset's name for it. */
labels: Record<string, string>;
results: PresetHostResult[];
}
export interface PresetApplyResponse {
preset: { id: number; name: string };
results: { serverId: number; name: string; labelled: PresetPort[]; skipped: { port: number; protocol: "tcp" | "udp"; reason: string }[] }[];
}
export interface PortScanSummary {
@@ -3690,6 +3732,14 @@ export const api = {
testClose: (integrationId: number) => request<{ ok: boolean; problems: string[]; notes: string[] }>("/api/alert-tickets/test-close", { method: "POST", body: JSON.stringify({ integrationId }) }),
run: () => request<{ summary: AlertTicketRunSummary; status: AlertTicketOverview["status"] }>("/api/alert-tickets/run", { method: "POST" }),
},
portPresets: {
list: () => request<{ presets: PortPreset[] }>("/api/port-presets"),
create: (data: { name: string; ports: PresetPort[] }) => request<{ preset: PortPreset }>("/api/port-presets", { method: "POST", body: JSON.stringify(data) }),
update: (id: number, data: { name: string; ports: PresetPort[] }) => request<{ preset: PortPreset }>(`/api/port-presets/${id}`, { method: "PUT", body: JSON.stringify(data) }),
remove: (id: number) => request<void>(`/api/port-presets/${id}`, { method: "DELETE" }),
scan: (id: number, targets: { serverId: number; address?: string }[]) => request<PresetScanResponse>(`/api/port-presets/${id}/scan`, { method: "POST", body: JSON.stringify({ targets }) }),
apply: (id: number, data: { serverIds: number[]; onlyOpen?: boolean; overwrite?: boolean }) => request<PresetApplyResponse>(`/api/port-presets/${id}/apply`, { method: "POST", body: JSON.stringify(data) }),
},
ports: {
agent: () => request<AgentPortsResponse>("/api/ports/agent"),
forwards: {
+349
View File
@@ -0,0 +1,349 @@
import { useEffect, useMemo, useState } from "react";
import { api, type PortPreset, type PresetApplyResponse, type PresetScanResponse, type ServerRecord } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { formatPortLines, parsePortLines } from "../utils/portPresetText";
import { toast } from "../utils/toast";
import { removeWithUndo } from "../utils/undoable";
import { ErrorNotice } from "./Notice";
/** The chips of a preset: "22 SSH · 3389 RDP …", UDP marked. */
function PortChips({ preset }: { preset: PortPreset }) {
return (
<div className="d-flex flex-wrap gap-1">
{preset.ports.map((p) => (
<span key={`${p.protocol}:${p.port}`} className="badge bg-secondary-lt text-secondary" title={`${p.port}/${p.protocol}`}>
{p.port}
{p.protocol === "udp" ? "/udp" : ""} {p.label}
</span>
))}
</div>
);
}
/**
* Check a preset on several hosts: which of its ports are open on each, in one table, from a scan from this app (TCP; private addresses only, as the Ports card's scan). The open ports can
* then be given the preset's names on all those hosts at once.
*/
function CheckHosts({ preset, canEdit, onClose }: { preset: PortPreset; canEdit: boolean; onClose: () => void }) {
const [servers, setServers] = useState<ServerRecord[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [picked, setPicked] = useState<Set<number>>(new Set());
const [filter, setFilter] = useState("");
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<PresetScanResponse | null>(null);
const [overwrite, setOverwrite] = useState(false);
useEffect(() => {
api.servers
.list()
.then((r) => setServers(r.servers))
.catch((err) => setError(readableError(err)));
}, []);
useEffect(() => setResult(null), [preset.id]);
const shown = useMemo(() => {
const q = filter.trim().toLowerCase();
return (servers ?? []).filter((s) => !q || s.name.toLowerCase().includes(q) || (s.hostname ?? "").toLowerCase().includes(q));
}, [servers, filter]);
const tcp = preset.ports.filter((p) => p.protocol === "tcp");
const toggle = (id: number) =>
setPicked((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
async function scan() {
setBusy(true);
setError(null);
setResult(null);
try {
setResult(await api.portPresets.scan(preset.id, [...picked].map((serverId) => ({ serverId }))));
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function apply() {
if (!result) return;
const hosts = result.results.filter((r) => r.state === "scanned" && r.open.length > 0);
const open = hosts.reduce((n, r) => n + r.open.length, 0);
if (
!(await confirmDialog({
title: "Name the open ports",
message: `Write the names from "${preset.name}" on the ${open} open ${open === 1 ? "port" : "ports"} found on ${hosts.length} ${hosts.length === 1 ? "host" : "hosts"}. A port with a name counts as noted, so the new-port alert stays quiet for it.${overwrite ? " Names somebody wrote are replaced." : " Names somebody wrote are kept."}`,
confirmLabel: "Write the names",
}))
)
return;
setBusy(true);
try {
const res: PresetApplyResponse = await api.portPresets.apply(preset.id, { serverIds: hosts.map((h) => h.serverId), onlyOpen: true, overwrite });
const labelled = res.results.reduce((n, r) => n + r.labelled.length, 0);
const kept = res.results.reduce((n, r) => n + r.skipped.filter((s) => s.reason === "has_label").length, 0);
toast.success(`Named ${labelled} ${labelled === 1 ? "port" : "ports"} on ${res.results.filter((r) => r.labelled.length > 0).length} ${res.results.length === 1 ? "host" : "hosts"}${kept > 0 ? `; ${kept} with a name of their own were left` : ""}.`);
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(false);
}
}
const scanned = result?.results.filter((r) => r.state === "scanned") ?? [];
const labelOf = (port: number) => result?.labels[String(port)] ?? "";
return (
<div className="border-top mt-2 pt-3">
<div className="d-flex align-items-center mb-2">
<h4 className="mb-0">Check “{preset.name}” on hosts</h4>
<button className="btn btn-sm ms-auto" onClick={onClose}>
Close
</button>
</div>
<div>
<ErrorNotice error={error} />
{tcp.length === 0 ? (
<div className="text-secondary">This preset has no TCP ports, and a scan only looks at TCP.</div>
) : (
<>
<p className="text-secondary small">
Scans the {tcp.length} TCP {tcp.length === 1 ? "port" : "ports"} of the preset on each host you pick, from this app, at the host's first known address (a host with none is skipped). What it finds is remembered as for any scan. A scan can see what is
reachable from here, not what is blocked by a firewall; only private addresses are scanned.
</p>
<div className="d-flex flex-wrap align-items-center gap-2 mb-2">
<input className="form-control form-control-sm" style={{ maxWidth: 240 }} placeholder="Filter hosts" value={filter} onChange={(e) => setFilter(e.target.value)} />
<button className="btn btn-sm" onClick={() => setPicked(new Set([...picked, ...shown.map((s) => s.id)]))}>
Pick the {shown.length} shown
</button>
<button className="btn btn-sm" onClick={() => setPicked(new Set())} disabled={picked.size === 0}>
None
</button>
<span className="text-secondary small">{picked.size} picked</span>
{canEdit && (
<button className="btn btn-primary btn-sm ms-auto" onClick={() => void scan()} disabled={busy || picked.size === 0}>
{busy && !result ? "Scanning…" : `Scan ${picked.size || ""} ${picked.size === 1 ? "host" : "hosts"}`}
</button>
)}
</div>
<div className="border rounded p-2 mb-3" style={{ maxHeight: 220, overflowY: "auto" }}>
{servers === null && <div className="text-secondary small">Loading…</div>}
{servers !== null && shown.length === 0 && <div className="text-secondary small">No host matches.</div>}
<div className="row">
{shown.map((s) => (
<div key={s.id} className="col-sm-6 col-lg-4">
<label className="form-check mb-1">
<input type="checkbox" className="form-check-input" checked={picked.has(s.id)} onChange={() => toggle(s.id)} />
<span className="form-check-label">
{s.name}
{s.hostname && s.hostname !== s.name && <span className="text-secondary small"> · {s.hostname}</span>}
</span>
</label>
</div>
))}
</div>
</div>
</>
)}
{result && (
<>
<div className="table-responsive">
<table className="table table-vcenter table-sm">
<thead>
<tr>
<th>Host</th>
<th>Address</th>
{result.ports.map((p) => (
<th key={p} className="text-center">
{p}
<div className="text-secondary fw-normal small">{labelOf(p)}</div>
</th>
))}
</tr>
</thead>
<tbody>
{result.results.map((r) => (
<tr key={r.serverId}>
<td>{r.name}</td>
<td className="text-secondary">{r.address ?? "—"}</td>
{r.state === "scanned" ? (
result.ports.map((p) => (
<td key={p} className="text-center">
{r.open.includes(p) ? <span className="badge bg-green-lt text-green">open</span> : r.closed.includes(p) ? <span className="text-secondary">–</span> : <span className="text-secondary" title="Never answered: a firewall may be dropping it">?</span>}
</td>
))
) : (
<td colSpan={result.ports.length} className={r.state === "no_answer" ? "text-yellow" : "text-secondary"}>
{r.message}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
<div className="text-secondary small mb-2">
{scanned.length} of {result.results.length} hosts scanned; {scanned.reduce((n, r) => n + r.open.length, 0)} open {scanned.reduce((n, r) => n + r.open.length, 0) === 1 ? "port" : "ports"}. <strong>open</strong>: it accepted a connection · – : it refused ·{" "}
? : it never answered.
</div>
{canEdit && scanned.some((r) => r.open.length > 0) && (
<div className="d-flex flex-wrap align-items-center gap-3">
<button className="btn btn-outline-primary" onClick={() => void apply()} disabled={busy}>
Name the open ports on these hosts
</button>
<label className="form-check mb-0">
<input type="checkbox" className="form-check-input" checked={overwrite} onChange={(e) => setOverwrite(e.target.checked)} />
<span className="form-check-label">Replace names somebody wrote</span>
</label>
</div>
)}
</>
)}
</div>
</div>
);
}
/** Port presets: a named list of ports (Remote access: SSH, RDP …) that gives a port its name wherever it shows, and can be checked on and written onto many hosts at once. */
export default function PortPresets({ canEdit }: { canEdit: boolean }) {
const [presets, setPresets] = useState<PortPreset[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [form, setForm] = useState<{ id: number | null; name: string; text: string } | null>(null);
const [formErrors, setFormErrors] = useState<string[]>([]);
const [saving, setSaving] = useState(false);
const [checking, setChecking] = useState<number | null>(null);
function load() {
api.portPresets
.list()
.then((r) => {
setPresets(r.presets);
setError(null);
})
.catch((err) => setError(readableError(err)));
}
useEffect(load, []);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!form) return;
const { ports, errors } = parsePortLines(form.text);
if (ports.length === 0 && errors.length === 0) errors.push("Give at least one port");
setFormErrors(errors);
if (errors.length > 0) return;
setSaving(true);
try {
if (form.id === null) await api.portPresets.create({ name: form.name.trim(), ports });
else await api.portPresets.update(form.id, { name: form.name.trim(), ports });
toast.success("Saved.");
setForm(null);
load();
} catch (err) {
setFormErrors([readableError(err)]);
} finally {
setSaving(false);
}
}
async function remove(p: PortPreset) {
if (checking === p.id) setChecking(null);
await removeWithUndo({
remove: () => api.portPresets.remove(p.id),
restore: () => api.portPresets.create({ name: p.name, ports: p.ports }),
message: `Removed the preset "${p.name}".`,
reload: load,
});
}
return (
<>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Port presets</h3>
<div className="card-actions">
{canEdit && !form && (
<button className="btn btn-primary btn-sm" onClick={() => { setForm({ id: null, name: "", text: "" }); setFormErrors([]); }}>
Add a preset
</button>
)}
</div>
</div>
<div className="card-body">
<p className="text-secondary small">
A preset is a named list of ports — <em>Remote access</em>: SSH, RDP, VNC; <em>Databases</em>: MySQL, PostgreSQL … — written once. A port in any preset is <strong>named</strong> wherever it shows (3389 → RDP, on the Ports cards and here) without a label typed for each host; you can <strong>check a preset on several hosts</strong> at
once and see which have which port open; and <strong>name the open ports on all of them</strong> in one go. The ready-made ones are ordinary presets: change or delete them.
</p>
<ErrorNotice error={error} />
{!presets && !error && <div className="text-secondary">Loading…</div>}
{presets && presets.length === 0 && !form && <div className="text-secondary">No preset yet.{canEdit ? " Add one to name ports and to check hosts for them." : ""}</div>}
{presets?.map((p) => (
<div key={p.id} className="border rounded p-2 mb-2">
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<strong>{p.name}</strong>
<span className="text-secondary small">
{p.ports.length} {p.ports.length === 1 ? "port" : "ports"}
</span>
<span className="ms-auto btn-list flex-nowrap">
<button className={`btn btn-sm ${checking === p.id ? "btn-primary" : ""}`} onClick={() => setChecking(checking === p.id ? null : p.id)}>
Check hosts
</button>
{canEdit && (
<>
<button className="btn btn-sm" onClick={() => { setForm({ id: p.id, name: p.name, text: formatPortLines(p.ports) }); setFormErrors([]); }}>
Edit
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(p)}>
Remove
</button>
</>
)}
</span>
</div>
<PortChips preset={p} />
{checking === p.id && <CheckHosts preset={p} canEdit={canEdit} onClose={() => setChecking(null)} />}
</div>
))}
{canEdit && form && (
<form onSubmit={save} className="border rounded p-3 mt-3">
<div className="mb-3">
<label className="form-label" htmlFor="pp-name">
Name
</label>
<input id="pp-name" className="form-control" required maxLength={60} placeholder="Remote access" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} autoFocus />
</div>
<div className="mb-2">
<label className="form-label" htmlFor="pp-ports">
Ports, one to a line
</label>
<textarea id="pp-ports" className="form-control font-monospace" rows={8} required placeholder={"22 SSH\n3389 RDP\n5900 VNC\n53/udp DNS"} value={form.text} onChange={(e) => setForm({ ...form, text: e.target.value })} />
<div className="form-hint">
The port number, then what it is. TCP unless you write <code>/udp</code> (a scan looks at TCP only; a UDP port is only given its name). Lines starting with # are skipped. Up to 60 ports.
</div>
</div>
{formErrors.length > 0 && (
<ul className="text-danger small mb-2">
{formErrors.map((m) => (
<li key={m}>{m}</li>
))}
</ul>
)}
<div className="btn-list">
<button className="btn btn-primary" disabled={saving || form.name.trim() === ""}>
{saving ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" onClick={() => setForm(null)}>
Cancel
</button>
</div>
</form>
)}
</div>
</div>
</>
);
}
+3 -3
View File
@@ -106,7 +106,7 @@ export default function ServerPorts({
const q = filter.trim().toLowerCase();
const rows = q
? data.ports.filter((p) =>
[String(p.port), p.protocol, p.label, p.comment, p.agent?.process].some((v) => v?.toLowerCase().includes(q)),
[String(p.port), p.protocol, p.label, p.service, p.comment, p.agent?.process].some((v) => v?.toLowerCase().includes(q)),
)
: data.ports;
return sortItems(rows, sortKey, sortDir);
@@ -221,7 +221,7 @@ export default function ServerPorts({
downloadCsv(
"ports.csv",
["Port", "Protocol", "Status", "Service", "Process", "Comment"],
visible.map((p) => [p.port, p.protocol, p.state, p.label ?? "", p.agent?.process ?? "", p.comment ?? ""]),
visible.map((p) => [p.port, p.protocol, p.state, p.label ?? p.service ?? "", p.agent?.process ?? "", p.comment ?? ""]),
);
}
@@ -491,7 +491,7 @@ export default function ServerPorts({
<StatusBadges entry={p} />
</td>
<td>
{p.label ?? <span className="text-secondary">—</span>}
{p.label ?? (p.service ? <span className="text-secondary" title="Named by a port preset (Network → Ports)">{p.service}</span> : <span className="text-secondary">—</span>)}
{p.agent?.process && <div className="text-secondary small">{p.agent.process}</div>}
</td>
<td className="text-secondary">{p.comment ?? "—"}</td>
+9 -3
View File
@@ -17,6 +17,7 @@ import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv";
import { formatAgo } from "../utils/duration";
import { ErrorNotice } from "../components/Notice";
import PortPresets from "../components/PortPresets";
import { EmptyRow, LoadingRow } from "../components/EmptyState";
const emptyForm: PortForwardInput = {
@@ -90,12 +91,13 @@ export default function Ports({ user }: { user: CurrentUser }) {
function exportAgentCsv() {
downloadCsv(
"agent-reported-ports.csv",
["Server", "Hostname", "Protocol", "Port", "Addresses", "Process", "Local only"],
["Server", "Hostname", "Protocol", "Port", "Service", "Addresses", "Process", "Local only"],
(sortedAgentPorts ?? []).map((p) => [
p.serverName,
p.serverHostname ?? "",
p.protocol,
p.port,
p.service ?? "",
p.addresses.join(", "),
p.process ?? "",
p.localOnly ? "yes" : "no",
@@ -184,6 +186,8 @@ export default function Ports({ user }: { user: CurrentUser }) {
<>
<h2 className="page-title mb-3">Ports</h2>
<PortPresets canEdit={canEdit} />
<div className="row g-3 mb-3">
<div className="col-12">
<div className="card">
@@ -209,6 +213,7 @@ export default function Ports({ user }: { user: CurrentUser }) {
<SortableTh<AgentPortRow> label="Server" sortKeyName="serverName" activeKey={agentSortKey} direction={agentSortDir} onSort={requestAgentSort} />
<SortableTh<AgentPortRow> label="Protocol" sortKeyName="protocol" activeKey={agentSortKey} direction={agentSortDir} onSort={requestAgentSort} />
<SortableTh<AgentPortRow> label="Port" sortKeyName="port" activeKey={agentSortKey} direction={agentSortDir} onSort={requestAgentSort} />
<th>Service</th>
<th>Address</th>
<th>Process</th>
<SortableTh<AgentPortRow> label="Last report" sortKeyName="lastSeenAt" activeKey={agentSortKey} direction={agentSortDir} onSort={requestAgentSort} />
@@ -223,6 +228,7 @@ export default function Ports({ user }: { user: CurrentUser }) {
</td>
<td className="text-uppercase text-secondary">{p.protocol}</td>
<td>{p.port}</td>
<td className="text-secondary" title={p.service ? "Named by a port preset" : undefined}>{p.service ?? "—"}</td>
<td className="text-secondary">
{p.addresses.join(", ")}
{p.localOnly && <span className="badge bg-secondary-lt text-secondary ms-2">local only</span>}
@@ -231,9 +237,9 @@ export default function Ports({ user }: { user: CurrentUser }) {
<td className="text-secondary"><TimeAgo value={p.lastSeenAt} /></td>
</tr>
))}
{agentPorts === null && <LoadingRow colSpan={6} />}
{agentPorts === null && <LoadingRow colSpan={7} />}
{agentPorts !== null && agentPorts.length === 0 && (
<EmptyRow colSpan={6} title="No listening ports reported yet" hint="Each server's agent lists what is listening with its next report. Install or update the agent to see ports here." action={{ label: "Go to Servers", to: "/servers" }} />
<EmptyRow colSpan={7} title="No listening ports reported yet" hint="Each server's agent lists what is listening with its next report. Install or update the agent to see ports here." action={{ label: "Go to Servers", to: "/servers" }} />
)}
</tbody>
</table>
+45
View File
@@ -0,0 +1,45 @@
// A port preset written as text, one port to a line, and read back: "3389 RDP", "22/tcp SSH", "53/udp DNS". The editor on the Ports page uses it, so a preset can be typed or pasted
// rather than built row by row.
export interface ParsedPresetPort {
port: number;
protocol: "tcp" | "udp";
label: string;
}
export const MAX_PRESET_PORTS = 60;
/** Pure: the ports in a text, and what is wrong with the lines that are not one. A blank line and a line starting with # are skipped; TCP is the protocol unless /udp is written. */
export function parsePortLines(text: string): { ports: ParsedPresetPort[]; errors: string[] } {
const ports: ParsedPresetPort[] = [];
const errors: string[] = [];
const seen = new Set<string>();
text.split(/\r?\n/).forEach((raw, i) => {
const line = raw.trim();
if (line === "" || line.startsWith("#")) return;
const m = /^(\d{1,5})(?:\s*\/\s*(tcp|udp))?\s*[:=,\-–]?\s*(.*)$/i.exec(line);
const at = `Line ${i + 1}`;
if (!m) {
errors.push(`${at}: start with the port number ("${line.slice(0, 20)}")`);
return;
}
const port = Number(m[1]);
const protocol = (m[2]?.toLowerCase() ?? "tcp") as "tcp" | "udp";
const label = m[3].trim();
if (port < 1 || port > 65535) errors.push(`${at}: ${port} is not a port (1–65535)`);
else if (label === "") errors.push(`${at}: say what ${port} is`);
else if (label.length > 60) errors.push(`${at}: the name is longer than 60 characters`);
else if (seen.has(`${protocol}:${port}`)) errors.push(`${at}: ${port}/${protocol} is in the list twice`);
else {
seen.add(`${protocol}:${port}`);
ports.push({ port, protocol, label });
}
});
if (ports.length > MAX_PRESET_PORTS) errors.push(`At most ${MAX_PRESET_PORTS} ports in a preset`);
return { ports, errors };
}
/** Pure: a preset's ports as text, for the editor (TCP is not written out). */
export function formatPortLines(ports: ParsedPresetPort[]): string {
return ports.map((p) => `${p.port}${p.protocol === "udp" ? "/udp" : ""} ${p.label}`).join("\n");
}