/** * Which things in this app an Uptime Kuma monitor is about — a server, an integration (a Proxmox host, a NAS…) or a DNS provider. * * A server matches the way the Uptime Kuma page already matches it: the monitor's host is one of the server's IP addresses, its * hostname, or its short name. An integration or DNS provider matches when the monitor's host is the host in its own address * (the URL entered when it was added) — as the same name or the same IP, exactly. Nothing is inferred through DNS: a website that * merely resolves to the same address as a proxy is not "the proxy", and guessing here would silence alerts that should fire. */ import * as net from "node:net"; import type { MaintenanceTargetType } from "../db/schema.js"; import { matchServerForTarget, type MatchableServer } from "./uptimeKumaMatch.js"; export interface WindowTarget { type: MaintenanceTargetType; id: number; name: string; } export interface AddressedTarget extends WindowTarget { /** The host from the address it was added with, e.g. "pve.example.lan" or "10.0.0.5". */ host: string; } const clean = (s: string) => s.trim().toLowerCase().replace(/\.$/, ""); /** The host part of an address as typed ("https://pve.example.lan:8006/", "10.0.0.5:8006", "pve.example.lan"), or null. */ export function hostOfAddress(address: string | null | undefined): string | null { if (!address || !address.trim()) return null; const text = address.trim(); try { const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`); const host = url.hostname.replace(/^\[|\]$/g, ""); return host ? clean(host) : null; } catch { return null; } } /** Everything in the app that `host` (a monitor's target) is the address of. */ export function targetsForHost(host: string | null, servers: MatchableServer[], addressed: AddressedTarget[]): WindowTarget[] { if (!host || !host.trim()) return []; const found: WindowTarget[] = []; const server = matchServerForTarget(host, servers); if (server) found.push({ type: "server", id: server.id, name: server.name }); const wanted = clean(host); for (const t of addressed) { // An IP is compared as an IP, so "::1" and "0:0:0:0:0:0:0:1" are the same thing; a name is compared as a name. const same = net.isIP(wanted) !== 0 && net.isIP(t.host) !== 0 ? sameIp(wanted, t.host) : t.host === wanted; if (same) found.push({ type: t.type, id: t.id, name: t.name }); } return found; } function sameIp(a: string, b: string): boolean { if (a === b) return true; if (net.isIPv6(a) && net.isIPv6(b)) { const list = new net.BlockList(); list.addAddress(a, "ipv6"); return list.check(b, "ipv6"); } return false; }