/** * 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((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 { const s = await listen(); const p = portOf(s); await new Promise((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 = {}; 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 (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 = {}) => (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((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", "Debian / Ubuntu", "File sharing", "Homelab tools", "Network services", "Remote access", "Tailscale", "Web", "Windows client", "Windows server"]); 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("the operating-system, network and Tailscale presets name what a Windows client, a Windows server and a Debian or Ubuntu machine have open, what the network runs, and Tailscale — and no port is called two things", async () => { const list = (await json<{ presets: Preset[] }>(await call("viewer", "GET", "/port-presets"))).presets; const has = (name: string, protocol: string, port: number, label: string) => list.find((p) => p.name === name)!.ports.some((p) => p.protocol === protocol && p.port === port && p.label === label); assert.ok(has("Windows client", "tcp", 445, "SMB") && has("Windows client", "tcp", 49664, "RPC (dynamic)") && has("Windows client", "udp", 5353, "mDNS")); assert.ok(has("Windows server", "tcp", 389, "LDAP") && has("Windows server", "tcp", 9389, "AD Web Services") && has("Windows server", "udp", 67, "DHCP server")); assert.ok(has("Debian / Ubuntu", "tcp", 22, "SSH") && has("Debian / Ubuntu", "udp", 41641, "Tailscale")); assert.ok(has("Network services", "udp", 161, "SNMP") && has("Network services", "udp", 51820, "WireGuard") && has("Network services", "tcp", 8291, "MikroTik Winbox")); assert.ok(has("Tailscale", "udp", 41641, "Tailscale") && has("Tailscale", "udp", 3478, "STUN") && has("Tailscale", "tcp", 8443, "HTTPS (alternate)")); for (const p of list) assert.ok(p.ports.length <= pp.MAX_PRESET_PORTS, p.name); // Whichever preset names a port first (by name) is the one heard, so every preset that names the same port must say the same thing. const said = new Map(); for (const p of list) for (const e of p.ports) { const key = `${e.protocol}:${e.port}`; assert.equal(said.get(key) ?? e.label, e.label, `${key} is called two things (${p.name})`); said.set(key, e.label); } }); 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; 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); 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((r) => s.close(() => r())); const body = await json(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(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(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(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(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(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(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, []); }); }); }); describe("the presets that came later, on a list that is already in use", () => { const names = async () => (await pp.listPresets()).map((p) => p.name).sort(); const forget = async (...which: string[]) => { const { settings } = await import("../src/db/schema.js"); for (const w of which) await db.delete(settings).where(eq(settings.key, `_internal:${w}`)); }; test("they are added once, beside what is there: a preset of the same name is left as it is, a deleted one is not put back, and an emptied list stays empty", async () => { // The list as an install from before them has it: two presets (one of them changed, and its name in another case) and a flag for the first five only. await db.delete(portPresets); const now = new Date().toISOString(); await db.insert(portPresets).values([ { name: "Remote access", ports: JSON.stringify([{ port: 22, protocol: "tcp", label: "SSH" }]), createdAt: now, updatedAt: now }, { name: "windows CLIENT", ports: JSON.stringify([{ port: 1, protocol: "tcp", label: "Mine" }]), createdAt: now, updatedAt: now }, ]); await forget("portPresetsOsSeeded", "portPresetsNetworkSeeded"); assert.deepEqual(await names(), ["Debian / Ubuntu", "Network services", "Remote access", "Tailscale", "Windows server", "windows CLIENT"], "the missing ones came, the one with the same name (any case) did not"); assert.deepEqual((await pp.listPresets()).find((p) => p.name === "windows CLIENT")!.ports.map((p) => p.label), ["Mine"]); for (const p of (await pp.listPresets()).filter((x) => x.name === "Debian / Ubuntu")) await db.delete(portPresets).where(eq(portPresets.id, p.id)); assert.deepEqual(await names(), ["Network services", "Remote access", "Tailscale", "Windows server", "windows CLIENT"], "deleted, and not put back"); await db.delete(portPresets); await forget("portPresetsOsSeeded", "portPresetsNetworkSeeded"); assert.deepEqual(await names(), [], "somebody emptied the list, so it stays empty"); assert.deepEqual(await names(), [], "and the next look is the same"); }); test("an install that already has the operating-system presets gets only the network ones, and not the ones it deleted", async () => { await db.delete(portPresets); const now = new Date().toISOString(); await db.insert(portPresets).values({ name: "Remote access", ports: JSON.stringify([{ port: 22, protocol: "tcp", label: "SSH" }]), createdAt: now, updatedAt: now }); await forget("portPresetsNetworkSeeded"); assert.deepEqual(await names(), ["Network services", "Remote access", "Tailscale"]); }); });