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:
1 parent
93aaf5476d
commit
fca2dc0338
24 files changed
+9764
-40
No files matched your search
+15
-4
@@ -23,8 +23,8 @@ 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` … `0078`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
|
||||
| **Tables** | 88 application tables, plus drizzle's own `__drizzle_migrations`. |
|
||||
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0079`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
|
||||
| **Tables** | 89 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`.
|
||||
|
||||
@@ -107,10 +107,10 @@ erDiagram
|
||||
event_webhooks ||--o{ webhook_deliveries : "cascade"
|
||||
```
|
||||
|
||||
These 23 tables are without a foreign key to another table, and — but for `integration_credentials`, which `integrations` and `dns_providers` point at — with none from another table to them; where they refer to something else it is by id or name, see
|
||||
These 24 tables are without a foreign key to another table, and — but for `integration_credentials`, which `integrations` and `dns_providers` point at — with none from another table to them; where they refer to something else it is by id or name, see
|
||||
[soft references](#soft-references-not-foreign-keys): `settings`, `secrets`, `ipam_entries`, `domains`, `diag_log`, `notification_queue`, `consistency_ignores`, `tag_definitions`,
|
||||
`maintenance_windows`, `maintenance_aliases`, `maintenance_schedules`, `metrics_tokens`, `restore_tests`, `dependencies`, `runbooks`, `renewals`, `assets`, `notes`,
|
||||
`alert_rules`, `alert_snoozes`, `alert_kind_runbooks`, `release_cache` and `integration_credentials`.
|
||||
`alert_rules`, `alert_snoozes`, `alert_kind_runbooks`, `release_cache`, `port_presets` and `integration_credentials`.
|
||||
|
||||
## Tables
|
||||
|
||||
@@ -367,6 +367,17 @@ records them; it can't check or change them.
|
||||
| `comment` | text | |
|
||||
| `created_at`, `updated_at` | text NOT NULL | |
|
||||
|
||||
#### `port_presets`
|
||||
|
||||
A named list of ports ("Remote access": SSH, RDP, VNC). A port in any preset is named wherever it is shown, can be scanned for on many servers at once, and can have its name written onto the servers where it is open (`server_ports.label`). The ready-made ones are written once, into an empty table (flag `_internal:portPresetsSeeded` in `settings`), and are ordinary rows after that.
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | integer PK | |
|
||||
| `name` | text NOT NULL, unique | Compared without regard to case by the API. |
|
||||
| `ports` | text NOT NULL, default `[]` | JSON: `[{ "port": 3389, "protocol": "tcp", "label": "RDP" }]`; 1–60 entries, no port + protocol twice. |
|
||||
| `created_at`, `updated_at` | text NOT NULL | |
|
||||
|
||||
### Integrations and credentials
|
||||
|
||||
#### `integrations`
|
||||
|
||||
@@ -1022,6 +1022,8 @@ host (`ss`), which catches services listening on localhost only — a scan from
|
||||
elsewhere can't see those, so they'd otherwise look free. Re-run the agent
|
||||
install one-liner on a host to pick that up.
|
||||
|
||||
**Port presets** (Network → Ports). A preset is a named list of ports written once — *Remote access* (SSH, RDP, VNC, WinRM), *Databases* (MySQL, PostgreSQL, Redis, MongoDB …), *Web*, *File sharing*, *Homelab tools* come ready-made, and are ordinary presets you can change or delete. Add your own by typing one port to a line (`3389 RDP`, `53/udp DNS`). A preset does three things: it **names ports** — a port in any preset shows its name (3389 → RDP) on every server's Ports card, in the agent table and in the new-port alert ("a new port is listening — 3389/tcp RDP"), without a label typed for each host, and a name you write yourself always wins; it **checks hosts** — pick any number of servers and see in one table which of the preset's TCP ports are open on each, from a scan from the app (private addresses only, at the server's first known address; what it finds is remembered like any scan); and it **names the open ports on all of them** in one go, keeping names somebody already wrote unless you say to replace them. Note that a port with a name counts as noted, so writing names also quiets the new-port alert for those ports. A scan only looks at TCP; a UDP port in a preset is only given its name. Operators change presets; everyone sees them.
|
||||
|
||||
**Network → Ports** is the cross-server counterpart: one page listing every
|
||||
port every agent currently reports as listening, across all servers at once
|
||||
(protocol, address, process, last report time), each linking back to its
|
||||
|
||||
@@ -115,6 +115,7 @@ even further, to admin only:
|
||||
admin-only (applying an existing tag to a server needs operator).
|
||||
- **Ports**: everyone can see both the agent-reported and manual tables;
|
||||
adding, editing, or deleting a manual port opening needs operator.
|
||||
- **Port presets** (Network → Ports): everyone can see them and the names they give ports; creating, changing and removing one, scanning hosts for one and writing its names onto many hosts' ports need operator.
|
||||
- **Admin Links**: everyone can see and open every server's admin
|
||||
bookmarks, from that server's own page or the summary page; adding,
|
||||
editing, or removing one needs operator, from either place.
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ Every threshold here is a default; where it can be changed, the place is named.
|
||||
| **ZFS / storage pool** | A ZFS pool (or Windows Storage Spaces pool) is not ONLINE | | not configurable |
|
||||
| **Synology volume / disk** | A volume's status is not "normal"; a disk's status or SMART result is not normal, or it is over the bad-sector or under the remaining-life limit | | not configurable |
|
||||
| **Unusual for the time** | CPU load or memory use over the last hour is far above what is normal for this hour of this weekday ([below](#what-is-normal-for-the-time)) | on · warning | Settings → Notifications |
|
||||
| **New port** | A TCP port starts listening that was not there when the agent first reported and that nobody noted on the server's *Ports* card | on | Settings → Notifications |
|
||||
| **New port** | A TCP port starts listening that was not there when the agent first reported and that nobody noted on the server's *Ports* card (a port preset names it in the message: "3389/tcp RDP") | on | Settings → Notifications |
|
||||
| **Network device offline** | A UniFi device has been offline too long | 10 min · critical | Settings → Notifications |
|
||||
| **Operating system support** | A server's OS has passed, or is about to pass, its end of support | within 90 days · note; warning once ended | Settings → Notifications |
|
||||
| **Updates waiting** | The agent reports updates waiting (and, where it can say, security ones and a restart needed) | | Updates page |
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE `port_presets` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`ports` text DEFAULT '[]' NOT NULL,
|
||||
`created_at` text NOT NULL,
|
||||
`updated_at` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `port_presets_name_unique` ON `port_presets` (`name`);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -554,6 +554,13 @@
|
||||
"when": 1793138206158,
|
||||
"tag": "0078_sturdy_typhoid_mary",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 79,
|
||||
"version": "6",
|
||||
"when": 1793390152367,
|
||||
"tag": "0079_cheerful_talkback",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -74,6 +74,7 @@ import { wallRouter } from "./routes/wall.js";
|
||||
import { adguardRouter } from "./routes/adguard.js";
|
||||
import { grafanaRouter } from "./routes/grafana.js";
|
||||
import { versionsRouter } from "./routes/versions.js";
|
||||
import { portPresetsRouter } from "./routes/portPresets.js";
|
||||
import { costsRouter } from "./routes/costs.js";
|
||||
import { nextcloudRouter } from "./routes/nextcloud.js";
|
||||
import { serviceLevelsRouter } from "./routes/serviceLevels.js";
|
||||
@@ -226,6 +227,7 @@ export function createApp() {
|
||||
app.use("/api/adguard", adguardRouter);
|
||||
app.use("/api/grafana", grafanaRouter);
|
||||
app.use("/api/versions", versionsRouter);
|
||||
app.use("/api/port-presets", portPresetsRouter);
|
||||
app.use("/api/costs", costsRouter);
|
||||
app.use("/api/nextcloud", nextcloudRouter);
|
||||
app.use("/api/service-levels", serviceLevelsRouter);
|
||||
|
||||
@@ -716,6 +716,18 @@ export const portForwards = sqliteTable("port_forwards", {
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// ─── Port presets ───────────────────────────────────────────────────────────
|
||||
|
||||
// A named list of ports and what each is — "Remote access": 22 SSH, 3389 RDP — written once and used on every host: to name a port wherever it shows, to scan several hosts for just those
|
||||
// ports, and to write the names onto what is open. `ports` is JSON: [{ port, protocol, label }]. Some ready-made ones are put there the first time (services/portPresets.ts).
|
||||
export const portPresets = sqliteTable("port_presets", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
name: text("name").notNull().unique(),
|
||||
ports: text("ports").notNull().default("[]"),
|
||||
createdAt: text("created_at").notNull(), // ISO
|
||||
updatedAt: text("updated_at").notNull(), // ISO
|
||||
});
|
||||
|
||||
// ─── Domain registrations ───────────────────────────────────────────────────
|
||||
|
||||
export const domainOrigins = ["manual", "zone"] as const;
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { Router } from "express";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { portPresets, servers, serverPorts } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson } from "../services/agentPorts.js";
|
||||
import { getPreset, listPresets, mapLimit, MAX_PRESET_PORTS, scannablePorts, type PresetPort } from "../services/portPresets.js";
|
||||
import { beginScan, endScan, resolveScanTarget, scanPortList } from "../services/portScan.js";
|
||||
import { recordPortScan, scanResponded } from "../services/portScanRecord.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const portPresetsRouter = Router();
|
||||
portPresetsRouter.use(requireAuth);
|
||||
|
||||
/** How many hosts a preset is scanned on at the same time: each scan holds hundreds of sockets open at most, but a whole network at once is a burst nobody asked for. */
|
||||
const HOSTS_AT_ONCE = 3;
|
||||
const MAX_TARGETS = 100;
|
||||
|
||||
const portSchema = z.object({
|
||||
port: z.number().int().min(1).max(65535),
|
||||
protocol: z.enum(["tcp", "udp"]).default("tcp"),
|
||||
label: z.string().trim().min(1).max(60),
|
||||
});
|
||||
|
||||
const presetSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(60),
|
||||
ports: z.array(portSchema).min(1).max(MAX_PRESET_PORTS),
|
||||
})
|
||||
.refine((d) => new Set(d.ports.map((p) => `${p.protocol}:${p.port}`)).size === d.ports.length, { message: "A port is in the list twice." });
|
||||
|
||||
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
|
||||
|
||||
const invalid = (res: import("express").Response, parsed: { error: z.ZodError }) =>
|
||||
res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a preset.", details: parsed.error.flatten() });
|
||||
|
||||
// Everyone signed in sees the presets: they are what ports are called.
|
||||
portPresetsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
res.json({ presets: await listPresets() });
|
||||
}));
|
||||
|
||||
portPresetsRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const parsed = presetSchema.safeParse(req.body);
|
||||
if (!parsed.success) return invalid(res, parsed);
|
||||
const taken = (await listPresets()).some((p) => p.name.toLowerCase() === parsed.data.name.toLowerCase());
|
||||
if (taken) return res.status(409).json({ error: "name_taken", message: "There is a preset with that name already." });
|
||||
const now = new Date().toISOString();
|
||||
const [row] = await db.insert(portPresets).values({ name: parsed.data.name, ports: JSON.stringify(parsed.data.ports), createdAt: now, updatedAt: now }).returning();
|
||||
await recordAudit({ actor: req.currentUser!, category: "server", action: "create_port_preset", targetType: "port_preset", targetId: row.id, detail: { name: row.name, ports: parsed.data.ports.length } });
|
||||
res.status(201).json({ preset: { id: row.id, name: row.name, ports: parsed.data.ports, updatedAt: row.updatedAt } });
|
||||
}));
|
||||
|
||||
portPresetsRouter.put("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const parsed = presetSchema.safeParse(req.body);
|
||||
if (!parsed.success) return invalid(res, parsed);
|
||||
const before = await getPreset(id);
|
||||
if (!before) return res.status(404).json({ error: "not_found" });
|
||||
const taken = (await listPresets()).some((p) => p.id !== id && p.name.toLowerCase() === parsed.data.name.toLowerCase());
|
||||
if (taken) return res.status(409).json({ error: "name_taken", message: "There is a preset with that name already." });
|
||||
const now = new Date().toISOString();
|
||||
await db.update(portPresets).set({ name: parsed.data.name, ports: JSON.stringify(parsed.data.ports), updatedAt: now }).where(eq(portPresets.id, id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "server", action: "update_port_preset", targetType: "port_preset", targetId: id, detail: { name: parsed.data.name, ports: parsed.data.ports.length } });
|
||||
res.json({ preset: { id, name: parsed.data.name, ports: parsed.data.ports, updatedAt: now } });
|
||||
}));
|
||||
|
||||
portPresetsRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const before = await getPreset(id);
|
||||
if (!before) return res.status(404).json({ error: "not_found" });
|
||||
await db.delete(portPresets).where(eq(portPresets.id, id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "server", action: "delete_port_preset", targetType: "port_preset", targetId: id, detail: { name: before.name } });
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
// ─── Scanning hosts for a preset ────────────────────────────────────────────
|
||||
|
||||
const scanSchema = z.object({
|
||||
targets: z
|
||||
.array(z.object({ serverId: z.number().int().positive(), address: z.string().trim().max(255).optional() }))
|
||||
.min(1)
|
||||
.max(MAX_TARGETS),
|
||||
});
|
||||
|
||||
export interface PresetHostResult {
|
||||
serverId: number;
|
||||
name: string;
|
||||
/** The address that was scanned; null when none could be found. */
|
||||
address: string | null;
|
||||
/** scanned: answered; no_answer: nothing answered (down, or dropping everything — says nothing of its ports); skipped: no address; error: could not be scanned; busy: a scan of it was running. */
|
||||
state: "scanned" | "no_answer" | "skipped" | "error" | "busy";
|
||||
message: string | null;
|
||||
open: number[];
|
||||
/** Refused: the host answered "nothing here". */
|
||||
closed: number[];
|
||||
/** Never answered (a firewall dropping packets). */
|
||||
filtered: number;
|
||||
}
|
||||
|
||||
/** The address to scan for a server that was not told one: the first address it is known by, else its host name. */
|
||||
export function addressOf(server: { ipAddresses: string | null; hostname: string | null }): string | null {
|
||||
const ips = parseJson<unknown>(server.ipAddresses, []);
|
||||
const first = Array.isArray(ips) ? ips.find((i): i is string => typeof i === "string" && i.trim() !== "") : undefined;
|
||||
return first?.trim() ?? (server.hostname?.trim() || null);
|
||||
}
|
||||
|
||||
portPresetsRouter.post("/:id/scan", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const parsed = scanSchema.safeParse(req.body);
|
||||
if (!parsed.success) return invalid(res, parsed);
|
||||
const preset = await getPreset(id);
|
||||
if (!preset) return res.status(404).json({ error: "not_found" });
|
||||
const ports = scannablePorts(preset);
|
||||
if (ports.length === 0) return res.status(400).json({ error: "nothing_to_scan", message: "This preset has no TCP ports — a scan only looks at TCP." });
|
||||
const wanted = new Set(ports);
|
||||
// A server named twice is scanned once, as the first request for it says.
|
||||
const targets = parsed.data.targets.filter((t, i, all) => all.findIndex((x) => x.serverId === t.serverId) === i);
|
||||
|
||||
const rows = await db.select({ id: servers.id, name: servers.name, ipAddresses: servers.ipAddresses, hostname: servers.hostname }).from(servers).where(inArray(servers.id, targets.map((t) => t.serverId)));
|
||||
const byId = new Map(rows.map((r) => [r.id, r]));
|
||||
|
||||
const results = await mapLimit(targets, HOSTS_AT_ONCE, async (t): Promise<PresetHostResult> => {
|
||||
const server = byId.get(t.serverId);
|
||||
const base = { serverId: t.serverId, name: server?.name ?? `#${t.serverId}`, open: [] as number[], closed: [] as number[], filtered: 0 };
|
||||
if (!server) return { ...base, address: null, state: "error", message: "That server does not exist." };
|
||||
const given = t.address && t.address !== "" ? t.address : addressOf(server);
|
||||
if (!given) return { ...base, address: null, state: "skipped", message: "No address is known for it — give one." };
|
||||
let target: string;
|
||||
try {
|
||||
target = await resolveScanTarget(given);
|
||||
} catch (err) {
|
||||
return { ...base, address: given, state: "error", message: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
if (!beginScan(server.id)) return { ...base, address: target, state: "busy", message: "A scan of this server is already running." };
|
||||
let scan;
|
||||
try {
|
||||
scan = await scanPortList(target, ports);
|
||||
} catch (err) {
|
||||
return { ...base, address: target, state: "error", message: err instanceof Error ? err.message : String(err) };
|
||||
} finally {
|
||||
endScan(server.id);
|
||||
}
|
||||
if (!scanResponded(scan)) return { ...base, address: target, state: "no_answer", message: "Nothing answered — it may be down, or dropping everything.", filtered: scan.filtered };
|
||||
await recordPortScan(server.id, (p) => wanted.has(p), scan, new Date().toISOString());
|
||||
return { ...base, address: target, state: "scanned", message: null, open: scan.open, closed: scan.refused, filtered: scan.filtered };
|
||||
});
|
||||
|
||||
await recordAudit({
|
||||
actor: req.currentUser!,
|
||||
category: "server",
|
||||
action: "scan_port_preset",
|
||||
targetType: "port_preset",
|
||||
targetId: id,
|
||||
detail: { name: preset.name, servers: results.length, scanned: results.filter((r) => r.state === "scanned").length, open: results.reduce((n, r) => n + r.open.length, 0) },
|
||||
});
|
||||
res.json({ preset: { id: preset.id, name: preset.name }, ports, labels: Object.fromEntries(preset.ports.filter((p) => p.protocol === "tcp").map((p) => [p.port, p.label])), results });
|
||||
}));
|
||||
|
||||
// ─── Writing a preset's names onto many hosts ───────────────────────────────
|
||||
|
||||
const applySchema = z.object({
|
||||
serverIds: z.array(z.number().int().positive()).min(1).max(500),
|
||||
/** Only the ports that are open on the host (a scan found them, or its agent says they are listening) — the default. False notes every port of the preset on every host. */
|
||||
onlyOpen: z.boolean().default(true),
|
||||
/** Replace a label somebody wrote with the preset's. Never by default. */
|
||||
overwrite: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export interface PresetApplyResult {
|
||||
serverId: number;
|
||||
name: string;
|
||||
labelled: { port: number; protocol: "tcp" | "udp"; label: string }[];
|
||||
skipped: { port: number; protocol: "tcp" | "udp"; reason: "not_open" | "has_label" | "same" }[];
|
||||
}
|
||||
|
||||
portPresetsRouter.post("/:id/apply", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const parsed = applySchema.safeParse(req.body);
|
||||
if (!parsed.success) return invalid(res, parsed);
|
||||
const preset = await getPreset(id);
|
||||
if (!preset) return res.status(404).json({ error: "not_found" });
|
||||
const { onlyOpen, overwrite } = parsed.data;
|
||||
const ids = [...new Set(parsed.data.serverIds)];
|
||||
const rows = await db.select({ id: servers.id, name: servers.name, listeningPorts: servers.listeningPorts }).from(servers).where(inArray(servers.id, ids));
|
||||
const existing = await db.select().from(serverPorts).where(inArray(serverPorts.serverId, rows.map((r) => r.id)));
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const results: PresetApplyResult[] = [];
|
||||
for (const server of rows) {
|
||||
const mine = existing.filter((r) => r.serverId === server.id);
|
||||
const agent = groupAgentPorts(parseJson<AgentPort[] | null>(server.listeningPorts, null) ?? []);
|
||||
const labelled: PresetApplyResult["labelled"] = [];
|
||||
const skipped: PresetApplyResult["skipped"] = [];
|
||||
for (const p of preset.ports as PresetPort[]) {
|
||||
const row = mine.find((r) => r.port === p.port && r.protocol === p.protocol);
|
||||
const open = !!row?.open || agent.has(`${p.protocol}:${p.port}`);
|
||||
if (onlyOpen && !open) {
|
||||
skipped.push({ port: p.port, protocol: p.protocol, reason: "not_open" });
|
||||
continue;
|
||||
}
|
||||
if (row?.label === p.label) {
|
||||
skipped.push({ port: p.port, protocol: p.protocol, reason: "same" });
|
||||
continue;
|
||||
}
|
||||
if (row?.label && !overwrite) {
|
||||
skipped.push({ port: p.port, protocol: p.protocol, reason: "has_label" });
|
||||
continue;
|
||||
}
|
||||
if (row) await db.update(serverPorts).set({ label: p.label, updatedAt: now }).where(and(eq(serverPorts.id, row.id), eq(serverPorts.serverId, server.id)));
|
||||
else await db.insert(serverPorts).values({ serverId: server.id, port: p.port, protocol: p.protocol, label: p.label, updatedAt: now });
|
||||
labelled.push({ port: p.port, protocol: p.protocol, label: p.label });
|
||||
}
|
||||
results.push({ serverId: server.id, name: server.name, labelled, skipped });
|
||||
}
|
||||
|
||||
await recordAudit({
|
||||
actor: req.currentUser!,
|
||||
category: "server",
|
||||
action: "apply_port_preset",
|
||||
targetType: "port_preset",
|
||||
targetId: id,
|
||||
detail: { name: preset.name, servers: results.length, labelled: results.reduce((n, r) => n + r.labelled.length, 0), onlyOpen, overwrite },
|
||||
});
|
||||
res.json({ preset: { id: preset.id, name: preset.name }, results });
|
||||
}));
|
||||
@@ -6,6 +6,7 @@ import { servers, portForwards } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson, splitPortKey } from "../services/agentPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "../services/portPresets.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const portsRouter = Router();
|
||||
@@ -23,6 +24,8 @@ export interface AgentPortRow {
|
||||
addresses: string[];
|
||||
process: string | null;
|
||||
localOnly: boolean;
|
||||
/** What a port preset calls it ("RDP"), when one does. */
|
||||
service: string | null;
|
||||
lastSeenAt: string | null;
|
||||
}
|
||||
|
||||
@@ -31,6 +34,7 @@ portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
.select({ id: servers.id, name: servers.name, hostname: servers.hostname, listeningPorts: servers.listeningPorts, lastSeenAt: servers.lastSeenAt })
|
||||
.from(servers);
|
||||
|
||||
const names = serviceNames(await listPresets());
|
||||
const out: AgentPortRow[] = [];
|
||||
for (const s of rows) {
|
||||
const raw = parseJson<AgentPort[] | null>(s.listeningPorts, null);
|
||||
@@ -46,6 +50,7 @@ portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
addresses: grouped.addresses,
|
||||
process: grouped.process,
|
||||
localOnly: grouped.localOnly,
|
||||
service: serviceName(names, protocol, port),
|
||||
lastSeenAt: s.lastSeenAt,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Router } from "express";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { servers, serverPorts } from "../db/schema.js";
|
||||
@@ -7,6 +7,8 @@ import { requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { beginScan, endScan, MAX_SCAN_SPAN, resolveScanTarget, scanPorts, toRanges } from "../services/portScan.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson } from "../services/agentPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "../services/portPresets.js";
|
||||
import { recordPortScan } from "../services/portScanRecord.js";
|
||||
import { newListeningPorts, parseBaseline, portKey } from "../services/newPorts.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
@@ -32,6 +34,8 @@ export interface PortEntry {
|
||||
protocol: "tcp" | "udp";
|
||||
label: string | null;
|
||||
comment: string | null;
|
||||
/** What a port preset calls this port ("RDP"), when one does; shown where there is no label of its own. */
|
||||
service: string | null;
|
||||
/** The last scan from this app connected to it. */
|
||||
scanOpen: boolean;
|
||||
lastSeenOpenAt: string | null;
|
||||
@@ -55,6 +59,7 @@ async function buildPortList(serverId: number) {
|
||||
const alerting = (await getSettings()).healthChecks.newPortAlerts;
|
||||
const fresh = new Set(alerting ? newListeningPorts(agentRaw, parseBaseline(server.portBaseline), expected).map((p) => portKey(p.protocol, p.port)) : []);
|
||||
|
||||
const names = serviceNames(await listPresets());
|
||||
const entries = new Map<string, PortEntry>();
|
||||
for (const row of rows) {
|
||||
const key = `${row.protocol}:${row.port}`;
|
||||
@@ -64,6 +69,7 @@ async function buildPortList(serverId: number) {
|
||||
protocol: row.protocol,
|
||||
label: row.label,
|
||||
comment: row.comment,
|
||||
service: serviceName(names, row.protocol, row.port),
|
||||
scanOpen: row.open,
|
||||
lastSeenOpenAt: row.lastSeenOpenAt,
|
||||
agent: agent.get(key) ?? null,
|
||||
@@ -80,6 +86,7 @@ async function buildPortList(serverId: number) {
|
||||
protocol: protocol as "tcp" | "udp",
|
||||
label: null,
|
||||
comment: null,
|
||||
service: serviceName(names, protocol, Number(port)),
|
||||
scanOpen: false,
|
||||
lastSeenOpenAt: null,
|
||||
agent: info,
|
||||
@@ -160,32 +167,7 @@ serverPortsRouter.post("/scan", requireRole("operator"), asyncHandler(async (req
|
||||
// which ports are open, so leave what we knew before rather than marking it all closed.
|
||||
const responded = scan.open.length + scan.refused.length > 0;
|
||||
|
||||
if (responded) {
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(serverPorts)
|
||||
.where(and(eq(serverPorts.serverId, serverId), eq(serverPorts.protocol, "tcp")));
|
||||
const inRange = existing.filter((r) => r.port >= from && r.port <= to);
|
||||
const openSet = new Set(scan.open);
|
||||
const known = new Set(existing.map((r) => r.port));
|
||||
|
||||
const newlyFound = scan.open.filter((p) => !known.has(p));
|
||||
for (let i = 0; i < newlyFound.length; i += 50) {
|
||||
await db.insert(serverPorts).values(
|
||||
newlyFound.slice(i, i + 50).map((port) => ({ serverId, port, protocol: "tcp" as const, open: true, lastSeenOpenAt: now })),
|
||||
);
|
||||
}
|
||||
const stillOpen = inRange.filter((r) => openSet.has(r.port)).map((r) => r.id);
|
||||
if (stillOpen.length > 0) {
|
||||
await db.update(serverPorts).set({ open: true, lastSeenOpenAt: now }).where(inArray(serverPorts.id, stillOpen));
|
||||
}
|
||||
// No longer open: keep it if someone wrote a note about it (it's now "reserved"), otherwise it carries no information.
|
||||
const gone = inRange.filter((r) => r.open && !openSet.has(r.port));
|
||||
const keep = gone.filter((r) => r.label || r.comment).map((r) => r.id);
|
||||
const drop = gone.filter((r) => !(r.label || r.comment)).map((r) => r.id);
|
||||
if (keep.length > 0) await db.update(serverPorts).set({ open: false }).where(inArray(serverPorts.id, keep));
|
||||
if (drop.length > 0) await db.delete(serverPorts).where(inArray(serverPorts.id, drop));
|
||||
}
|
||||
if (responded) await recordPortScan(serverId, (port) => port >= from && port <= to, scan, now);
|
||||
|
||||
const summary: StoredScan = {
|
||||
at: now,
|
||||
|
||||
@@ -13,6 +13,7 @@ import { dependencyCover, HEALTH_STATE_FLAG } from "./dependencies.js";
|
||||
import { getFailingSources } from "./integrationHealthMonitor.js";
|
||||
import { hostHealthConditions, parseHostHealth, withoutIgnoredServices, type HostHealth } from "./hostHealth.js";
|
||||
import { newListeningPorts, newPortMessage, parseBaseline, portKey, type NewPort } from "./newPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "./portPresets.js";
|
||||
import { parseJson, type AgentPort } from "./agentPorts.js";
|
||||
import { diskLimit, parseThresholds, type ServerThresholds } from "./serverThresholds.js";
|
||||
import { computeRuleFindings, findingKey, listRules, type RuleFinding } from "./alertRules.js";
|
||||
@@ -488,6 +489,7 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
|
||||
const { healthChecks: checks } = await getSettings();
|
||||
// The ports somebody has said are expected (a label or a comment on the Ports page); a row that only records an open scan says nothing.
|
||||
const portNames = serviceNames(await listPresets());
|
||||
const expectedByServer = new Map<number, Set<string>>();
|
||||
if (checks.newPortAlerts) {
|
||||
for (const r of await db.select().from(serverPorts)) {
|
||||
@@ -504,7 +506,7 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
} catch {
|
||||
// a malformed report shouldn't stop every other server being checked
|
||||
}
|
||||
const newPorts = checks.newPortAlerts ? newListeningPorts(parseJson<AgentPort[] | null>(s.listeningPorts, null), parseBaseline(s.portBaseline), expectedByServer.get(s.id) ?? new Set()) : [];
|
||||
const newPorts = checks.newPortAlerts ? newListeningPorts(parseJson<AgentPort[] | null>(s.listeningPorts, null), parseBaseline(s.portBaseline), expectedByServer.get(s.id) ?? new Set()).map((p) => ({ ...p, service: serviceName(portNames, "tcp", p.port) })) : [];
|
||||
snapshot.servers.push({ id: s.id, name: s.name, lastSeenAt: s.lastSeenAt, disks, health: withoutIgnoredServices(parseHostHealth(s.hostHealth), parseThresholds(s.thresholds)?.ignoreServices), thresholds: parseThresholds(s.thresholds), newPorts });
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface NewPort {
|
||||
port: number;
|
||||
/** What is listening, as the agent says; null when it does not. */
|
||||
process: string | null;
|
||||
/** What a port preset calls the port ("RDP"), when one does. */
|
||||
service?: string | null;
|
||||
}
|
||||
|
||||
export const portKey = (protocol: string, port: number) => `${protocol}:${port}`;
|
||||
@@ -57,4 +59,4 @@ export function newListeningPorts(listening: AgentPort[] | null | undefined, bas
|
||||
}
|
||||
|
||||
export const newPortMessage = (serverName: string, p: NewPort) =>
|
||||
`${serverName}: a new port is listening — ${p.port}/tcp${p.process ? ` (${p.process})` : ""}. If it should be there, note it on the server's Ports card.`;
|
||||
`${serverName}: a new port is listening — ${p.port}/tcp${p.service ? ` ${p.service}` : ""}${p.process ? ` (${p.process})` : ""}. If it should be there, note it on the server's Ports card.`;
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Port presets: a named list of ports and what each is ("Remote access" = 22 SSH, 3389 RDP …), written once and used on every host — to put a name to a port wherever it shows (without a label
|
||||
* typed for each host), to scan several hosts for just those ports, and to write the names onto the ports that are open on many hosts in one go.
|
||||
*
|
||||
* A few ready-made presets are put there the first time they are asked for; they are ordinary presets (change them, delete them) and are not put back once the list has been touched — deleting them all
|
||||
* leaves none. Scanning is TCP only (as the Ports card's scan is), so a UDP entry in a preset is for naming only.
|
||||
*/
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { portPresets } from "../db/schema.js";
|
||||
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
||||
|
||||
export interface PresetPort {
|
||||
port: number;
|
||||
protocol: "tcp" | "udp";
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface PortPreset {
|
||||
id: number;
|
||||
name: string;
|
||||
ports: PresetPort[];
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export const MAX_PRESET_PORTS = 60;
|
||||
const SEEDED_FLAG = "portPresetsSeeded";
|
||||
|
||||
const tcp = (port: number, label: string): PresetPort => ({ port, protocol: "tcp", label });
|
||||
|
||||
/** What is there to begin with. */
|
||||
export const STARTER_PRESETS: { name: string; ports: PresetPort[] }[] = [
|
||||
{ name: "Remote access", ports: [tcp(22, "SSH"), tcp(3389, "RDP"), tcp(5900, "VNC"), tcp(5985, "WinRM (HTTP)"), tcp(5986, "WinRM (HTTPS)")] },
|
||||
{ name: "Databases", ports: [tcp(1433, "SQL Server"), tcp(1521, "Oracle"), tcp(3306, "MySQL / MariaDB"), tcp(5432, "PostgreSQL"), tcp(6379, "Redis"), tcp(11211, "Memcached"), tcp(27017, "MongoDB")] },
|
||||
{ name: "Web", ports: [tcp(80, "HTTP"), tcp(443, "HTTPS"), tcp(8080, "HTTP (alternate)"), tcp(8443, "HTTPS (alternate)")] },
|
||||
{ name: "File sharing", ports: [tcp(21, "FTP"), tcp(139, "NetBIOS"), tcp(445, "SMB"), tcp(873, "rsync"), tcp(2049, "NFS")] },
|
||||
{ name: "Homelab tools", ports: [tcp(3000, "Grafana"), tcp(5000, "Synology DSM"), tcp(5001, "Synology DSM (HTTPS)"), tcp(8006, "Proxmox VE"), tcp(8007, "Proxmox Backup Server"), tcp(9090, "Prometheus")] },
|
||||
];
|
||||
|
||||
function parsePorts(stored: string): PresetPort[] {
|
||||
try {
|
||||
const v = JSON.parse(stored);
|
||||
if (!Array.isArray(v)) return [];
|
||||
return v
|
||||
.filter((p): p is PresetPort => p !== null && typeof p === "object" && Number.isInteger(p.port) && (p.protocol === "tcp" || p.protocol === "udp") && typeof p.label === "string")
|
||||
.map((p) => ({ port: p.port, protocol: p.protocol, label: p.label }));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const rowToPreset = (r: typeof portPresets.$inferSelect): PortPreset => ({ id: r.id, name: r.name, ports: parsePorts(r.ports), updatedAt: r.updatedAt });
|
||||
|
||||
/** Puts the ready-made presets there, once: the first time, and only into an empty list. */
|
||||
async function ensureStarters(): Promise<void> {
|
||||
if ((await getInternalFlag(SEEDED_FLAG)) !== null) return;
|
||||
const existing = await db.select({ id: portPresets.id }).from(portPresets).limit(1);
|
||||
if (existing.length === 0) {
|
||||
const now = new Date().toISOString();
|
||||
for (const p of STARTER_PRESETS) await db.insert(portPresets).values({ name: p.name, ports: JSON.stringify(p.ports), createdAt: now, updatedAt: now });
|
||||
}
|
||||
await setInternalFlag(SEEDED_FLAG, new Date().toISOString());
|
||||
}
|
||||
|
||||
/** Every preset, by name. */
|
||||
export async function listPresets(): Promise<PortPreset[]> {
|
||||
await ensureStarters();
|
||||
return (await db.select().from(portPresets).orderBy(asc(portPresets.name))).map(rowToPreset);
|
||||
}
|
||||
|
||||
export async function getPreset(id: number): Promise<PortPreset | null> {
|
||||
await ensureStarters();
|
||||
const [row] = await db.select().from(portPresets).where(eq(portPresets.id, id)).limit(1);
|
||||
return row ? rowToPreset(row) : null;
|
||||
}
|
||||
|
||||
const keyOf = (protocol: string, port: number) => `${protocol}:${port}`;
|
||||
|
||||
/**
|
||||
* Pure: what each port is called, from every preset: "tcp:3389" → "RDP". A port in more than one preset is called what the first of them (by name) calls it, so a port is never
|
||||
* called two things at once.
|
||||
*/
|
||||
export function serviceNames(presets: PortPreset[]): Map<string, string> {
|
||||
const names = new Map<string, string>();
|
||||
for (const p of presets) for (const e of p.ports) if (!names.has(keyOf(e.protocol, e.port))) names.set(keyOf(e.protocol, e.port), e.label);
|
||||
return names;
|
||||
}
|
||||
|
||||
export const serviceName = (names: Map<string, string>, protocol: string, port: number): string | null => names.get(keyOf(protocol, port)) ?? null;
|
||||
|
||||
/** Pure: the TCP ports of a preset, in order — what a scan of it looks at. */
|
||||
export const scannablePorts = (preset: Pick<PortPreset, "ports">): number[] => [...new Set(preset.ports.filter((p) => p.protocol === "tcp").map((p) => p.port))].sort((a, b) => a - b);
|
||||
|
||||
/** Runs `run` for each item, at most `limit` at a time, and returns the answers in the order of the items. */
|
||||
export async function mapLimit<T, R>(items: T[], limit: number, run: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
async function worker() {
|
||||
while (next < items.length) {
|
||||
const i = next++;
|
||||
out[i] = await run(items[i]);
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return out;
|
||||
}
|
||||
@@ -61,6 +61,32 @@ export async function scanPorts(
|
||||
return { open, refused, filtered };
|
||||
}
|
||||
|
||||
/** TCP connect scan of a list of ports (a preset's), with a bounded number of connections in flight. The answers are as scanPorts gives them. */
|
||||
export async function scanPortList(host: string, ports: number[], options: { timeoutMs?: number; concurrency?: number } = {}): Promise<ScanResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 700;
|
||||
const concurrency = options.concurrency ?? 400;
|
||||
const list = [...new Set(ports)];
|
||||
const open: number[] = [];
|
||||
const refused: number[] = [];
|
||||
let filtered = 0;
|
||||
let next = 0;
|
||||
|
||||
async function worker() {
|
||||
while (next < list.length) {
|
||||
const port = list[next++];
|
||||
const result = await probe(host, port, timeoutMs);
|
||||
if (result === "open") open.push(port);
|
||||
else if (result === "refused") refused.push(port);
|
||||
else filtered++;
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: Math.min(concurrency, list.length) }, worker));
|
||||
open.sort((a, b) => a - b);
|
||||
refused.sort((a, b) => a - b);
|
||||
return { open, refused, filtered };
|
||||
}
|
||||
|
||||
function isPrivateIPv4(ip: string): boolean {
|
||||
const [a, b] = ip.split(".").map(Number);
|
||||
return (
|
||||
@@ -91,6 +117,7 @@ export function isPrivateAddress(ip: string): boolean {
|
||||
* describe the machine the app itself runs on.
|
||||
*/
|
||||
export async function resolveScanTarget(address: string): Promise<string> {
|
||||
if (resolverOverride) return resolverOverride(address);
|
||||
const trimmed = address.trim();
|
||||
if (!trimmed) throw new Error("No address to scan.");
|
||||
let ips: string[];
|
||||
@@ -115,6 +142,12 @@ export async function resolveScanTarget(address: string): Promise<string> {
|
||||
return ip;
|
||||
}
|
||||
|
||||
let resolverOverride: ((address: string) => Promise<string>) | null = null;
|
||||
/** For tests: what decides which address is scanned, instead of the rule that it must be a private one (a test listens on the loopback address). */
|
||||
export function setScanTargetResolverForTests(fn: ((address: string) => Promise<string>) | null): void {
|
||||
resolverOverride = fn;
|
||||
}
|
||||
|
||||
/** Collapses a sorted list of ports into inclusive [start, end] ranges. */
|
||||
export function toRanges(ports: number[]): [number, number][] {
|
||||
const ranges: [number, number][] = [];
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* What a scan changes in what is remembered about a server's ports: a port found open that was not known is written down, one that is still open is marked as seen, and one that is no longer open
|
||||
* is kept if somebody wrote a note about it (it is then "reserved") and dropped if not. Only the ports the scan looked at are touched, whether they are a range or a list. If nothing at all
|
||||
* answered the host is probably down or dropping everything, which says nothing of its ports, so what was known is left alone.
|
||||
*/
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { serverPorts } from "../db/schema.js";
|
||||
import type { ScanResult } from "./portScan.js";
|
||||
|
||||
/** Whether anything answered (open, or refusing): the only case in which a scan says anything. */
|
||||
export const scanResponded = (scan: ScanResult): boolean => scan.open.length + scan.refused.length > 0;
|
||||
|
||||
export async function recordPortScan(serverId: number, inScope: (port: number) => boolean, scan: ScanResult, now: string): Promise<void> {
|
||||
if (!scanResponded(scan)) return;
|
||||
const existing = await db.select().from(serverPorts).where(and(eq(serverPorts.serverId, serverId), eq(serverPorts.protocol, "tcp")));
|
||||
const inRange = existing.filter((r) => inScope(r.port));
|
||||
const openSet = new Set(scan.open);
|
||||
const known = new Set(existing.map((r) => r.port));
|
||||
|
||||
const newlyFound = scan.open.filter((p) => !known.has(p));
|
||||
for (let i = 0; i < newlyFound.length; i += 50) {
|
||||
await db.insert(serverPorts).values(newlyFound.slice(i, i + 50).map((port) => ({ serverId, port, protocol: "tcp" as const, open: true, lastSeenOpenAt: now })));
|
||||
}
|
||||
const stillOpen = inRange.filter((r) => openSet.has(r.port)).map((r) => r.id);
|
||||
if (stillOpen.length > 0) await db.update(serverPorts).set({ open: true, lastSeenOpenAt: now }).where(inArray(serverPorts.id, stillOpen));
|
||||
// No longer open: keep it if someone wrote a note about it (it's now "reserved"), otherwise it carries no information.
|
||||
const gone = inRange.filter((r) => r.open && !openSet.has(r.port));
|
||||
const keep = gone.filter((r) => r.label || r.comment).map((r) => r.id);
|
||||
const drop = gone.filter((r) => !(r.label || r.comment)).map((r) => r.id);
|
||||
if (keep.length > 0) await db.update(serverPorts).set({ open: false }).where(inArray(serverPorts.id, keep));
|
||||
if (drop.length > 0) await db.delete(serverPorts).where(inArray(serverPorts.id, drop));
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* A port preset written as text, one port to a line: the pure parser and formatter the preset editor on the Ports page uses, run here against the web's own source file.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { join } from "node:path";
|
||||
|
||||
const web = (file: string) => pathToFileURL(join(import.meta.dirname, "../../web/src/utils", file)).href;
|
||||
const { parsePortLines, formatPortLines, MAX_PRESET_PORTS } = (await import(web("portPresetText.ts"))) as typeof import("../../web/src/utils/portPresetText");
|
||||
|
||||
describe("parsePortLines", () => {
|
||||
test("reads a port and its name, TCP unless /udp is written", () => {
|
||||
const { ports, errors } = parsePortLines("22 SSH\n3389/tcp RDP\n53/udp DNS");
|
||||
assert.deepEqual(errors, []);
|
||||
assert.deepEqual(ports, [
|
||||
{ port: 22, protocol: "tcp", label: "SSH" },
|
||||
{ port: 3389, protocol: "tcp", label: "RDP" },
|
||||
{ port: 53, protocol: "udp", label: "DNS" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("accepts a separator after the port and keeps a name with spaces", () => {
|
||||
const { ports, errors } = parsePortLines("5432: PostgreSQL main\r\n6379 - Redis\n8006=Proxmox VE");
|
||||
assert.deepEqual(errors, []);
|
||||
assert.deepEqual(
|
||||
ports.map((p) => [p.port, p.label]),
|
||||
[[5432, "PostgreSQL main"], [6379, "Redis"], [8006, "Proxmox VE"]],
|
||||
);
|
||||
});
|
||||
|
||||
test("skips blank lines and comments", () => {
|
||||
const { ports, errors } = parsePortLines("# remote access\n\n 22 SSH \n \n");
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal(ports.length, 1);
|
||||
assert.equal(ports[0].label, "SSH");
|
||||
});
|
||||
|
||||
test("says what is wrong with a line, by number, and still returns the good ones", () => {
|
||||
const { ports, errors } = parsePortLines("22 SSH\nSSH 22\n70000 Nope\n80\n22 Again\n443/udp QUIC\n443/udp Twice");
|
||||
assert.deepEqual(ports.map((p) => `${p.port}/${p.protocol}`), ["22/tcp", "443/udp"]);
|
||||
assert.equal(errors.length, 5);
|
||||
assert.match(errors[0], /^Line 2:/);
|
||||
assert.match(errors[1], /^Line 3: 70000 is not a port/);
|
||||
assert.match(errors[2], /^Line 4: say what 80 is/);
|
||||
assert.match(errors[3], /^Line 5: 22\/tcp is in the list twice/);
|
||||
assert.match(errors[4], /^Line 7: 443\/udp is in the list twice/);
|
||||
});
|
||||
|
||||
test("the same number over TCP and UDP is two ports", () => {
|
||||
const { ports, errors } = parsePortLines("53 DNS\n53/udp DNS");
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal(ports.length, 2);
|
||||
});
|
||||
|
||||
test("refuses a name longer than 60 characters and more ports than a preset holds", () => {
|
||||
assert.match(parsePortLines(`22 ${"x".repeat(61)}`).errors[0], /longer than 60/);
|
||||
const many = Array.from({ length: MAX_PRESET_PORTS + 1 }, (_, i) => `${i + 1} p${i + 1}`).join("\n");
|
||||
assert.match(parsePortLines(many).errors.join(" "), /At most 60 ports/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatPortLines", () => {
|
||||
test("writes TCP without the protocol and UDP with it, and reads back the same", () => {
|
||||
const ports = [
|
||||
{ port: 22, protocol: "tcp" as const, label: "SSH" },
|
||||
{ port: 53, protocol: "udp" as const, label: "DNS" },
|
||||
];
|
||||
const text = formatPortLines(ports);
|
||||
assert.equal(text, "22 SSH\n53/udp DNS");
|
||||
assert.deepEqual(parsePortLines(text).ports, ports);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* Port presets: the ready-made ones (put there once), writing and changing them, naming ports from them, scanning several hosts for one (against real listening sockets), and writing their names
|
||||
* onto the ports that are open on many hosts.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as net from "node:net";
|
||||
import type { Server } from "node:http";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-portpresets-"));
|
||||
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, serverPorts, portPresets, auditLog } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const pp = await import("../src/services/portPresets.js");
|
||||
const scan = await import("../src/services/portScan.js");
|
||||
const { requireAuth } = await import("../src/auth/middleware.js");
|
||||
const { portPresetsRouter, addressOf } = await import("../src/routes/portPresets.js");
|
||||
const { serverPortsRouter } = await import("../src/routes/serverPorts.js");
|
||||
const { portsRouter } = await import("../src/routes/ports.js");
|
||||
const { newPortMessage, newListeningPorts } = await import("../src/services/newPorts.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
/** A listening TCP socket on the loopback address, on a port the system picks. */
|
||||
const listen = () =>
|
||||
new Promise<net.Server>((resolve) => {
|
||||
const s = net.createServer((c) => c.destroy());
|
||||
s.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
const portOf = (s: net.Server) => (s.address() as AddressInfo).port;
|
||||
/** A port nothing listens on. */
|
||||
async function freePort(): Promise<number> {
|
||||
const s = await listen();
|
||||
const p = portOf(s);
|
||||
await new Promise<void>((r) => s.close(() => r()));
|
||||
return p;
|
||||
}
|
||||
|
||||
describe("the pure parts", () => {
|
||||
test("a port is called what the first preset (by name) calls it", () => {
|
||||
const names = pp.serviceNames([
|
||||
{ id: 1, name: "A", ports: [{ port: 80, protocol: "tcp", label: "HTTP" }, { port: 53, protocol: "udp", label: "DNS" }], updatedAt: "" },
|
||||
{ id: 2, name: "B", ports: [{ port: 80, protocol: "tcp", label: "Web" }, { port: 443, protocol: "tcp", label: "HTTPS" }], updatedAt: "" },
|
||||
]);
|
||||
assert.equal(pp.serviceName(names, "tcp", 80), "HTTP");
|
||||
assert.equal(pp.serviceName(names, "tcp", 443), "HTTPS");
|
||||
assert.equal(pp.serviceName(names, "udp", 53), "DNS");
|
||||
assert.equal(pp.serviceName(names, "tcp", 53), null, "a UDP name is not a TCP name");
|
||||
});
|
||||
|
||||
test("a scan looks at a preset's TCP ports once each, in order", () => {
|
||||
assert.deepEqual(pp.scannablePorts({ ports: [{ port: 443, protocol: "tcp", label: "a" }, { port: 53, protocol: "udp", label: "b" }, { port: 22, protocol: "tcp", label: "c" }, { port: 443, protocol: "tcp", label: "d" }] }), [22, 443]);
|
||||
});
|
||||
|
||||
test("hosts are done a few at a time and the answers come back in the order of the hosts", async () => {
|
||||
let inFlight = 0;
|
||||
let most = 0;
|
||||
const out = await pp.mapLimit([5, 1, 4, 2, 3, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
most = Math.max(most, inFlight);
|
||||
await new Promise((r) => setTimeout(r, n * 5));
|
||||
inFlight--;
|
||||
return n * 10;
|
||||
});
|
||||
assert.deepEqual(out, [50, 10, 40, 20, 30, 60]);
|
||||
assert.ok(most <= 3 && most > 1);
|
||||
assert.deepEqual(await pp.mapLimit([], 3, async (n: number) => n), []);
|
||||
});
|
||||
|
||||
test("the address to scan is the first one the server is known by, else its name", () => {
|
||||
assert.equal(addressOf({ ipAddresses: JSON.stringify(["192.168.1.5", "10.0.0.2"]), hostname: "x.lan" }), "192.168.1.5");
|
||||
assert.equal(addressOf({ ipAddresses: JSON.stringify([]), hostname: "x.lan" }), "x.lan");
|
||||
assert.equal(addressOf({ ipAddresses: "not json", hostname: null }), null);
|
||||
assert.equal(addressOf({ ipAddresses: null, hostname: " " }), null);
|
||||
});
|
||||
|
||||
test("a new-port alert says what the port is called, then what is listening on it", () => {
|
||||
assert.equal(newPortMessage("nas", { protocol: "tcp", port: 3389, process: "xrdp", service: "RDP" }), "nas: a new port is listening — 3389/tcp RDP (xrdp). If it should be there, note it on the server's Ports card.");
|
||||
assert.equal(newPortMessage("nas", { protocol: "tcp", port: 8080, process: null }), "nas: a new port is listening — 8080/tcp. If it should be there, note it on the server's Ports card.");
|
||||
assert.equal(newListeningPorts([{ protocol: "tcp", port: 3389, address: "0.0.0.0", process: "xrdp" }], new Set(), new Set())[0].port, 3389);
|
||||
});
|
||||
|
||||
test("scanning a list: the open ports and the refused ones, each looked at once", async () => {
|
||||
const a = await listen();
|
||||
const closed = await freePort();
|
||||
const r = await scan.scanPortList("127.0.0.1", [portOf(a), closed, portOf(a)], { timeoutMs: 1000 });
|
||||
assert.deepEqual([r.open, r.refused, r.filtered], [[portOf(a)], [closed], 0]);
|
||||
a.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the routes", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
const ids: Record<string, number> = {};
|
||||
const open: net.Server[] = [];
|
||||
const call = (sub: string, method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", "x-sub": sub }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const json = async <T>(r: Response) => (await r.json()) as T;
|
||||
type Preset = { id: number; name: string; ports: { port: number; protocol: string; label: string }[] };
|
||||
|
||||
before(async () => {
|
||||
await db.insert(users).values([{ oidcSub: "viewer", name: "Vic", role: "viewer" }, { oidcSub: "operator", name: "Olle", role: "operator" }]);
|
||||
const mk = async (name: string, extra: Partial<typeof servers.$inferInsert> = {}) => (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, ...extra }).returning({ id: servers.id }))[0].id;
|
||||
ids.web = await mk("web", { ipAddresses: JSON.stringify(["127.0.0.1"]) });
|
||||
ids.db = await mk("db", { ipAddresses: JSON.stringify(["127.0.0.1"]) });
|
||||
ids.noaddr = await mk("noaddr");
|
||||
ids.agent = await mk("agent-host", { listeningPorts: JSON.stringify([{ protocol: "tcp", port: 22, address: "0.0.0.0", process: "sshd" }, { protocol: "tcp", port: 3389, address: "0.0.0.0", process: "xrdp" }, { protocol: "tcp", port: 9999, address: "0.0.0.0", process: "x" }]) });
|
||||
ids.agent2 = await mk("agent-host-2", { listeningPorts: JSON.stringify([{ protocol: "tcp", port: 22, address: "0.0.0.0", process: "sshd" }]) });
|
||||
scan.setScanTargetResolverForTests(async (address) => {
|
||||
if (address === "boom") throw new Error("\"boom\" isn't on a private network.");
|
||||
return "127.0.0.1";
|
||||
});
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/port-presets", portPresetsRouter);
|
||||
a.use("/api/servers", requireAuth); // as the servers router does before it hands over to the ports routes
|
||||
a.use("/api/servers/:id/ports", serverPortsRouter);
|
||||
a.use("/api/ports", portsRouter);
|
||||
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`;
|
||||
});
|
||||
after(() => {
|
||||
scan.setScanTargetResolverForTests(null);
|
||||
for (const s of open) s.close();
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("the ready-made presets are there the first time, for everyone", async () => {
|
||||
const list = (await json<{ presets: Preset[] }>(await call("viewer", "GET", "/port-presets"))).presets;
|
||||
assert.deepEqual(list.map((p) => p.name), ["Databases", "File sharing", "Homelab tools", "Remote access", "Web"]);
|
||||
const remote = list.find((p) => p.name === "Remote access")!;
|
||||
assert.deepEqual(remote.ports.map((p) => [p.port, p.label]), [[22, "SSH"], [3389, "RDP"], [5900, "VNC"], [5985, "WinRM (HTTP)"], [5986, "WinRM (HTTPS)"]]);
|
||||
assert.ok(list.find((p) => p.name === "Databases")!.ports.some((p) => p.port === 5432 && p.label === "PostgreSQL"));
|
||||
});
|
||||
|
||||
test("an operator writes, changes and removes one; a viewer cannot; the name is unique whatever its case; what is not a preset is refused", async () => {
|
||||
const mine = { name: "Media", ports: [{ port: 8096, protocol: "tcp", label: "Jellyfin" }, { port: 8989, label: "Sonarr" }] };
|
||||
assert.equal((await call("viewer", "POST", "/port-presets", mine)).status, 403);
|
||||
const made = await call("operator", "POST", "/port-presets", mine);
|
||||
assert.equal(made.status, 201);
|
||||
const preset = (await json<{ preset: Preset }>(made)).preset;
|
||||
assert.deepEqual(preset.ports.map((p) => [p.port, p.protocol]), [[8096, "tcp"], [8989, "tcp"]], "the protocol is TCP unless said");
|
||||
assert.equal((await call("operator", "POST", "/port-presets", { ...mine, name: "media" })).status, 409);
|
||||
const changed = await call("operator", "PUT", `/port-presets/${preset.id}`, { name: "Media servers", ports: [{ port: 32400, protocol: "tcp", label: "Plex" }] });
|
||||
assert.equal(changed.status, 200);
|
||||
assert.equal((await call("operator", "PUT", `/port-presets/${preset.id}`, { name: "Web", ports: [{ port: 1, label: "x" }] })).status, 409, "another preset has that name");
|
||||
assert.equal((await call("operator", "PUT", `/port-presets/${preset.id}`, { name: "Media servers", ports: [{ port: 32400, label: "Plex" }] })).status, 200, "its own name is fine");
|
||||
assert.equal((await call("viewer", "DELETE", `/port-presets/${preset.id}`)).status, 403);
|
||||
assert.equal((await call("operator", "DELETE", `/port-presets/${preset.id}`)).status, 204);
|
||||
assert.equal((await call("operator", "DELETE", `/port-presets/${preset.id}`)).status, 404);
|
||||
assert.equal((await call("operator", "PUT", "/port-presets/99999", mine)).status, 404);
|
||||
for (const bad of [
|
||||
{ name: "", ports: [{ port: 22, label: "x" }] },
|
||||
{ name: "x", ports: [] },
|
||||
{ name: "x", ports: [{ port: 0, label: "x" }] },
|
||||
{ name: "x", ports: [{ port: 70000, label: "x" }] },
|
||||
{ name: "x", ports: [{ port: 22, label: "" }] },
|
||||
{ name: "x", ports: [{ port: 22, label: "x" }, { port: 22, protocol: "tcp", label: "y" }] },
|
||||
{ name: "x", ports: [{ port: 22, protocol: "sctp", label: "x" }] },
|
||||
{ name: "x", ports: Array.from({ length: 61 }, (_, i) => ({ port: i + 1, label: "x" })) },
|
||||
]) assert.equal((await call("operator", "POST", "/port-presets", bad)).status, 400, JSON.stringify(bad).slice(0, 60));
|
||||
const entries = (await db.select().from(auditLog)).filter((e) => e.targetType === "port_preset").map((e) => e.action);
|
||||
assert.deepEqual(entries, ["create_port_preset", "update_port_preset", "update_port_preset", "delete_port_preset"]);
|
||||
});
|
||||
|
||||
test("a port is named from the presets — on a server's Ports card (a row, and a port only the agent knows) and in the list of what agents report — and a label of its own is left as it is", async () => {
|
||||
const card = await json<{ ports: { port: number; service: string | null; label: string | null }[] }>(await call("viewer", "GET", `/servers/${ids.agent}/ports`));
|
||||
assert.deepEqual(card.ports.map((p) => [p.port, p.service]), [[22, "SSH"], [3389, "RDP"], [9999, null]]);
|
||||
assert.equal((await call("operator", "PUT", `/servers/${ids.agent}/ports`, { port: 22, protocol: "tcp", label: "Admin SSH", comment: "" })).status, 200);
|
||||
const after = await json<{ ports: { port: number; service: string | null; label: string | null }[] }>(await call("viewer", "GET", `/servers/${ids.agent}/ports`));
|
||||
assert.deepEqual(after.ports.filter((p) => p.port === 22).map((p) => [p.label, p.service]), [["Admin SSH", "SSH"]]);
|
||||
const agent = await json<{ ports: { serverId: number; port: number; service: string | null }[] }>(await call("viewer", "GET", "/ports/agent"));
|
||||
assert.deepEqual(agent.ports.filter((p) => p.serverId === ids.agent).map((p) => [p.port, p.service]), [[22, "SSH"], [3389, "RDP"], [9999, null]]);
|
||||
await db.delete(serverPorts).where(eq(serverPorts.serverId, ids.agent));
|
||||
});
|
||||
|
||||
describe("scanning hosts for a preset", () => {
|
||||
let presetId = 0;
|
||||
let p1 = 0;
|
||||
let p2 = 0;
|
||||
let closed = 0;
|
||||
before(async () => {
|
||||
const a = await listen();
|
||||
const b = await listen();
|
||||
open.push(a, b);
|
||||
p1 = portOf(a);
|
||||
p2 = portOf(b);
|
||||
closed = await freePort();
|
||||
presetId = (await json<{ preset: Preset }>(await call("operator", "POST", "/port-presets", { name: "Mine", ports: [{ port: p1, label: "Alpha" }, { port: p2, label: "Beta" }, { port: closed, label: "Gamma" }, { port: 53, protocol: "udp", label: "DNS" }] }))).preset.id;
|
||||
});
|
||||
type Res = { preset: { name: string }; ports: number[]; labels: Record<string, string>; results: { serverId: number; name: string; address: string | null; state: string; message: string | null; open: number[]; closed: number[] }[] };
|
||||
|
||||
test("each host is asked for the preset's TCP ports: the open ones, the refused ones, and what could not be scanned — with the reason", async () => {
|
||||
const res = await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: [{ serverId: ids.web }, { serverId: ids.db, address: "10.0.0.9" }, { serverId: ids.noaddr }, { serverId: ids.web, address: "boom" }, { serverId: 99999 }] });
|
||||
assert.equal(res.status, 200);
|
||||
const body = await json<Res>(res);
|
||||
assert.deepEqual(body.ports, [p1, p2, closed].sort((x, y) => x - y));
|
||||
assert.equal(body.labels[p1], "Alpha");
|
||||
assert.equal(body.results.length, 4, "a server asked for twice is scanned once");
|
||||
const by = (id: number) => body.results.find((r) => r.serverId === id)!;
|
||||
assert.deepEqual([by(ids.web).state, by(ids.web).open, by(ids.web).closed], ["scanned", [p1, p2].sort((x, y) => x - y), [closed]], "the first of the two requests for web wins");
|
||||
assert.deepEqual([by(ids.db).state, by(ids.db).address, by(ids.db).open], ["scanned", "127.0.0.1", [p1, p2].sort((x, y) => x - y)]);
|
||||
assert.deepEqual([by(ids.noaddr).state, by(ids.noaddr).message], ["skipped", "No address is known for it — give one."]);
|
||||
assert.deepEqual([by(99999).state, by(99999).message], ["error", "That server does not exist."]);
|
||||
});
|
||||
|
||||
test("what was found is written down like any scan: the open ports are remembered, and only the preset's ports are touched", async () => {
|
||||
const rows = (await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.web))).filter((r) => r.open).map((r) => r.port).sort((a, b) => a - b);
|
||||
assert.deepEqual(rows, [p1, p2].sort((a, b) => a - b));
|
||||
await db.insert(serverPorts).values({ serverId: ids.web, port: 1, protocol: "tcp", label: "Noted", open: true, lastSeenOpenAt: new Date().toISOString() });
|
||||
await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: [{ serverId: ids.web }] });
|
||||
assert.equal((await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.web))).find((r) => r.port === 1)!.open, true, "port 1 is not in the preset, so the scan said nothing of it");
|
||||
});
|
||||
|
||||
test("a port that has stopped listening goes from the remembered ones when it carries no note, and stays reserved when it does", async () => {
|
||||
await db.update(serverPorts).set({ label: "Mine" }).where(eq(serverPorts.port, p2));
|
||||
const stop = open.splice(0, 2);
|
||||
for (const s of stop) await new Promise<void>((r) => s.close(() => r()));
|
||||
const body = await json<Res>(await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: [{ serverId: ids.web }] }));
|
||||
assert.deepEqual([body.results[0].state, body.results[0].open], ["scanned", []]);
|
||||
const left = (await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.web))).filter((r) => r.port === p1 || r.port === p2);
|
||||
assert.deepEqual(left.map((r) => [r.port, r.open, r.label]), [[p2, false, "Mine"]]);
|
||||
});
|
||||
|
||||
test("a preset with no TCP port cannot be scanned; an operator is needed; no targets, an unknown preset and a bad body are refused; it is in the audit log", async () => {
|
||||
const udpOnly = (await json<{ preset: Preset }>(await call("operator", "POST", "/port-presets", { name: "Udp", ports: [{ port: 53, protocol: "udp", label: "DNS" }] }))).preset;
|
||||
assert.equal(((await json<{ error: string }>(await call("operator", "POST", `/port-presets/${udpOnly.id}/scan`, { targets: [{ serverId: ids.web }] }))).error), "nothing_to_scan");
|
||||
assert.equal((await call("viewer", "POST", `/port-presets/${presetId}/scan`, { targets: [{ serverId: ids.web }] })).status, 403);
|
||||
assert.equal((await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: [] })).status, 400);
|
||||
assert.equal((await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: Array.from({ length: 101 }, (_, i) => ({ serverId: i + 1 })) })).status, 400);
|
||||
assert.equal((await call("operator", "POST", `/port-presets/99999/scan`, { targets: [{ serverId: ids.web }] })).status, 404);
|
||||
assert.ok((await db.select().from(auditLog)).some((e) => e.action === "scan_port_preset"));
|
||||
});
|
||||
|
||||
test("a host that is already being scanned is said to be busy, not scanned twice", async () => {
|
||||
assert.equal(scan.beginScan(ids.web), true);
|
||||
try {
|
||||
const body = await json<Res>(await call("operator", "POST", `/port-presets/${presetId}/scan`, { targets: [{ serverId: ids.web }] }));
|
||||
assert.deepEqual([body.results[0].state, body.results[0].message], ["busy", "A scan of this server is already running."]);
|
||||
} finally {
|
||||
scan.endScan(ids.web);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("writing a preset's names onto many hosts", () => {
|
||||
let remote = 0;
|
||||
type Applied = { results: { serverId: number; name: string; labelled: { port: number; label: string }[]; skipped: { port: number; reason: string }[] }[] };
|
||||
before(async () => {
|
||||
remote = (await json<{ presets: Preset[] }>(await call("viewer", "GET", "/port-presets"))).presets.find((p) => p.name === "Remote access")!.id;
|
||||
});
|
||||
|
||||
test("the open ports of each host get the preset's names; the ones that are not open are left; a label somebody wrote stays", async () => {
|
||||
await db.insert(serverPorts).values({ serverId: ids.agent2, port: 22, protocol: "tcp", label: "My own SSH note" });
|
||||
const body = await json<Applied>(await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [ids.agent, ids.agent2] }));
|
||||
const by = (id: number) => body.results.find((r) => r.serverId === id)!;
|
||||
assert.deepEqual(by(ids.agent).labelled.map((l) => [l.port, l.label]), [[22, "SSH"], [3389, "RDP"]]);
|
||||
assert.deepEqual(by(ids.agent).skipped.map((s) => [s.port, s.reason]), [[5900, "not_open"], [5985, "not_open"], [5986, "not_open"]]);
|
||||
assert.deepEqual(by(ids.agent2).labelled, []);
|
||||
assert.deepEqual(by(ids.agent2).skipped.find((s) => s.port === 22), { port: 22, protocol: "tcp", reason: "has_label" });
|
||||
const rows = await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.agent));
|
||||
assert.deepEqual(rows.map((r) => [r.port, r.label]).sort((a, b) => Number(a[0]) - Number(b[0])), [[22, "SSH"], [3389, "RDP"]]);
|
||||
assert.equal((await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.agent2)))[0].label, "My own SSH note");
|
||||
});
|
||||
|
||||
test("again, it is already so; with overwrite a label somebody wrote is replaced", async () => {
|
||||
const again = await json<Applied>(await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [ids.agent] }));
|
||||
assert.deepEqual(again.results[0].skipped.filter((s) => s.reason === "same").map((s) => s.port), [22, 3389]);
|
||||
assert.deepEqual(again.results[0].labelled, []);
|
||||
const over = await json<Applied>(await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [ids.agent2], overwrite: true }));
|
||||
assert.deepEqual(over.results[0].labelled.map((l) => [l.port, l.label]), [[22, "SSH"]]);
|
||||
});
|
||||
|
||||
test("not only the open ones: every port of the preset is noted on the host (reserved)", async () => {
|
||||
const all = await json<Applied>(await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [ids.noaddr], onlyOpen: false }));
|
||||
assert.deepEqual(all.results[0].labelled.map((l) => l.port), [22, 3389, 5900, 5985, 5986]);
|
||||
const rows = await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.noaddr));
|
||||
assert.ok(rows.every((r) => r.open === false && r.label), "noted, none of them open");
|
||||
});
|
||||
|
||||
test("a label counts as noting the port, so the new-port alert is quiet for it — as the card says", async () => {
|
||||
const listening = [{ protocol: "tcp" as const, port: 3389, address: "0.0.0.0", process: "xrdp" }];
|
||||
const expected = new Set((await db.select().from(serverPorts).where(eq(serverPorts.serverId, ids.agent))).filter((r) => r.label).map((r) => `${r.protocol}:${r.port}`));
|
||||
assert.deepEqual(newListeningPorts(listening, new Set(), expected), []);
|
||||
assert.equal(newListeningPorts(listening, new Set(), new Set()).length, 1);
|
||||
});
|
||||
|
||||
test("an operator is needed; nothing to apply to, an unknown preset and servers that do not exist are handled; it is in the audit log", async () => {
|
||||
assert.equal((await call("viewer", "POST", `/port-presets/${remote}/apply`, { serverIds: [ids.agent] })).status, 403);
|
||||
assert.equal((await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [] })).status, 400);
|
||||
assert.equal((await call("operator", "POST", "/port-presets/99999/apply", { serverIds: [ids.agent] })).status, 404);
|
||||
assert.deepEqual((await json<Applied>(await call("operator", "POST", `/port-presets/${remote}/apply`, { serverIds: [99998] }))).results, []);
|
||||
assert.ok((await db.select().from(auditLog)).some((e) => e.action === "apply_port_preset"));
|
||||
});
|
||||
|
||||
test("the ready-made presets are not put back once they have been deleted", async () => {
|
||||
for (const p of await db.select().from(portPresets)) await db.delete(portPresets).where(eq(portPresets.id, p.id));
|
||||
assert.deepEqual((await json<{ presets: Preset[] }>(await call("viewer", "GET", "/port-presets"))).presets, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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: {
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in new issue
Block a user