import { Router } from "express"; import { isIP } from "node:net"; import { and, eq, inArray } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; import { ipamEntries, integrations, dnsRecordsCache, networkDevices } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { asyncHandler } from "../utils/asyncHandler.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createTailscaleAdapter } from "../integrations/tailscale/adapter.js"; import { createProxmoxAdapter } from "../integrations/proxmox/adapter.js"; import { createPhpIpamAdapter } from "../integrations/phpipam/adapter.js"; import { makeExclusion } from "../services/consistency.js"; import { getSettings } from "../services/settingsStore.js"; export const ipamRouter = Router(); ipamRouter.use(requireAuth); async function matchingDnsRecordsByIp(ips: string[]): Promise> { const byIp = new Map(); if (ips.length === 0) return byIp; const rows = await db .select({ ip: dnsRecordsCache.content, name: dnsRecordsCache.name }) .from(dnsRecordsCache) .where(inArray(dnsRecordsCache.content, ips)); for (const row of rows) { const list = byIp.get(row.ip) ?? []; list.push(row.name); byIp.set(row.ip, list); } return byIp; } ipamRouter.get("/", asyncHandler(async (_req, res) => { const rows = await db.select().from(ipamEntries).orderBy(ipamEntries.ipAddress); const byIp = await matchingDnsRecordsByIp(rows.map((r) => r.ipAddress)); // Same excluded-ranges setting the Consistency page manages — "not interesting" addresses (Docker's bridge // network repeating on every host, say) can be hidden here too, without duplicating that configuration. const { consistency } = await getSettings(); const excluded = makeExclusion(consistency.excludedRanges); res.json({ entries: rows.map((r) => ({ ...r, matchingDnsRecords: byIp.get(r.ipAddress) ?? [], excluded: excluded(r.ipAddress) })), excludedRanges: consistency.excludedRanges, }); })); const createInput = z.object({ ipAddress: z.string().refine((v) => isIP(v) !== 0, "Must be a valid IPv4 or IPv6 address"), label: z.string().max(200).optional(), vendor: z.string().max(200).optional(), location: z.string().max(200).optional(), notes: z.string().max(4000).optional(), }); const updateInput = createInput.omit({ ipAddress: true }).partial(); ipamRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => { const parsed = createInput.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } const [existing] = await db .select({ id: ipamEntries.id }) .from(ipamEntries) .where(eq(ipamEntries.ipAddress, parsed.data.ipAddress)) .limit(1); if (existing) { return res.status(409).json({ error: "duplicate_ip" }); } const [created] = await db.insert(ipamEntries).values(parsed.data).returning(); await recordAudit({ actor: req.currentUser!, category: "ipam", action: "create", targetType: "ipam_entry", targetId: created.id, detail: { ipAddress: created.ipAddress }, }); const byIp = await matchingDnsRecordsByIp([created.ipAddress]); res.status(201).json({ entry: { ...created, matchingDnsRecords: byIp.get(created.ipAddress) ?? [] } }); })); ipamRouter.patch("/:id", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const parsed = updateInput.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } const [existing] = await db.select().from(ipamEntries).where(eq(ipamEntries.id, id)).limit(1); if (!existing) { return res.status(404).json({ error: "not_found" }); } const [updated] = await db .update(ipamEntries) .set({ ...parsed.data, updatedAt: new Date().toISOString() }) .where(eq(ipamEntries.id, id)) .returning(); await recordAudit({ actor: req.currentUser!, category: "ipam", action: "update", targetType: "ipam_entry", targetId: id, detail: { ipAddress: updated.ipAddress }, }); const byIp = await matchingDnsRecordsByIp([updated.ipAddress]); res.json({ entry: { ...updated, matchingDnsRecords: byIp.get(updated.ipAddress) ?? [] } }); })); ipamRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const [existing] = await db.select().from(ipamEntries).where(eq(ipamEntries.id, id)).limit(1); if (!existing) { return res.status(404).json({ error: "not_found" }); } await db.delete(ipamEntries).where(eq(ipamEntries.id, id)); await recordAudit({ actor: req.currentUser!, category: "ipam", action: "delete", targetType: "ipam_entry", targetId: id, detail: { ipAddress: existing.ipAddress }, }); res.status(204).end(); })); /** * Inserts a new IPAM entry for `ip`, or updates one this same sync source * previously created — but never touches an entry that already exists from * a manual entry or a different sync source, so two syncs (or a sync and a * human) can never clobber each other. */ async function upsertSyncedEntry( ip: string, label: string, vendor: string, notes: string | null, location: string | null, source: string, ): Promise<"added" | "updated" | "skipped"> { const [existing] = await db.select().from(ipamEntries).where(eq(ipamEntries.ipAddress, ip)).limit(1); if (!existing) { await db.insert(ipamEntries).values({ ipAddress: ip, label, vendor, notes, location, source }); return "added"; } if (existing.source === source) { await db .update(ipamEntries) .set({ label, notes, location, updatedAt: new Date().toISOString() }) .where(eq(ipamEntries.id, existing.id)); return "updated"; } return "skipped"; } ipamRouter.post("/sync-tailscale", requireRole("operator"), asyncHandler(async (req, res) => { const tailscaleIntegrations = await db .select() .from(integrations) .where(and(eq(integrations.type, "tailscale"), eq(integrations.enabled, true))); if (tailscaleIntegrations.length === 0) { return res.status(400).json({ error: "no_tailscale_integration" }); } let added = 0; let updated = 0; let skipped = 0; const skippedIps: string[] = []; const errors: string[] = []; for (const integration of tailscaleIntegrations) { const loaded = await loadIntegrationConfig(integration.id); if (!loaded || loaded.integration.type !== "tailscale") continue; let devices; try { const adapter = createTailscaleAdapter(loaded.config as { tailnet: string; apiKey: string }); devices = await adapter.listDevices(); } catch (err) { errors.push(`${integration.name}: ${err instanceof Error ? err.message : String(err)}`); continue; } for (const device of devices) { const ip = device.primaryAddress; if (!ip) continue; const label = device.label || device.hostname || ip; const notes = device.os ? `OS: ${device.os}` : null; const result = await upsertSyncedEntry(ip, label, "Tailscale", notes, null, "tailscale"); if (result === "added") added++; else if (result === "updated") updated++; else { skipped++; skippedIps.push(ip); } } } await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_tailscale", detail: { added, updated, skipped }, }); res.json({ added, updated, skipped, skippedIps, errors }); })); ipamRouter.post("/sync-proxmox", requireRole("operator"), asyncHandler(async (req, res) => { const proxmoxIntegrations = await db .select() .from(integrations) .where(and(eq(integrations.type, "proxmox"), eq(integrations.enabled, true))); if (proxmoxIntegrations.length === 0) { return res.status(400).json({ error: "no_proxmox_integration" }); } let added = 0; let updated = 0; let skipped = 0; const skippedIps: string[] = []; const errors: string[] = []; for (const integration of proxmoxIntegrations) { const loaded = await loadIntegrationConfig(integration.id); if (!loaded || loaded.integration.type !== "proxmox") continue; const adapter = createProxmoxAdapter( loaded.config as { url: string; tokenId: string; tokenSecret: string; insecure?: boolean }, ); let guests; try { guests = await adapter.listGuests(); } catch (err) { errors.push(`${integration.name}: ${err instanceof Error ? err.message : String(err)}`); continue; } for (const guest of guests) { let detail; try { detail = await adapter.getGuestDetail(guest.node, guest.type, guest.vmid); } catch (err) { errors.push(`${integration.name}/${guest.name}: ${err instanceof Error ? err.message : String(err)}`); continue; } const label = guest.name || `${guest.type}/${guest.vmid}`; const notes = `Proxmox ${guest.type === "qemu" ? "VM" : "LXC"} #${guest.vmid} on ${guest.node}`; for (const ip of detail.ipAddresses) { const result = await upsertSyncedEntry(ip, label, "Proxmox", notes, null, "proxmox"); if (result === "added") added++; else if (result === "updated") updated++; else { skipped++; skippedIps.push(ip); } } } } await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_proxmox", detail: { added, updated, skipped }, }); res.json({ added, updated, skipped, skippedIps, errors }); })); ipamRouter.post("/sync-unifi", requireRole("operator"), asyncHandler(async (req, res) => { const controllers = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "unifi"), eq(integrations.enabled, true))); if (controllers.length === 0) { return res.status(400).json({ error: "no_unifi_integration" }); } let added = 0; let updated = 0; let skipped = 0; const skippedIps: string[] = []; // What was last read from the controllers (the page's own copy), not a new call: a device is as current as the Network devices page says. for (const d of await db.select().from(networkDevices)) { if (!d.ip) continue; const kind = d.kind.replace("_", " "); const notes = [`${kind}${d.model ? `, ${d.model}` : ""}`, d.mac ? `MAC ${d.mac}` : null].filter((v): v is string => !!v).join(" — "); const result = await upsertSyncedEntry(d.ip, d.name, "UniFi", notes, d.siteName && d.siteName !== "Default" ? d.siteName : null, "unifi"); if (result === "added") added++; else if (result === "updated") updated++; else { skipped++; skippedIps.push(d.ip); } } await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_unifi", detail: { added, updated, skipped } }); res.json({ added, updated, skipped, skippedIps, errors: [] }); })); ipamRouter.post("/sync-phpipam", requireRole("operator"), asyncHandler(async (req, res) => { const phpIpamIntegrations = await db .select() .from(integrations) .where(and(eq(integrations.type, "phpipam"), eq(integrations.enabled, true))); if (phpIpamIntegrations.length === 0) { return res.status(400).json({ error: "no_phpipam_integration" }); } let added = 0; let updated = 0; let skipped = 0; const skippedIps: string[] = []; const errors: string[] = []; for (const integration of phpIpamIntegrations) { const loaded = await loadIntegrationConfig(integration.id); if (!loaded || loaded.integration.type !== "phpipam") continue; let addresses; try { const adapter = createPhpIpamAdapter(loaded.config as { url: string; appId: string; token: string; insecure?: boolean }); addresses = await adapter.listAddresses(); } catch (err) { errors.push(`${integration.name}: ${err instanceof Error ? err.message : String(err)}`); continue; } for (const addr of addresses) { const label = addr.hostname || addr.description || addr.ip; const notes = [addr.description, addr.note, addr.mac ? `MAC ${addr.mac}` : null].filter((v): v is string => !!v).join(" — ") || null; const result = await upsertSyncedEntry(addr.ip, label, "phpIPAM", notes, addr.subnetLabel, "phpipam"); if (result === "added") added++; else if (result === "updated") updated++; else { skipped++; skippedIps.push(addr.ip); } } } await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_phpipam", detail: { added, updated, skipped }, }); res.json({ added, updated, skipped, skippedIps, errors }); }));