Files
Homelab-manager/server/src/services/portPresets.ts
T
bobbanandClaude Sonnet 5.5 b8ce337dfb Port presets: Network services and Tailscale
Two more ready-made presets, added once to installs that already have presets.
Later batches now each have their own flag (LATER_BATCHES), so the next one is
a list entry rather than new seeding code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:47:28 +01:00

179 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 });
const udp = (port: number, label: string): PresetPort => ({ port, protocol: "udp", label });
/** A run of ports with one name: the dynamic RPC ports Windows listens on, 49664–49670. */
const run = (from: number, to: number, label: string): PresetPort[] => Array.from({ length: to - from + 1 }, (_, i) => tcp(from + i, 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")] },
];
/**
* What a machine has open out of the box, by operating system. These came later than the five above, so they are put there once more (see ensureStarters), into a list that is already in use.
* A port that other presets name too is called the same thing here, so it is never called two names; the ones named only here are what is new.
*/
export const OS_PRESETS: { name: string; ports: PresetPort[] }[] = [
{
name: "Windows client",
ports: [
tcp(135, "RPC endpoint mapper"), tcp(139, "NetBIOS"), tcp(445, "SMB"), tcp(2869, "UPnP device host"), tcp(3389, "RDP"), tcp(5040, "Device association (CDPSvc)"), tcp(5357, "Web Services for Devices"),
tcp(5985, "WinRM (HTTP)"), tcp(5986, "WinRM (HTTPS)"), tcp(7680, "Delivery Optimization"), ...run(49664, 49670, "RPC (dynamic)"),
udp(137, "NetBIOS name"), udp(138, "NetBIOS datagram"), udp(1900, "SSDP (UPnP discovery)"), udp(3702, "WS-Discovery"), udp(5353, "mDNS"), udp(5355, "LLMNR"),
],
},
{
name: "Windows server",
ports: [
tcp(53, "DNS"), tcp(80, "HTTP"), tcp(88, "Kerberos"), tcp(135, "RPC endpoint mapper"), tcp(139, "NetBIOS"), tcp(389, "LDAP"), tcp(443, "HTTPS"), tcp(445, "SMB"), tcp(464, "Kerberos password change"),
tcp(593, "RPC over HTTP"), tcp(636, "LDAPS"), tcp(1688, "KMS activation"), tcp(2179, "Hyper-V VM console"), tcp(3268, "Global Catalog"), tcp(3269, "Global Catalog (SSL)"), tcp(3389, "RDP"),
tcp(5722, "DFS Replication"), tcp(5985, "WinRM (HTTP)"), tcp(5986, "WinRM (HTTPS)"), tcp(8530, "WSUS"), tcp(8531, "WSUS (HTTPS)"), tcp(9389, "AD Web Services"), tcp(47001, "WinRM (HTTP.sys)"),
...run(49664, 49670, "RPC (dynamic)"),
udp(53, "DNS"), udp(67, "DHCP server"), udp(88, "Kerberos"), udp(123, "NTP"), udp(137, "NetBIOS name"), udp(138, "NetBIOS datagram"), udp(389, "LDAP"), udp(464, "Kerberos password change"), udp(5355, "LLMNR"),
],
},
{
name: "Debian / Ubuntu",
ports: [
tcp(22, "SSH"), tcp(25, "SMTP"), tcp(53, "DNS"), tcp(111, "rpcbind"), tcp(631, "CUPS (printing)"), tcp(5355, "LLMNR"),
udp(53, "DNS"), udp(68, "DHCP client"), udp(111, "rpcbind"), udp(123, "NTP"), udp(161, "SNMP"), udp(323, "NTP (chrony)"), udp(5353, "mDNS"), udp(5355, "LLMNR"), udp(41641, "Tailscale"),
],
},
];
/**
* The network's own services, and Tailscale. Tailscale makes few ports of its own that a scan can find — it talks out, and on a port picked at run time — so what is named here is the direct
* WireGuard port an agent reports and the ports Serve and Funnel answer on. 8443 keeps the name the Web preset gives it: a name given here would be given to it on every host.
*/
export const NETWORK_PRESETS: { name: string; ports: PresetPort[] }[] = [
{
name: "Network services",
ports: [
tcp(22, "SSH"), tcp(23, "Telnet"), tcp(53, "DNS"), tcp(179, "BGP"), tcp(853, "DNS over TLS"), tcp(1723, "PPTP"), tcp(5201, "iperf3"), tcp(8291, "MikroTik Winbox"), tcp(8728, "MikroTik API"), tcp(8729, "MikroTik API (SSL)"),
udp(53, "DNS"), udp(67, "DHCP server"), udp(68, "DHCP client"), udp(69, "TFTP"), udp(123, "NTP"), udp(161, "SNMP"), udp(162, "SNMP trap"), udp(500, "IPsec (IKE)"), udp(514, "Syslog"), udp(520, "RIP"),
udp(546, "DHCPv6 client"), udp(547, "DHCPv6 server"), udp(1194, "OpenVPN"), udp(1701, "L2TP"), udp(1812, "RADIUS"), udp(1813, "RADIUS accounting"), udp(1900, "SSDP (UPnP discovery)"), udp(3478, "STUN"),
udp(4500, "IPsec (NAT traversal)"), udp(5201, "iperf3"), udp(5353, "mDNS"), udp(51820, "WireGuard"),
],
},
{ name: "Tailscale", ports: [tcp(22, "SSH"), tcp(443, "HTTPS"), tcp(8443, "HTTPS (alternate)"), udp(3478, "STUN"), udp(41641, "Tailscale")] },
];
/** The presets that came after the first five, each batch with the flag that says it has been put there. */
const LATER_BATCHES: { flag: string; presets: { name: string; ports: PresetPort[] }[] }[] = [
{ flag: "portPresetsOsSeeded", presets: OS_PRESETS },
{ flag: "portPresetsNetworkSeeded", presets: NETWORK_PRESETS },
];
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. The ones that came later (LATER_BATCHES) are put there once as well, and in a list that is already
* in use only those whose name is not taken (whatever its case) — an empty list stays empty, since somebody cleared it — so a preset deleted afterwards is not put back.
*/
async function ensureStarters(): Promise<void> {
const first = (await getInternalFlag(SEEDED_FLAG)) === null;
const due = [];
for (const b of LATER_BATCHES) if ((await getInternalFlag(b.flag)) === null) due.push(b);
if (!first && due.length === 0) return;
const now = new Date().toISOString();
const add = (p: { name: string; ports: PresetPort[] }) => db.insert(portPresets).values({ name: p.name, ports: JSON.stringify(p.ports), createdAt: now, updatedAt: now });
const existing = await db.select({ name: portPresets.name }).from(portPresets);
if (first) {
if (existing.length === 0) for (const p of [...STARTER_PRESETS, ...LATER_BATCHES.flatMap((b) => b.presets)]) await add(p);
await setInternalFlag(SEEDED_FLAG, now);
for (const b of LATER_BATCHES) await setInternalFlag(b.flag, now);
return;
}
const taken = new Set(existing.map((e) => e.name.toLowerCase()));
for (const b of due) {
if (existing.length > 0) for (const p of b.presets) if (!taken.has(p.name.toLowerCase())) await add(p);
await setInternalFlag(b.flag, now);
}
}
/** 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;
}