import { ResponseError } from "@homarr/common/server"; import type { z } from "zod/v4"; import type { UnifiOsClientCounts, UnifiOsDevice, UnifiOsDeviceStatistics, UnifiOsSite } from "./unifi-os-types"; import { countClients, createUnifiOsPageSchema, parseUnifiOsAsync, unifiOsClientSchema, unifiOsDeviceSchema, unifiOsDeviceStatisticsSchema, unifiOsInfoSchema, unifiOsSiteSchema, unifiOsVpnServerSchema, } from "./unifi-os-types"; export type UnifiOsFetch = (url: string, init?: RequestInit & { timeout?: number }) => Promise; const INTEGRATION_PATH = "/proxy/network/integration/v1"; const REQUEST_TIMEOUT_MS = 10_000; /** Plafond imposé par l'API : demander davantage renvoie quand même 200. */ const MAX_PAGE_LIMIT = 200; const PARSE_ERROR_MESSAGE = "Invalid UniFi OS response"; const clientPageSchema = createUnifiOsPageSchema(unifiOsClientSchema); const devicePageSchema = createUnifiOsPageSchema(unifiOsDeviceSchema); const sitePageSchema = createUnifiOsPageSchema(unifiOsSiteSchema); const vpnServerPageSchema = createUnifiOsPageSchema(unifiOsVpnServerSchema); /** * Client de l'API d'intégration locale d'UniFi OS. * * Ne connaît ni Homarr ni la notion d'intégration : il ne sait que parler à une * console. Le `fetch` est injecté pour que les tests n'aient pas à mocker un module. */ export class UnifiOsApi { private readonly baseUrl: string; constructor( origin: string, private readonly apiKey: string, private readonly fetchAsync: UnifiOsFetch, ) { this.baseUrl = `${origin.replace(/\/+$/, "")}${INTEGRATION_PATH}`; } public async getInfoAsync(): Promise<{ applicationVersion: string }> { return await this.requestAsync("/info", unifiOsInfoSchema); } public async getFirstSiteAsync(): Promise { const page = await this.requestAsync("/sites", sitePageSchema); return page.data[0] ?? null; } public async getDevicesAsync(siteId: string): Promise { const page = await this.requestAsync( `/sites/${encodeURIComponent(siteId)}/devices?limit=${MAX_PAGE_LIMIT}`, devicePageSchema, ); return page.data; } public async getDeviceStatisticsAsync(siteId: string, deviceId: string): Promise { return await this.requestAsync( `/sites/${encodeURIComponent(siteId)}/devices/${encodeURIComponent(deviceId)}/statistics/latest`, unifiOsDeviceStatisticsSchema, ); } public async getVpnServersAsync(siteId: string): Promise<{ enabled: boolean }[]> { const page = await this.requestAsync(`/sites/${encodeURIComponent(siteId)}/vpn/servers`, vpnServerPageSchema); return page.data; } /** * Sous le plafond de 200 clients, une seule page suffit et le comptage se fait * en mémoire. Au-delà, rapatrier tous les enregistrements pour n'en tirer que * des compteurs coûterait plus cher que cinq requêtes bornées. */ public async getClientCountsAsync(siteId: string): Promise { const path = `/sites/${encodeURIComponent(siteId)}/clients`; const firstPage = await this.requestAsync(`${path}?limit=${MAX_PAGE_LIMIT}`, clientPageSchema); if (firstPage.totalCount <= MAX_PAGE_LIMIT) { return countClients(firstPage.data); } const countByFilterAsync = async (filter: string) => { const page = await this.requestAsync(`${path}?limit=1&filter=${encodeURIComponent(filter)}`, clientPageSchema); return page.totalCount; }; const [wired, wireless, vpn, teleport, guests] = await Promise.all([ countByFilterAsync("type.eq('WIRED')"), countByFilterAsync("type.eq('WIRELESS')"), countByFilterAsync("type.eq('VPN')"), countByFilterAsync("type.eq('TELEPORT')"), countByFilterAsync("access.type.eq('GUEST')"), ]); return { total: firstPage.totalCount, wired, wireless, vpn: vpn + teleport, guests }; } private async requestAsync(path: string, schema: z.ZodType): Promise { const response = await this.fetchAsync(`${this.baseUrl}${path}`, { headers: { "X-API-KEY": this.apiKey, Accept: "application/json" }, timeout: REQUEST_TIMEOUT_MS, }); if (!response.ok) { throw new ResponseError(response); } return await parseUnifiOsAsync(await response.json(), schema, PARSE_ERROR_MESSAGE); } }