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

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

No files matched your search

+75
View File
@@ -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);
});
});
+324
View File
@@ -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, []);
});
});
});