/** * UniFi (Network application) adapter. * Requires config: url, and either apiKey, or username + password; optional: site, selfHosted, insecure. * * Two ways in, because controllers differ: * * - **API key** (UniFi Network 9 and later; the key is made under Settings → Control Plane → Integrations and sent as `X-API-KEY`). This uses the * official Integration API, `/proxy/network/integration/v1/…` on a UniFi OS console (UDM, UCG, Cloud Key Gen2+) or `:8443/integration/v1/…` * on a self-hosted Network application. Sites, devices (state, IP, firmware), each device's uplink and uptime, networks and Wi-Fi broadcasts. The prefix is * found by asking: a 404 on the first form tries the second, and a 401/403 means the key is not accepted. * - **Login** (any version, including ones from before API keys): a local account's username and password, with the classic endpoints * `/proxy/network/api/s//…` (UniFi OS) or `:8443/api/s//…` (self-hosted). A read-only local account is enough; a Ubiquiti * cloud (SSO) account with two-factor is not. * * It only ever reads. Wi-Fi passphrases are in the controller's answers on the login path; they are never copied out of this file's normalising functions, which * list the fields they keep. * * The endpoints and field names are from Ubiquiti's published Integration API and the long-documented classic API, but have not been checked against a live * controller here. Every field is read defensively (a missing or renamed one leaves that value blank rather than breaking the sync), and a device whose own detail * cannot be read is still listed. If your controller answers differently, the Diagnostic Log has what it said. */ import * as http from "node:http"; import * as https from "node:https"; import { withDiagLogging } from "../../services/diagLog.js"; export interface UnifiConfig { url: string; apiKey?: string; username?: string; password?: string; /** Only this site (its name as shown in the controller); blank reads them all. */ site?: string; /** A self-hosted Network application rather than a UniFi OS console (no /proxy/network in front of the paths). */ selfHosted?: boolean; insecure?: boolean; } export type UnifiDeviceKind = "gateway" | "switch" | "access_point" | "other"; export type UnifiDeviceState = "online" | "offline" | "updating" | "pending" | "other"; export interface UnifiDevice { /** The MAC address, lower case, with colons. */ externalId: string; mac: string; name: string; model: string | null; kind: UnifiDeviceKind; ip: string | null; state: UnifiDeviceState; uptimeSeconds: number | null; firmware: string | null; firmwareUpdatable: boolean; /** The MAC of the device this one is connected through. */ uplinkExternalId: string | null; siteName: string; } export interface UnifiNetwork { externalId: string; name: string; enabled: boolean; vlanId: number | null; subnet: string | null; purpose: string | null; siteName: string; } export interface UnifiSsid { externalId: string; name: string; enabled: boolean; security: string | null; networkName: string | null; vlanId: number | null; siteName: string; } export interface UnifiInventory { mode: "api_key" | "login"; sites: string[]; devices: UnifiDevice[]; networks: UnifiNetwork[]; ssids: UnifiSsid[]; } export interface UnifiAdapter { ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>; fetchInventory(): Promise; } // ─── Normalising (pure, exported for tests) ───────────────────────────────── const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null); const num = (v: unknown): number | null => { const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN; return Number.isFinite(n) ? n : null; }; const obj = (v: unknown): Record => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}); const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); /** "AA-BB-CC-DD-EE-FF" / "aabbccddeeff" / "AA:BB:…" → "aa:bb:cc:dd:ee:ff"; null if it isn't a MAC address. */ export function normaliseMac(value: unknown): string | null { const hex = (str(value) ?? "").replace(/[^0-9a-fA-F]/g, "").toLowerCase(); return hex.length === 12 ? hex.match(/../g)!.join(":") : null; } const GATEWAY_MODEL = /^(udm|udr|uxg|ucg|usg|udw|dream\s*(machine|router)|cloud\s*gateway|gateway)/i; export function deviceKind(model: string | null, features: string[], legacyType: string | null): UnifiDeviceKind { const type = (legacyType ?? "").toLowerCase(); if (type === "ugw" || type === "udm" || type === "uxg" || type === "ucg" || (model && GATEWAY_MODEL.test(model))) return "gateway"; if (type === "uap" || features.includes("accessPoint")) return "access_point"; if (type === "usw" || features.includes("switching")) return "switch"; if (model && /^(uap|u6|u7|ap\b)/i.test(model)) return "access_point"; if (model && /^(usw|us-|flex|ultra)/i.test(model)) return "switch"; return "other"; } /** The Integration API's device states. Only "offline" is a problem worth an alert; a device being adopted or updating is not. */ export function stateFromApi(state: unknown): UnifiDeviceState { switch (String(state ?? "").toUpperCase()) { case "ONLINE": return "online"; case "OFFLINE": case "CONNECTION_INTERRUPTED": case "ISOLATED": return "offline"; case "UPDATING": return "updating"; case "PENDING_ADOPTION": case "ADOPTING": case "GETTING_READY": return "pending"; default: return "other"; } } /** The classic API's numeric states (1 connected, 0 disconnected, 4 upgrading, 5 provisioning, 6 heartbeat missed, 7 adopting, 11 isolated). */ export function stateFromLegacy(state: unknown): UnifiDeviceState { switch (num(state)) { case 1: return "online"; case 0: case 6: case 11: return "offline"; case 4: return "updating"; case 5: case 7: return "pending"; default: return "other"; } } /** One device from the Integration API: its list entry, its detail (for the uplink), and its latest statistics (for the uptime) — the last two may be missing. */ export function deviceFromApi(entry: unknown, detail: unknown, stats: unknown, siteName: string, macById: Map): UnifiDevice | null { const e = obj(entry); const d = { ...e, ...obj(detail) }; const mac = normaliseMac(d.macAddress); if (!mac) return null; const model = str(d.model); const uplinkId = str(obj(d.uplink).deviceId); return { externalId: mac, mac, name: str(d.name) ?? model ?? mac, model, kind: deviceKind(model, list(d.features).filter((f): f is string => typeof f === "string"), null), ip: str(d.ipAddress), state: stateFromApi(d.state), uptimeSeconds: num(obj(stats).uptimeSec), firmware: str(d.firmwareVersion), firmwareUpdatable: d.firmwareUpdatable === true, uplinkExternalId: uplinkId ? (macById.get(uplinkId) ?? null) : null, siteName, }; } export function deviceFromLegacy(raw: unknown, siteName: string): UnifiDevice | null { const d = obj(raw); const mac = normaliseMac(d.mac); if (!mac) return null; const model = str(d.model) ?? str(d.shortname); const up = obj(d.uplink); return { externalId: mac, mac, name: str(d.name) ?? model ?? mac, model, kind: deviceKind(model, [], str(d.type)), ip: str(d.ip), state: stateFromLegacy(d.state), uptimeSeconds: num(d.uptime), firmware: str(d.version), firmwareUpdatable: d.upgradable === true, uplinkExternalId: normaliseMac(up.uplink_mac) ?? normaliseMac(d.uplink_mac), siteName, }; } export function networkFromApi(entry: unknown, detail: unknown, siteName: string): UnifiNetwork | null { const d = { ...obj(entry), ...obj(detail) }; const id = str(d.id); const name = str(d.name); if (!id || !name) return null; const v4 = obj(d.ipv4Configuration); const host = str(v4.hostIpAddress); const prefix = num(v4.prefixLength); return { externalId: id, name, enabled: d.enabled !== false, vlanId: num(d.vlanId), subnet: host && prefix !== null ? `${host}/${prefix}` : null, purpose: str(d.management)?.toLowerCase() ?? null, siteName, }; } export function networkFromLegacy(raw: unknown, siteName: string): UnifiNetwork | null { const d = obj(raw); const id = str(d._id); const name = str(d.name); if (!id || !name) return null; return { externalId: id, name, enabled: d.enabled !== false, vlanId: d.vlan_enabled === false ? null : num(d.vlan), subnet: str(d.ip_subnet), purpose: str(d.purpose), siteName, }; } const API_SECURITY: Record = { OPEN: "Open", WPA2_PERSONAL: "WPA2", WPA3_PERSONAL: "WPA3", WPA2_WPA3_PERSONAL: "WPA2/WPA3", WPA2_ENTERPRISE: "WPA2 Enterprise", WPA3_ENTERPRISE: "WPA3 Enterprise" }; export function ssidFromApi(raw: unknown, networkNames: Map, siteName: string): UnifiSsid | null { const d = obj(raw); const id = str(d.id); const name = str(d.name); if (!id || !name) return null; const sec = str(obj(d.securityConfiguration).type); const net = obj(d.network); const networkId = str(net.networkId); return { externalId: id, name, enabled: d.enabled !== false, security: sec ? (API_SECURITY[sec.toUpperCase()] ?? sec) : null, networkName: networkId ? (networkNames.get(networkId) ?? null) : str(net.type)?.toUpperCase() === "NATIVE" ? "Default" : null, vlanId: null, siteName, }; } const LEGACY_SECURITY: Record = { open: "Open", wpapsk: "WPA personal", wpaeap: "WPA enterprise" }; export function ssidFromLegacy(raw: unknown, networkNames: Map, siteName: string): UnifiSsid | null { const d = obj(raw); const id = str(d._id); const name = str(d.name); if (!id || !name) return null; const sec = str(d.security); const networkId = str(d.networkconf_id); const vlan = d.vlan_enabled === true ? num(d.vlan) : null; return { externalId: id, name, enabled: d.enabled !== false, security: sec ? (LEGACY_SECURITY[sec.toLowerCase()] ?? sec) : null, networkName: networkId ? (networkNames.get(networkId) ?? null) : null, vlanId: vlan, siteName, }; } // ─── HTTP ─────────────────────────────────────────────────────────────────── const REQUEST_TIMEOUT_MS = 15_000; /** How many per-device / per-network requests are in flight at once: a controller is a small box. */ const CONCURRENCY = 4; const PAGE = 200; interface RawResponse { status: number; headers: http.IncomingHttpHeaders; text: string; } function request(url: string, opts: { method?: "GET" | "POST"; headers?: Record; body?: unknown; insecure: boolean }): Promise { return new Promise((resolve, reject) => { const parsed = new URL(url); const isHttps = parsed.protocol === "https:"; const lib = isHttps ? https : http; const payload = opts.body === undefined ? null : JSON.stringify(opts.body); const req = lib.request( { hostname: parsed.hostname, port: parsed.port || (isHttps ? 443 : 80), path: parsed.pathname + parsed.search, method: opts.method ?? "GET", headers: { Accept: "application/json", ...(payload ? { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(payload)) } : {}), ...opts.headers }, timeout: REQUEST_TIMEOUT_MS, ...(isHttps ? { rejectUnauthorized: !opts.insecure } : {}), }, (res) => { let body = ""; res.setEncoding("utf8"); res.on("data", (chunk) => { body += chunk; }); res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, text: body })); }, ); req.on("timeout", () => req.destroy(new Error(`timed out after ${REQUEST_TIMEOUT_MS / 1000}s`))); req.on("error", reject); if (payload) req.write(payload); req.end(); }); } function parseJson(res: RawResponse): any { try { return res.text ? JSON.parse(res.text) : null; } catch { return null; } } /** Runs `work` over `items` a few at a time, keeping the order of the results. */ async function pooled(items: T[], work: (item: T) => Promise): Promise { const out: R[] = new Array(items.length); let next = 0; await Promise.all( Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => { while (next < items.length) { const i = next++; out[i] = await work(items[i]); } }), ); return out; } const messageOf = (err: unknown) => (err instanceof Error ? err.message : String(err)); export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter { const insecure = config.insecure === true; const root = config.url.replace(/\/+$/, ""); const wantSite = (config.site ?? "").trim().toLowerCase(); const useKey = typeof config.apiKey === "string" && config.apiKey.trim() !== ""; if (!useKey && !(config.username && config.password)) throw new Error("UniFi needs an API key, or a username and password"); // ── API key ── async function apiGet(prefix: string, path: string): Promise { const res = await request(`${root}${prefix}${path}`, { headers: { "X-API-KEY": config.apiKey!.trim() }, insecure }); if (res.status === 401 || res.status === 403) throw new Error("UniFi did not accept the API key (HTTP " + res.status + ")"); if (res.status < 200 || res.status >= 300) throw new Error(`UniFi API error: HTTP ${res.status}${parseJson(res)?.message ? ` — ${parseJson(res).message}` : ""}`); const body = parseJson(res); if (body === null) throw new Error("UniFi answered with something that isn't JSON — is the address the controller's?"); return body; } /** Every page of a list endpoint ({offset, limit, count, totalCount, data}). */ async function apiPaged(prefix: string, path: string): Promise { const out: unknown[] = []; for (let offset = 0; offset < 10_000; ) { const body = await apiGet(prefix, `${path}${path.includes("?") ? "&" : "?"}offset=${offset}&limit=${PAGE}`); const data = list(body?.data); out.push(...data); const total = num(body?.totalCount); offset += data.length; if (data.length === 0 || total === null || offset >= total) break; } return out; } let cachedPrefix: string | null = null; async function apiPrefix(): Promise { if (cachedPrefix !== null) return cachedPrefix; const candidates = config.selfHosted ? ["/integration/v1"] : ["/proxy/network/integration/v1", "/integration/v1"]; let last: unknown = null; for (const prefix of candidates) { try { await apiGet(prefix, "/sites?limit=1"); cachedPrefix = prefix; return prefix; } catch (err) { last = err; // Only "not found" means this form of the address is the wrong one; a rejected key or a dead host will not be any better on the other. if (!/HTTP 404/.test(messageOf(err))) throw err; } } throw new Error(`UniFi has no Integration API at this address${messageOf(last) ? ` (${messageOf(last)})` : ""} — it needs Network 9 or later; for an older controller use a username and password`); } async function inventoryViaKey(): Promise { const prefix = await apiPrefix(); let sites = list(await apiPaged(prefix, "/sites")).map((s) => ({ id: str(obj(s).id), name: str(obj(s).name) ?? str(obj(s).internalReference) ?? "Default" })); sites = sites.filter((s) => s.id); if (wantSite) { sites = sites.filter((s) => s.name.toLowerCase() === wantSite); if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`); } const inventory: UnifiInventory = { mode: "api_key", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] }; for (const site of sites) { const base = `/sites/${site.id}`; const entries = await apiPaged(prefix, `${base}/devices`); const macById = new Map(); for (const e of entries) { const id = str(obj(e).id); const mac = normaliseMac(obj(e).macAddress); if (id && mac) macById.set(id, mac); } const details = await pooled(entries, async (e) => { const id = str(obj(e).id); if (!id) return { detail: null, stats: null }; // A device whose detail or statistics cannot be read is still listed, just without its uplink or uptime. const [detail, stats] = await Promise.all([apiGet(prefix, `${base}/devices/${id}`).catch(() => null), apiGet(prefix, `${base}/devices/${id}/statistics/latest`).catch(() => null)]); return { detail, stats }; }); entries.forEach((e, i) => { const d = deviceFromApi(e, details[i].detail, details[i].stats, site.name, macById); if (d) inventory.devices.push(d); }); const netEntries = await apiPaged(prefix, `${base}/networks`).catch(() => []); const netDetails = await pooled(netEntries, async (e) => { const id = str(obj(e).id); return id ? apiGet(prefix, `${base}/networks/${id}`).catch(() => null) : null; }); const networkNames = new Map(); netEntries.forEach((e, i) => { const n = networkFromApi(e, netDetails[i], site.name); if (n) { inventory.networks.push(n); networkNames.set(n.externalId, n.name); } }); for (const raw of await apiPaged(prefix, `${base}/wifi/broadcasts`).catch(() => [])) { const s = ssidFromApi(raw, networkNames, site.name); if (s) inventory.ssids.push(s); } } return inventory; } // ── Login ── interface Session { prefix: string; headers: Record; logout: () => Promise; } async function login(): Promise { const body = { username: config.username, password: config.password, remember: false }; // A UniFi OS console logs in at /api/auth/login and serves the Network application under /proxy/network; a self-hosted one at /api/login. const attempts = config.selfHosted ? [{ path: "/api/login", prefix: "", os: false }] : [{ path: "/api/auth/login", prefix: "/proxy/network", os: true }, { path: "/api/login", prefix: "", os: false }]; let last: RawResponse | null = null; for (const a of attempts) { const res = await request(`${root}${a.path}`, { method: "POST", body, insecure }); last = res; if (res.status === 404) continue; if (res.status === 400 || res.status === 401 || res.status === 403) throw new Error("UniFi did not accept the username and password"); if (res.status < 200 || res.status >= 300) throw new Error(`UniFi login failed: HTTP ${res.status}`); const cookies = list(res.headers["set-cookie"]) .map((c) => String(c).split(";")[0]) .filter(Boolean) .join("; "); if (!cookies) throw new Error("UniFi accepted the login but sent no session"); const headers: Record = { Cookie: cookies }; const csrf = res.headers["x-csrf-token"] ?? res.headers["x-updated-csrf-token"]; if (typeof csrf === "string") headers["X-CSRF-Token"] = csrf; return { prefix: a.prefix, headers, // Best effort: give the session back rather than leave one open per sync. logout: async () => { try { await request(`${root}${a.os ? "/api/auth/logout" : "/api/logout"}`, { method: "POST", headers, body: {}, insecure }); } catch { // nothing to do about it } }, }; } throw new Error(`UniFi has no login at this address${last ? ` (HTTP ${last.status})` : ""} — check the address, and the “self-hosted” box`); } async function legacyGet(session: Session, path: string): Promise { const res = await request(`${root}${session.prefix}${path}`, { headers: session.headers, insecure }); if (res.status === 401 || res.status === 403) throw new Error("UniFi did not allow this account to read that (HTTP " + res.status + ")"); if (res.status < 200 || res.status >= 300) throw new Error(`UniFi API error: HTTP ${res.status}`); const body = parseJson(res); if (body === null) throw new Error("UniFi answered with something that isn't JSON — is the address the controller's?"); return list(body.data); } async function inventoryViaLogin(): Promise { const session = await login(); try { let sites = (await legacyGet(session, "/api/self/sites")).map((s) => ({ key: str(obj(s).name), name: str(obj(s).desc) ?? str(obj(s).name) ?? "Default" })).filter((s): s is { key: string; name: string } => !!s.key); if (wantSite) { sites = sites.filter((s) => s.name.toLowerCase() === wantSite || s.key.toLowerCase() === wantSite); if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`); } const inventory: UnifiInventory = { mode: "login", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] }; for (const site of sites) { for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/device`)) { const d = deviceFromLegacy(raw, site.name); if (d) inventory.devices.push(d); } const networkNames = new Map(); for (const raw of await legacyGet(session, `/api/s/${site.key}/rest/networkconf`).catch(() => [])) { const n = networkFromLegacy(raw, site.name); if (n) { inventory.networks.push(n); networkNames.set(n.externalId, n.name); } } for (const raw of await legacyGet(session, `/api/s/${site.key}/rest/wlanconf`).catch(() => [])) { const s = ssidFromLegacy(raw, networkNames, site.name); if (s) inventory.ssids.push(s); } } return inventory; } finally { await session.logout(); } } async function fetchInventory(): Promise { return useKey ? inventoryViaKey() : inventoryViaLogin(); } async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> { const start = Date.now(); try { if (useKey) { await apiPrefix(); } else { const session = await login(); await session.logout(); } return { ok: true, latencyMs: Date.now() - start }; } catch (err) { return { ok: false, error: messageOf(err) }; } } return withDiagLogging("unifi", { ping, fetchInventory }); }