diff --git a/DATABASE.md b/DATABASE.md index b121b16..20ac462 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -55,6 +55,8 @@ erDiagram endpoint_checks ||--o{ endpoint_results : "cascade" heartbeats ||--o{ heartbeat_pings : "cascade" integration_credentials ||--o{ integrations : "credential (set null)" + integrations ||--o{ network_devices : "cascade" + integrations ||--o{ network_segments : "cascade" integration_credentials ||--o{ dns_providers : "credential (set null)" dns_providers ||--o{ dns_zones_cache : "cascade" dns_providers ||--o{ dns_records_cache : "cascade" @@ -148,7 +150,7 @@ required, so a forgotten window can't silence real problems forever. | Column | Type | Notes | |---|---|---| | `id` | integer PK | | -| `target_type` | text NOT NULL | `server` \| `integration` \| `dns_provider`. | +| `target_type` | text NOT NULL | `server` \| `integration` \| `dns_provider` \| `device`. | | `target_id` | integer NOT NULL | The ID in the table `target_type` names. **Not a foreign key**; a window whose target was deleted is simply ignored. | | `reason` | text | | | `started_at`, `ends_at` | text NOT NULL | ISO. | @@ -456,6 +458,8 @@ JSON) plus a few internal bookkeeping rows. Details under | `value` | text NOT NULL | JSON (or a plain date/time for internal flags). | | `updated_at` | text NOT NULL | | +Internal flag `unifiSync`: a JSON object keyed by integration id, `{ at (ISO — the last *successful* read), ok, error, sites, mode, devices, networks, ssids }`. A controller whose `at` is older than twenty minutes is not judged for offline devices. + Internal flag `flapState`: a JSON object keyed by alert key, `{ raises: number[] (epoch ms of raises in the last hour), flapping: boolean, since, lastEvent, message }`. It is what lets a restart remember which alerts are being held as flapping; entries are dropped once an alert has been calm for an hour. #### `tag_definitions` @@ -641,17 +645,55 @@ The hardware inventory. #### `dependencies` -"A needs B" between servers and integrations: when B is down, A's alert is folded under B's. The "runs on" links of servers are part of the same graph but live on `servers`. +"A needs B" between servers, network devices and integrations: when B is down, A's alert is folded under B's. The "runs on" links of servers are part of the same graph but live on `servers`, and the "connected through" links of network devices on `network_devices`. | Column | Type | Notes | |---|---|---| | `id` | integer PK | | -| `from_type`, `from_id` | text, integer NOT NULL | The thing that needs: `server` or `integration`, and its id. | +| `from_type`, `from_id` | text, integer NOT NULL | The thing that needs: `server`, `integration` or `device`, and its id. | | `to_type`, `to_id` | text, integer NOT NULL | The thing it needs. Unique together with the pair above. | | `created_at` | text NOT NULL | ISO. | No foreign keys (like `maintenance_windows`): a row whose server or integration is gone is ignored, not an error. +#### `network_devices` + +Switches, access points and gateways read from a UniFi controller (see INTEGRATIONS.md), refreshed every five minutes. A device is a node of the dependency map as `device:`. + +| Column | Type | Notes | +|---|---|---| +| `id` | integer PK | | +| `integration_id` | integer NOT NULL → `integrations.id`, **cascade** | The controller. Unique together with `external_id`. | +| `external_id` | text NOT NULL | The MAC address, lower case with colons. | +| `site_name`, `name`, `model` | text | | +| `kind` | text NOT NULL | `gateway` \| `switch` \| `access_point` \| `other`. | +| `ip`, `mac` | text | | +| `state` | text NOT NULL | `online` \| `offline` \| `updating` \| `pending` \| `other`. Only `offline` raises an alert. | +| `uptime_seconds` | integer | | +| `firmware` | text | | +| `firmware_updatable` | bool NOT NULL | | +| `uplink_external_id` | text | The MAC of the device this one is connected through; what makes it depend on that device. | +| `offline_since` | text | ISO. When the controller first stopped seeing it online; null while online. The offline alert counts from here. | +| `last_online_at`, `first_seen_at`, `updated_at` | text | ISO. | + +A device the controller no longer lists is deleted on the next read. Dependencies written by hand that mention a removed device are ignored. + +#### `network_segments` + +The networks (VLANs) and Wi-Fi names of a UniFi controller, replaced as a whole on every read. Passphrases are never stored. + +| Column | Type | Notes | +|---|---|---| +| `id` | integer PK | | +| `integration_id` | integer NOT NULL → `integrations.id`, **cascade** | Unique together with `kind` and `external_id`. | +| `kind` | text NOT NULL | `network` \| `ssid`. | +| `external_id`, `site_name`, `name` | text | | +| `enabled` | bool NOT NULL | | +| `vlan_id` | integer | | +| `subnet`, `purpose` | text | A network's address range and what it is for. | +| `security`, `network_name` | text | A Wi-Fi name's security, and the network its clients land on. | +| `updated_at` | text NOT NULL | ISO. | + #### `push_subscriptions` A browser or phone that asked for push notifications, one row per device. @@ -855,7 +897,7 @@ that were never changed aren't stored; the app fills in defaults when reading. | `inventory` | `currency` (a short name, may be blank) and `pricePerKwh` (null) — what the inventory's running cost is worked out with. | | `monthlyReport` | The monthly report: `enabled` (false), `day` (1–28, default 1) and `time` (`HH:MM`, default `08:00`), in the notification time zone. | | `digest` | The weekly digest: `enabled` (false), `day` (0 = Sunday … 6; default 1, Monday) and `time` (`HH:MM`, default `08:00`), in the notification time zone. | -| `healthChecks` | `restoreTestDays` (0 = off — how long a guest's last passing restore test counts; a failed one is always raised), `serverOfflineMinutes` (60), `diskUsagePercent` (90), `domainWarnDays` (30), `diskForecastDays` (14; 0 = off — how far ahead a filling disk is flagged on the Alerts page), `backupStaleHours` (48; 0 = off — how old a Proxmox guest's newest backup may be), `newPortAlerts` (true — warn when a server starts listening on a TCP port that is not in its baseline and not noted), `flapRaises` (3; 0 = off — raises of one alert within an hour that make it "flapping" so its messages are held; see NOTIFICATIONS.md). A server can override each of these (see `servers.thresholds`). | +| `healthChecks` | `restoreTestDays` (0 = off — how long a guest's last passing restore test counts; a failed one is always raised), `serverOfflineMinutes` (60), `diskUsagePercent` (90), `domainWarnDays` (30), `diskForecastDays` (14; 0 = off — how far ahead a filling disk is flagged on the Alerts page), `backupStaleHours` (48; 0 = off — how old a Proxmox guest's newest backup may be), `newPortAlerts` (true — warn when a server starts listening on a TCP port that is not in its baseline and not noted), `flapRaises` (3; 0 = off — raises of one alert within an hour that make it "flapping" so its messages are held; see NOTIFICATIONS.md), `deviceOfflineMinutes` (10 — how long a UniFi device may be offline before it is raised). A server can override each of these (see `servers.thresholds`). | | `logRetention` | `enabled`, `retentionDays` (90), `intervalHours` (24). | | `display` | `dateFormat`, `timeFormat`, `pageSize`. | | `providerColors`, `integrationColors` | Badge colours, by provider / integration type. | diff --git a/INTEGRATIONS.md b/INTEGRATIONS.md index 155cb19..8a7d215 100644 --- a/INTEGRATIONS.md +++ b/INTEGRATIONS.md @@ -6,10 +6,10 @@ Homelab Manager (Integrations → Add integration, or DNS → Add provider). All credentials are entered in-app and encrypted at rest — nothing is read from environment variables. -Every adapter listed here performs write actions (starting/stopping +Every adapter listed here except UniFi performs write actions (starting/stopping things, editing DNS records, etc.), not just reads — a read-only credential will fail as soon as you use one of those actions, even if -the dashboard views themselves load fine. +the dashboard views themselves load fine. (UniFi only ever reads.) ## Integrations @@ -224,6 +224,28 @@ the dashboard views themselves load fine. run it against a real phpIPAM yet. If a sync comes back empty or with the wrong fields, tell us what your instance actually returned and we'll adjust. +### UniFi (Network application) + +- **Config fields:** controller URL; **either** an API key, **or** a username and password; optionally one site; two checkboxes — *self-hosted Network application* and *allow self-signed certificate*. +- **Two ways in:** + - **API key** (UniFi Network 9 or later). In the controller, **Settings → Control Plane → Integrations → Create API key**. Used with the official Integration API: on a UniFi OS console (UDM, Cloud Gateway, + Cloud Key Gen2+) at `https:///proxy/network/integration/v1/…`, on a self-hosted Network application at `https://:8443/integration/v1/…`. The form is found by asking, so the URL is + just the console's address; tick *self-hosted* only to skip the first guess. + - **Username and password** (any version, including ones from before API keys). Create a **local** user in the controller with **read-only** access to the site (a Ubiquiti cloud/SSO account, or one with + two-factor, cannot be used). The classic endpoints are used (`/proxy/network/api/s//…`, or `/api/s//…` self-hosted), and the session is logged out after each read. +- **Required access:** read only — and, unlike most integrations here, **nothing is ever written** to the controller. +- **What it does:** every five minutes (and on **Read now**) the controller is read and kept: each device's name, model, kind (gateway, switch, access point), state, IP address, MAC address, uptime, firmware (and + whether an update is waiting), and the device it is connected through; and the networks (VLAN, address range) and Wi-Fi names (security, which network) it has set up. Wi-Fi passphrases are never read into the app. + It all appears on **Network → Network devices**. + - A device is a **node in the dependency map**, like a server: the *connected through* link is made into a dependency by itself (an access point needs its switch, the switch needs the gateway), and you can write + others by hand (a server needs the switch it is plugged into). + - A device the controller has not seen online for longer than **Settings → Notifications → Alert when a network device is offline for** (10 minutes) is a critical **offline** alert about it. What needs it, and what + it is connected through if that is down too, is folded under it, like a guest under its host. It can be silenced with a maintenance window, and has runbooks like any target. + - If the controller cannot be read for twenty minutes its devices are neither raised nor cleared, and the Alerts page says it could not check; the integration itself is raised as failing like any other. +- **Not verified against a live controller** — built from Ubiquiti's published Integration API and the long-documented classic API (and tried against a pretend controller that answers the way those documents say), + but nobody has run it against real hardware yet. Every field is read defensively, so one a version renames is left blank rather than breaking the read. If a read fails or comes back empty, the **Diagnostic Log** has + what the controller answered; tell us and we'll adjust. + ## DNS providers ### Cloudflare diff --git a/NOTIFICATIONS.md b/NOTIFICATIONS.md index 804c8fc..758660f 100644 --- a/NOTIFICATIONS.md +++ b/NOTIFICATIONS.md @@ -170,6 +170,13 @@ A scheduled backup of the app's own database that fails sends one message throug Availability of servers and endpoints, incidents (how many, how long they took, the longest), updates and patch plan runs, restore tests and the state of the backups, and what was renewed — a topic only where there is something to say. The same report is on the Monthly report page. *Preview last month* and *Send last month now* are on the settings page. +## Network devices + +A switch, access point or gateway that a UniFi controller has not seen online for longer than the limit (Settings → Notifications → *Servers and disks*, 10 minutes) is announced like a server that stopped reporting, under +*Server offline, disk nearly full …* (`healthAlerts`): "Hallway AP (access point, U6 Pro) has been offline for 45 min", with a recovery message when it is back. For routing it counts as *Server down*; maintenance on the +device holds it back; and what depends on it (or it is connected through, if that is down too) is folded under it and named in its message ("— also takes down …"). The controller is read every five minutes; if it cannot be +read for twenty, its devices are held — neither announced nor cleared. + ## Flapping alerts A health alert that is raised, clears and is raised again is announced the first times as usual. When the same alert has been raised **three times within an hour** (Settings → Notifications → *Servers and disks*; 0 = off) it is *flapping*: diff --git a/README.md b/README.md index 5ae8e5d..718bee6 100644 --- a/README.md +++ b/README.md @@ -804,6 +804,13 @@ nobody has noted is a warning on the Alerts page (kind *Monitoring*) and a notif (where programs pick a free one) and anything bound to localhost only are left out. The port's row on the server's **Ports** card says *New* and has **Mark as expected**, which notes it and ends the alert; so does a label or comment you write on it yourself. It also ends when the port stops listening, and maintenance on the server holds it back like its other alerts. It can be switched off under Settings → Notifications (*Servers and disks*); servers get their baseline from their next report after an upgrade, so nothing alerts for what was already there. +**UniFi network equipment.** Add a UniFi controller under Integrations (an API key, or a read-only local account; see INTEGRATIONS.md) and **Network → Network devices** lists its switches, access points and +gateways: whether each is up (and since when it was not), IP and MAC address, uptime, firmware (with *update available*), the device it is connected through, how many things depend on it, and — on the *Networks & Wi-Fi* tab — +its networks (VLAN, address range) and Wi-Fi names (security, which network). It is read every five minutes and on **Read now**; nothing is ever written to the controller, and Wi-Fi passphrases are never read. The devices +join the **dependency map** (Map → Dependencies): what each is connected through becomes a dependency by itself, you can write others ("the NAS needs the rack switch"), and when a device is down, what needs it is folded under +its alert — "Hallway AP has been offline for 45 min — also takes down pi". A device offline for longer than a set time (Settings → Notifications, 10 minutes) is a critical *Server down* alert, can be silenced with maintenance +(also in the Maintenance page and the command palette), and can have runbooks. Not yet tried against a real controller — see INTEGRATIONS.md. + **Flapping alerts and the noise report.** An alert that is raised and clears again and again is more tiring than one that stays: each raise and each recovery is a message. When the same alert has been **raised three times within an hour** (Settings → Notifications → *Servers and disks* → *Call an alert flapping after*; 0 turns it off) it is called **flapping**: one message says so — "raised 3 times within an hour" — and its further raise and recovery messages are held back. The alert itself is still on the Alerts page, with a *flapping* badge, and keeps counting for the badge in the menu and for /metrics. diff --git a/ROLES.md b/ROLES.md index cc35413..1f6a4de 100644 --- a/ROLES.md +++ b/ROLES.md @@ -99,6 +99,8 @@ even further, to admin only: operator, and so does *Refresh from agent*; the price of power used for the running cost is admin-only. - **Bulk actions** (the bar that appears when rows are ticked) need the same role as the single action: operator to acknowledge, silence, tag, change hardware and undo any of those; administrator for *Runs on…* on several servers (and its undo). Viewers do not see the tick boxes. The **Noise** tab of Alerts is for everyone signed in. +- **Network devices** (Network → Network devices): everyone can see the devices, networks and Wi-Fi names read from UniFi controllers; **Read now** and putting a device under maintenance need operator; adding the UniFi + integration itself (a key or login) is an administrator's job, like any integration. - **Dependencies**: everyone can see what needs what; adding and removing one needs operator. - **Endpoints**: everyone sees the checks and how they are doing; adding, changing and removing one is administrator-only (each makes the server connect somewhere); *Check now* needs operator. diff --git a/server/drizzle/0044_sparkling_scourge.sql b/server/drizzle/0044_sparkling_scourge.sql new file mode 100644 index 0000000..324a6f5 --- /dev/null +++ b/server/drizzle/0044_sparkling_scourge.sql @@ -0,0 +1,41 @@ +CREATE TABLE `network_devices` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `integration_id` integer NOT NULL, + `external_id` text NOT NULL, + `site_name` text, + `name` text NOT NULL, + `model` text, + `kind` text DEFAULT 'other' NOT NULL, + `ip` text, + `mac` text, + `state` text DEFAULT 'other' NOT NULL, + `uptime_seconds` integer, + `firmware` text, + `firmware_updatable` integer DEFAULT false NOT NULL, + `uplink_external_id` text, + `offline_since` text, + `last_online_at` text, + `first_seen_at` text NOT NULL, + `updated_at` text NOT NULL, + FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `network_devices_unique` ON `network_devices` (`integration_id`,`external_id`);--> statement-breakpoint +CREATE TABLE `network_segments` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `integration_id` integer NOT NULL, + `kind` text NOT NULL, + `external_id` text NOT NULL, + `site_name` text, + `name` text NOT NULL, + `enabled` integer DEFAULT true NOT NULL, + `vlan_id` integer, + `subnet` text, + `purpose` text, + `security` text, + `network_name` text, + `updated_at` text NOT NULL, + FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `network_segments_unique` ON `network_segments` (`integration_id`,`kind`,`external_id`); \ No newline at end of file diff --git a/server/drizzle/meta/0044_snapshot.json b/server/drizzle/meta/0044_snapshot.json new file mode 100644 index 0000000..1678141 --- /dev/null +++ b/server/drizzle/meta/0044_snapshot.json @@ -0,0 +1,4633 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "48aafec3-a2de-4c4a-9d6d-3e4ee3a765c1", + "prevId": "603c307c-a4f9-455b-8a9e-8a7d63c04d98", + "tables": { + "alert_acks": { + "name": "alert_acks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "assignee_user_id": { + "name": "assignee_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assignee_name": { + "name": "assignee_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "acked_by": { + "name": "acked_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "acked_at": { + "name": "acked_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "until": { + "name": "until", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "alert_acks_key_idx": { + "name": "alert_acks_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "alert_acks_assignee_user_id_users_id_fk": { + "name": "alert_acks_assignee_user_id_users_id_fk", + "tableFrom": "alert_acks", + "tableTo": "users", + "columnsFrom": [ + "assignee_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_incidents": { + "name": "alert_incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "peak_severity": { + "name": "peak_severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "link": { + "name": "link", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_name": { + "name": "target_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "caused_by": { + "name": "caused_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "opened_at": { + "name": "opened_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "missing_since": { + "name": "missing_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "escalated_step": { + "name": "escalated_step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "escalated_at": { + "name": "escalated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_incidents_key_idx": { + "name": "alert_incidents_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + }, + "alert_incidents_opened_idx": { + "name": "alert_incidents_opened_idx", + "columns": [ + "opened_at" + ], + "isUnique": false + }, + "alert_incidents_target_idx": { + "name": "alert_incidents_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_tickets": { + "name": "alert_tickets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seen_count": { + "name": "seen_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ticket_number": { + "name": "ticket_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grouped": { + "name": "grouped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ticketed_at": { + "name": "ticketed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cleared_at": { + "name": "cleared_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_tickets_key_idx": { + "name": "alert_tickets_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + } + }, + "foreignKeys": { + "alert_tickets_integration_id_integrations_id_fk": { + "name": "alert_tickets_integration_id_integrations_id_fk", + "tableFrom": "alert_tickets", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assets": { + "name": "assets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "manufacturer": { + "name": "manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "serial": { + "name": "serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_date": { + "name": "purchase_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_price": { + "name": "purchase_price", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warranty_until": { + "name": "warranty_until", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end_of_support": { + "name": "end_of_support", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "replacement_cost": { + "name": "replacement_cost", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rack_unit": { + "name": "rack_unit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_watts": { + "name": "power_watts", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_label": { + "name": "actor_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "audit_log_actor_user_id_users_id_fk": { + "name": "audit_log_actor_user_id_users_id_fk", + "tableFrom": "audit_log", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "consistency_ignores": { + "name": "consistency_ignores", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "consistency_ignores_key_unique": { + "name": "consistency_ignores_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dependencies": { + "name": "dependencies", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "from_type": { + "name": "from_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "from_id": { + "name": "from_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_type": { + "name": "to_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_id": { + "name": "to_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "dependencies_edge_idx": { + "name": "dependencies_edge_idx", + "columns": [ + "from_type", + "from_id", + "to_type", + "to_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "diag_log": { + "name": "diag_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latency_ms": { + "name": "latency_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_providers": { + "name": "dns_providers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_type": { + "name": "provider_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "dns_providers_credential_id_integration_credentials_id_fk": { + "name": "dns_providers_credential_id_integration_credentials_id_fk", + "tableFrom": "dns_providers", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_records_cache": { + "name": "dns_records_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ttl": { + "name": "ttl", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxied": { + "name": "proxied", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "dns_records_cache_provider_id_dns_providers_id_fk": { + "name": "dns_records_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_records_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_zones_cache": { + "name": "dns_zones_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_name": { + "name": "zone_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "dns_zones_cache_provider_zone_idx": { + "name": "dns_zones_cache_provider_zone_idx", + "columns": [ + "provider_id", + "zone_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "dns_zones_cache_provider_id_dns_providers_id_fk": { + "name": "dns_zones_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_zones_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "domains": { + "name": "domains", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'manual'" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registrar": { + "name": "registrar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lookup_source": { + "name": "lookup_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_ok_at": { + "name": "last_checked_ok_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "domains_name_unique": { + "name": "domains_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_checks": { + "name": "endpoint_checks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expect_status": { + "name": "expect_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "keyword": { + "name": "keyword", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "insecure": { + "name": "insecure", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "interval_minutes": { + "name": "interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "timeout_seconds": { + "name": "timeout_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 10 + }, + "failures_before_alert": { + "name": "failures_before_alert", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 14 + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_ok": { + "name": "last_ok", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message": { + "name": "last_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_response_ms": { + "name": "last_response_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cert_expires_at": { + "name": "cert_expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_change_at": { + "name": "last_change_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_daily": { + "name": "endpoint_daily", + "columns": { + "check_id": { + "name": "check_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_sum": { + "name": "ms_sum", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_count": { + "name": "ms_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "endpoint_daily_check_id_endpoint_checks_id_fk": { + "name": "endpoint_daily_check_id_endpoint_checks_id_fk", + "tableFrom": "endpoint_daily", + "tableTo": "endpoint_checks", + "columnsFrom": [ + "check_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "endpoint_daily_check_id_day_pk": { + "columns": [ + "check_id", + "day" + ], + "name": "endpoint_daily_check_id_day_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_results": { + "name": "endpoint_results", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "check_id": { + "name": "check_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ms": { + "name": "ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "endpoint_results_check_idx": { + "name": "endpoint_results_check_idx", + "columns": [ + "check_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "endpoint_results_check_id_endpoint_checks_id_fk": { + "name": "endpoint_results_check_id_endpoint_checks_id_fk", + "tableFrom": "endpoint_results", + "tableTo": "endpoint_checks", + "columnsFrom": [ + "check_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "event_webhooks": { + "name": "event_webhooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_result": { + "name": "last_result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "heartbeat_pings": { + "name": "heartbeat_pings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "heartbeat_id": { + "name": "heartbeat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "heartbeat_pings_idx": { + "name": "heartbeat_pings_idx", + "columns": [ + "heartbeat_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "heartbeat_pings_heartbeat_id_heartbeats_id_fk": { + "name": "heartbeat_pings_heartbeat_id_heartbeats_id_fk", + "tableFrom": "heartbeat_pings", + "tableTo": "heartbeats", + "columnsFrom": [ + "heartbeat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "heartbeats": { + "name": "heartbeats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "period_minutes": { + "name": "period_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grace_minutes": { + "name": "grace_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 10 + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_ping_at": { + "name": "last_ping_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_status": { + "name": "last_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message": { + "name": "last_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_duration_ms": { + "name": "last_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_start_at": { + "name": "last_start_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ping_count": { + "name": "ping_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "heartbeats_token_unique": { + "name": "heartbeats_token_unique", + "columns": [ + "token" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_notes": { + "name": "incident_notes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "incident_id": { + "name": "incident_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "author": { + "name": "author", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "incident_notes_incident_idx": { + "name": "incident_notes_incident_idx", + "columns": [ + "incident_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "incident_notes_incident_id_alert_incidents_id_fk": { + "name": "incident_notes_incident_id_alert_incidents_id_fk", + "tableFrom": "incident_notes", + "tableTo": "alert_incidents", + "columnsFrom": [ + "incident_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integration_credentials": { + "name": "integration_credentials", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encrypted_secret": { + "name": "encrypted_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integrations": { + "name": "integrations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "integrations_credential_id_integration_credentials_id_fk": { + "name": "integrations_credential_id_integration_credentials_id_fk", + "tableFrom": "integrations", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ipam_entries": { + "name": "ipam_entries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "vendor": { + "name": "vendor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "ipam_entries_ip_address_unique": { + "name": "ipam_entries_ip_address_unique", + "columns": [ + "ip_address" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_aliases": { + "name": "maintenance_aliases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "maintenance_aliases_unique_idx": { + "name": "maintenance_aliases_unique_idx", + "columns": [ + "address", + "target_type", + "target_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_schedules": { + "name": "maintenance_schedules", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "targets": { + "name": "targets", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_windows": { + "name": "maintenance_windows", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ends_at": { + "name": "ends_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "metrics_tokens": { + "name": "metrics_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "metrics_tokens_token_hash_unique": { + "name": "metrics_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "network_devices": { + "name": "network_devices", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_name": { + "name": "site_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "ip": { + "name": "ip", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mac": { + "name": "mac", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "uptime_seconds": { + "name": "uptime_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firmware": { + "name": "firmware", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firmware_updatable": { + "name": "firmware_updatable", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "uplink_external_id": { + "name": "uplink_external_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "offline_since": { + "name": "offline_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_online_at": { + "name": "last_online_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "network_devices_unique": { + "name": "network_devices_unique", + "columns": [ + "integration_id", + "external_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "network_devices_integration_id_integrations_id_fk": { + "name": "network_devices_integration_id_integrations_id_fk", + "tableFrom": "network_devices", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "network_segments": { + "name": "network_segments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_name": { + "name": "site_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "vlan_id": { + "name": "vlan_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "subnet": { + "name": "subnet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "security": { + "name": "security", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "network_name": { + "name": "network_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "network_segments_unique": { + "name": "network_segments_unique", + "columns": [ + "integration_id", + "kind", + "external_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "network_segments_integration_id_integrations_id_fk": { + "name": "network_segments_integration_id_integrations_id_fk", + "tableFrom": "network_segments", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_queue": { + "name": "notification_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "audience": { + "name": "audience", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "patch_plan_runs": { + "name": "patch_plan_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "plan_id": { + "name": "plan_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "plan_name": { + "name": "plan_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_by": { + "name": "started_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "items": { + "name": "items", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "patch_plan_runs_plan_idx": { + "name": "patch_plan_runs_plan_idx", + "columns": [ + "plan_id", + "started_at" + ], + "isUnique": false + }, + "patch_plan_runs_status_idx": { + "name": "patch_plan_runs_status_idx", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "patch_plan_runs_plan_id_patch_plans_id_fk": { + "name": "patch_plan_runs_plan_id_patch_plans_id_fk", + "tableFrom": "patch_plan_runs", + "tableTo": "patch_plans", + "columnsFrom": [ + "plan_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "patch_plans": { + "name": "patch_plans", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "server_ids": { + "name": "server_ids", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_id": { + "name": "template_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_name": { + "name": "template_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "limit_from": { + "name": "limit_from", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'name'" + }, + "stop_on_failure": { + "name": "stop_on_failure", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "only_with_updates": { + "name": "only_with_updates", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "silence_dependents": { + "name": "silence_dependents", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "window_minutes": { + "name": "window_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 90 + }, + "last_run_date": { + "name": "last_run_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "port_forwards": { + "name": "port_forwards", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_port": { + "name": "external_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "destination": { + "name": "destination", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "internal_port": { + "name": "internal_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "port_forwards_server_id_servers_id_fk": { + "name": "port_forwards_server_id_servers_id_fk", + "tableFrom": "port_forwards", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_success_at": { + "name": "last_success_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "min_severity": { + "name": "min_severity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "categories": { + "name": "categories", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "renewals": { + "name": "renewals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "from_date": { + "name": "from_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_date": { + "name": "to_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "renewals_at_idx": { + "name": "renewals_at_idx", + "columns": [ + "at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "restore_tests": { + "name": "restore_tests", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "subject_key": { + "name": "subject_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tested_at": { + "name": "tested_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tested_by": { + "name": "tested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "restore_tests_subject_idx": { + "name": "restore_tests_subject_idx", + "columns": [ + "subject_key", + "tested_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runbooks": { + "name": "runbooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "runbooks_target_idx": { + "name": "runbooks_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "scheduled_tasks": { + "name": "scheduled_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schedule_expression": { + "name": "schedule_expression", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_metadata": { + "name": "raw_metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_stale": { + "name": "is_stale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "scheduled_tasks_server_id_servers_id_fk": { + "name": "scheduled_tasks_server_id_servers_id_fk", + "tableFrom": "scheduled_tasks", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "secrets": { + "name": "secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'generic'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiry_date": { + "name": "expiry_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 30 + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_host": { + "name": "check_host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_port": { + "name": "check_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_links": { + "name": "server_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "server_links_server_id_servers_id_fk": { + "name": "server_links_server_id_servers_id_fk", + "tableFrom": "server_links", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_metrics": { + "name": "server_metrics", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "server_metrics_lookup_idx": { + "name": "server_metrics_lookup_idx", + "columns": [ + "server_id", + "metric", + "recorded_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "server_metrics_server_id_servers_id_fk": { + "name": "server_metrics_server_id_servers_id_fk", + "tableFrom": "server_metrics", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_ports": { + "name": "server_ports", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "open": { + "name": "open", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "last_seen_open_at": { + "name": "last_seen_open_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "server_ports_unique": { + "name": "server_ports_unique", + "columns": [ + "server_id", + "port", + "protocol" + ], + "isUnique": true + } + }, + "foreignKeys": { + "server_ports_server_id_servers_id_fk": { + "name": "server_ports_server_id_servers_id_fk", + "tableFrom": "server_ports", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "servers": { + "name": "servers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hostname": { + "name": "hostname", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_type": { + "name": "os_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'linux'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "api_token_hash": { + "name": "api_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_token_prefix": { + "name": "api_token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ip_addresses": { + "name": "ip_addresses", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_model": { + "name": "cpu_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_cores": { + "name": "cpu_cores", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_load_percent": { + "name": "cpu_load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_total_bytes": { + "name": "mem_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_used_bytes": { + "name": "mem_used_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disks": { + "name": "disks", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "listening_ports": { + "name": "listening_ports", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_port_scan": { + "name": "last_port_scan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_integration_id": { + "name": "proxmox_integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_node": { + "name": "proxmox_node", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_guest_type": { + "name": "proxmox_guest_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_vmid": { + "name": "proxmox_vmid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hide_proxmox_link": { + "name": "hide_proxmox_link", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "parent_server_id": { + "name": "parent_server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "no_parent": { + "name": "no_parent", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "pending_updates": { + "name": "pending_updates", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_pending_since": { + "name": "updates_pending_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_health": { + "name": "host_health", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_diagnostics": { + "name": "agent_diagnostics", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "port_baseline": { + "name": "port_baseline", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_manufacturer": { + "name": "hw_manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_model": { + "name": "hw_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_serial": { + "name": "hw_serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thresholds": { + "name": "thresholds", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_version": { + "name": "agent_version", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "servers_proxmox_integration_id_integrations_id_fk": { + "name": "servers_proxmox_integration_id_integrations_id_fk", + "tableFrom": "servers", + "tableTo": "integrations", + "columnsFrom": [ + "proxmox_integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "share_links": { + "name": "share_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'summary'" + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'wall'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "share_links_token_hash_unique": { + "name": "share_links_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "status_items": { + "name": "status_items", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "link_id": { + "name": "link_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "monitor_id": { + "name": "monitor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "status_items_link_idx": { + "name": "status_items_link_idx", + "columns": [ + "link_id", + "position" + ], + "isUnique": false + } + }, + "foreignKeys": { + "status_items_link_id_share_links_id_fk": { + "name": "status_items_link_id_share_links_id_fk", + "tableFrom": "status_items", + "tableTo": "share_links", + "columnsFrom": [ + "link_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tag_definitions": { + "name": "tag_definitions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "tag_definitions_name_unique": { + "name": "tag_definitions_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "update_runs": { + "name": "update_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_id": { + "name": "template_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_name": { + "name": "template_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "host_limit": { + "name": "host_limit", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_status": { + "name": "task_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "window_id": { + "name": "window_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "window_created": { + "name": "window_created", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_by": { + "name": "started_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_ended_at": { + "name": "task_ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_reported_at": { + "name": "host_reported_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_before": { + "name": "updates_before", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_after": { + "name": "updates_after", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reboot_required": { + "name": "reboot_required", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "poll_errors": { + "name": "poll_errors", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "update_runs_server_idx": { + "name": "update_runs_server_idx", + "columns": [ + "server_id", + "started_at" + ], + "isUnique": false + }, + "update_runs_status_idx": { + "name": "update_runs_status_idx", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "update_runs_server_id_servers_id_fk": { + "name": "update_runs_server_id_servers_id_fk", + "tableFrom": "update_runs", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "oidc_sub": { + "name": "oidc_sub", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'viewer'" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_login_at": { + "name": "last_login_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "favorites": { + "name": "favorites", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_looked_at": { + "name": "last_looked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "groups": { + "name": "groups", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dashboard_layout": { + "name": "dashboard_layout", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "picture_url": { + "name": "picture_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_oidc_sub_unique": { + "name": "users_oidc_sub_unique", + "columns": [ + "oidc_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 96dc6af..99e28be 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -309,6 +309,13 @@ "when": 1792443011097, "tag": "0043_puzzling_prism", "breakpoints": true + }, + { + "idx": 44, + "version": "6", + "when": 1792447584218, + "tag": "0044_sparkling_scourge", + "breakpoints": true } ] } \ No newline at end of file diff --git a/server/src/app.ts b/server/src/app.ts index 69991a7..3cbda52 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -45,6 +45,7 @@ import { tagsRouter } from "./routes/tags.js"; import { portsRouter } from "./routes/ports.js"; import { alertsRouter } from "./routes/alerts.js"; import { mapRouter } from "./routes/map.js"; +import { networkRouter } from "./routes/network.js"; import { generatorRouter } from "./routes/generator.js"; import { alertTicketsRouter } from "./routes/alertTickets.js"; import { avatarsRouter } from "./routes/avatars.js"; @@ -161,6 +162,7 @@ export function createApp() { app.use("/api/alerts/bulk", alertsBulkRouter); app.use("/api/alerts", alertsRouter); app.use("/api/map", mapRouter); + app.use("/api/network", networkRouter); app.use("/api/generator", generatorRouter); app.use("/api/alert-tickets", alertTicketsRouter); diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 66f13b9..f1a5e05 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -76,7 +76,7 @@ export const notificationQueue = sqliteTable("notification_queue", { // ─── Maintenance windows — alerts about a target are silenced until endsAt ── -export const maintenanceTargetTypes = ["server", "integration", "dns_provider"] as const; +export const maintenanceTargetTypes = ["server", "integration", "dns_provider", "device"] as const; export type MaintenanceTargetType = (typeof maintenanceTargetTypes)[number]; export const maintenanceWindows = sqliteTable("maintenance_windows", { @@ -515,6 +515,7 @@ export const integrationTypes = [ "phpipam", "pbs", "osticket", + "unifi", ] as const; export type IntegrationType = (typeof integrationTypes)[number]; @@ -533,6 +534,59 @@ export const integrations = sqliteTable("integrations", { .default(sql`(current_timestamp)`), }); +// Network equipment read from a UniFi controller (switches, access points, gateways), refreshed every few minutes by services/unifiSync.ts. A device is a node +// in the dependency map ("device:"), like a server, and raises an "offline" alert when the controller has not seen it online for a while. +export const networkDevices = sqliteTable( + "network_devices", + { + id: integer("id").primaryKey({ autoIncrement: true }), + integrationId: integer("integration_id") + .notNull() + .references(() => integrations.id, { onDelete: "cascade" }), + externalId: text("external_id").notNull(), // the MAC address, lower case: the one thing both of UniFi's APIs give for every device + siteName: text("site_name"), + name: text("name").notNull(), + model: text("model"), + kind: text("kind").$type<"gateway" | "switch" | "access_point" | "other">().notNull().default("other"), + ip: text("ip"), + mac: text("mac"), + state: text("state").$type<"online" | "offline" | "updating" | "pending" | "other">().notNull().default("other"), + uptimeSeconds: integer("uptime_seconds"), + firmware: text("firmware"), + firmwareUpdatable: integer("firmware_updatable", { mode: "boolean" }).notNull().default(false), + uplinkExternalId: text("uplink_external_id"), // the MAC of the device this one is connected through, when the controller says + // When the controller first stopped seeing it online, kept until it is online again; the offline alert counts from here. + offlineSince: text("offline_since"), + lastOnlineAt: text("last_online_at"), + firstSeenAt: text("first_seen_at").notNull(), + updatedAt: text("updated_at").notNull(), + }, + (t) => [uniqueIndex("network_devices_unique").on(t.integrationId, t.externalId)], +); + +// The networks (VLANs) and Wi-Fi names (SSIDs) a UniFi controller has set up, kept beside the devices. Passphrases are never read. +export const networkSegments = sqliteTable( + "network_segments", + { + id: integer("id").primaryKey({ autoIncrement: true }), + integrationId: integer("integration_id") + .notNull() + .references(() => integrations.id, { onDelete: "cascade" }), + kind: text("kind").$type<"network" | "ssid">().notNull(), + externalId: text("external_id").notNull(), + siteName: text("site_name"), + name: text("name").notNull(), + enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), + vlanId: integer("vlan_id"), + subnet: text("subnet"), // a network's address range, e.g. 192.168.10.1/24 + purpose: text("purpose"), // a network: corporate, guest, … + security: text("security"), // an SSID: wpa2, wpa3, open, … + networkName: text("network_name"), // an SSID: the network its clients land on + updatedAt: text("updated_at").notNull(), + }, + (t) => [uniqueIndex("network_segments_unique").on(t.integrationId, t.kind, t.externalId)], +); + // A port on a server that's either been seen open (by a scan or the agent) or that someone wrote a note about. // Rows exist only while they carry information: an open port, or one with a label/comment ("reserved"). export const serverPorts = sqliteTable( diff --git a/server/src/index.ts b/server/src/index.ts index 56ff6f9..5a95a27 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -24,6 +24,7 @@ import { initEscalation } from "./services/escalation.js"; import { initEndpointMonitor } from "./services/endpointMonitor.js"; import { initPatchPlans } from "./services/patchPlans.js"; import { initFlapMonitor } from "./services/flapMonitor.js"; +import { initUnifiSync } from "./services/unifiSync.js"; import { initSelfBackupScheduler } from "./services/selfBackupScheduler.js"; import { initIncidentRecorder } from "./services/incidents.js"; import { getAlerts } from "./services/alerts.js"; @@ -67,6 +68,7 @@ initEscalation(); initEndpointMonitor(); initPatchPlans(); initFlapMonitor(); +initUnifiSync(); createApp().listen(env.port, () => { console.log(`homelab-manager listening on port ${env.port}`); diff --git a/server/src/integrations/fieldSchemas.ts b/server/src/integrations/fieldSchemas.ts index ff5ca34..995c067 100644 --- a/server/src/integrations/fieldSchemas.ts +++ b/server/src/integrations/fieldSchemas.ts @@ -72,6 +72,22 @@ export const INTEGRATION_FIELDS: Partial, ): string[] { const fields = INTEGRATION_FIELDS[type] ?? []; - return fields + const missing = fields .filter((f) => f.type !== "checkbox" && !f.optional) .filter((f) => merged[f.key] === undefined || merged[f.key] === "") .map((f) => f.key); + // UniFi takes an API key, or a username with its password: one way in is required, which no single field says. + if (type === "unifi") { + const has = (k: string) => typeof merged[k] === "string" && (merged[k] as string).trim() !== ""; + if (!has("apiKey") && !(has("username") && has("password"))) missing.push(has("username") ? "password" : "apiKey"); + } + return missing; } diff --git a/server/src/integrations/registry.ts b/server/src/integrations/registry.ts index 219711f..5d459ab 100644 --- a/server/src/integrations/registry.ts +++ b/server/src/integrations/registry.ts @@ -10,6 +10,7 @@ import { createUptimeKumaAdapter } from "./uptimekuma/adapter.js"; import { createPhpIpamAdapter } from "./phpipam/adapter.js"; import { createPbsAdapter } from "./pbs/adapter.js"; import { createOsTicketAdapter } from "./osticket/adapter.js"; +import { createUnifiAdapter } from "./unifi/adapter.js"; export interface PingableAdapter { ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>; @@ -44,6 +45,8 @@ export function createIntegrationAdapter(type: IntegrationType, config: Integrat return createPbsAdapter(config as any); case "osticket": return createOsTicketAdapter(config as any); + case "unifi": + return createUnifiAdapter(config as any); default: throw new Error(`Integration type "${type}" is not implemented yet`); } diff --git a/server/src/integrations/unifi/adapter.ts b/server/src/integrations/unifi/adapter.ts new file mode 100644 index 0000000..61b788c --- /dev/null +++ b/server/src/integrations/unifi/adapter.ts @@ -0,0 +1,556 @@ +/** + * 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 }); +} diff --git a/server/src/routes/dependencies.ts b/server/src/routes/dependencies.ts index 124d039..fb44a4d 100644 --- a/server/src/routes/dependencies.ts +++ b/server/src/routes/dependencies.ts @@ -2,7 +2,7 @@ import { Router } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; -import { dependencies, servers } from "../db/schema.js"; +import { dependencies, networkDevices, servers } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { invalidateAlertsCache } from "../services/alerts.js"; @@ -59,11 +59,12 @@ dependenciesRouter.get("/impact", asyncHandler(async (req, res) => { dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => { const graph = await loadGraph(); const written = new Set(graph.rows.map((r) => `${nodeKey(r.fromType, r.fromId)}>${nodeKey(r.toType, r.toId)}`)); - const edges: { from: string; to: string; kind: "written" | "runs-on" }[] = []; + const edges: { from: string; to: string; kind: "written" | "runs-on" | "uplink" }[] = []; const taking = new Set(); for (const [needing, needed] of graph.edges) { for (const n of needed) { - edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : "runs-on" }); + // A device connected through another is an uplink (the controller says so); a server's "runs on" is the other kind of link nobody wrote. + edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : needing.startsWith("device:") && n.startsWith("device:") ? "uplink" : "runs-on" }); taking.add(needing); taking.add(n); } @@ -73,6 +74,7 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => { const serverRows = await db.select({ id: servers.id, lastSeenAt: servers.lastSeenAt, thresholds: servers.thresholds }).from(servers); const serverById = new Map(serverRows.map((s) => [s.id, s])); const intById = new Map(graph.intRows.map((i) => [i.id, i])); + const deviceById = new Map((await db.select({ id: networkDevices.id, state: networkDevices.state }).from(networkDevices)).map((d) => [d.id, d])); const nodes = [...taking] .map((key) => { const [type, rawId] = key.split(":"); @@ -81,6 +83,9 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => { if (type === "server") { const s = serverById.get(id); if (s) status = serverStatus(s, healthChecks.serverOfflineMinutes, now); + } else if (type === "device") { + const d = deviceById.get(id); + if (d) status = d.state === "online" ? "ok" : d.state === "offline" ? "bad" : d.state === "updating" ? "warn" : "unknown"; } else { const i = intById.get(id); if (i?.enabled) { @@ -88,7 +93,7 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => { status = st === "failing" ? "bad" : st === "ok" ? "ok" : "unknown"; } } - return { key, type: type as "server" | "integration", id, name: graph.names.get(key) ?? key, status, href: type === "server" ? `/servers/${id}` : "/integrations" }; + return { key, type: type as "server" | "integration" | "device", id, name: graph.names.get(key) ?? key, status, href: type === "server" ? `/servers/${id}` : type === "device" ? "/network/devices" : "/integrations" }; }) .sort((a, b) => a.name.localeCompare(b.name)); res.json({ nodes, edges }); diff --git a/server/src/routes/integrations.ts b/server/src/routes/integrations.ts index 7370038..097b177 100644 --- a/server/src/routes/integrations.ts +++ b/server/src/routes/integrations.ts @@ -2,7 +2,7 @@ import { Router, type Request, type Response } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; -import { integrations, integrationCredentials, integrationTypes, servers } from "../db/schema.js"; +import { integrations, integrationCredentials, integrationTypes, servers, type IntegrationType } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { encryptSecret } from "../crypto.js"; @@ -25,6 +25,8 @@ import { createPbsAdapter } from "../integrations/pbs/adapter.js"; import { createOsTicketAdapter } from "../integrations/osticket/adapter.js"; import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js"; import { getSourceStatus } from "../services/integrationHealthMonitor.js"; +import { removeIntegrationData, syncUnifiIntegration } from "../services/unifiSync.js"; +import { invalidateAlertsCache } from "../services/alerts.js"; import { asyncHandler } from "../utils/asyncHandler.js"; import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js"; @@ -60,6 +62,13 @@ integrationsRouter.get("/", asyncHandler(async (_req, res) => { const configValueSchema = z.union([z.string(), z.boolean()]); +/** What to tell the person when a form was submitted without something it needs. */ +function missingMessage(type: IntegrationType, missing: string[]): string { + if (type === "unifi") return "UniFi needs an API key, or a username together with its password."; + const labels = (INTEGRATION_FIELDS[type] ?? []).filter((f) => missing.includes(f.key)).map((f) => f.label); + return `Fill in: ${labels.length > 0 ? labels.join(", ") : missing.join(", ")}.`; +} + const createIntegrationSchema = z.object({ type: z.enum(integrationTypes), name: z.string().min(1).max(200), @@ -79,7 +88,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) const missing = validateIntegrationConfig(type, config); if (missing.length > 0) { - return res.status(400).json({ error: "missing_fields", fields: missing }); + return res.status(400).json({ error: "missing_fields", fields: missing, message: missingMessage(type, missing) }); } const { secretFields, nonSecretFields } = splitIntegrationConfig(type, config); @@ -114,6 +123,9 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) detail: { type, name }, }); + // A new UniFi controller is read at once, so its equipment is there when the person opens the page (not waited for: a slow controller must not slow this). + if (type === "unifi") void syncUnifiIntegration(created.id).then(() => invalidateAlertsCache()); + res.status(201).json({ integration: { id: created.id, @@ -213,6 +225,8 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, }, }); + if (updated.type === "unifi" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUnifiIntegration(updated.id).then(() => invalidateAlertsCache()); + res.json({ integration: { id: updated.id, @@ -288,6 +302,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, .where(eq(servers.proxmoxIntegrationId, id)) .returning({ id: servers.id }); + if (existing.type === "unifi") await removeIntegrationData(id); await db.delete(integrations).where(eq(integrations.id, id)); if (existing.credentialId) { await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId)); diff --git a/server/src/routes/maintenance.ts b/server/src/routes/maintenance.ts index 8dfc393..1860946 100644 --- a/server/src/routes/maintenance.ts +++ b/server/src/routes/maintenance.ts @@ -2,7 +2,7 @@ import { Router } from "express"; import { and, eq, inArray } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; -import { dnsProviders, integrations, maintenanceAliases, maintenanceSchedules, maintenanceTargetTypes, maintenanceWindows, servers } from "../db/schema.js"; +import { dnsProviders, integrations, maintenanceAliases, maintenanceSchedules, maintenanceTargetTypes, maintenanceWindows, networkDevices, servers } from "../db/schema.js"; import { deleteSchedule, isValidTimeZone, materializeSchedules, occurrencesBetween, removeFutureWindows, targetsOf } from "../services/maintenanceSchedules.js"; import { hostOfAddress } from "../services/kumaTargets.js"; import { invalidateAlertsCache } from "../services/alerts.js"; @@ -37,10 +37,11 @@ maintenanceRouter.get("/", asyncHandler(async (_req, res) => { const upcoming = await describe(await listUpcomingWindows()); upcoming.sort((a, b) => a.startedAt.localeCompare(b.startedAt)); - const [serverRows, integrationRows, providerRows] = await Promise.all([ + const [serverRows, integrationRows, providerRows, deviceRows] = await Promise.all([ db.select({ id: servers.id, name: servers.name }).from(servers).orderBy(servers.name), db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).orderBy(integrations.name), db.select({ id: dnsProviders.id, name: dnsProviders.name, providerType: dnsProviders.providerType }).from(dnsProviders).orderBy(dnsProviders.name), + db.select({ id: networkDevices.id, name: networkDevices.name, kind: networkDevices.kind }).from(networkDevices).orderBy(networkDevices.name), ]); const aliases = []; for (const a of await db.select().from(maintenanceAliases).orderBy(maintenanceAliases.address)) { @@ -48,7 +49,7 @@ maintenanceRouter.get("/", asyncHandler(async (_req, res) => { if (!target) continue; // target was deleted — the alias has nothing left to point at aliases.push({ id: a.id, address: a.address, targetType: a.targetType, targetId: a.targetId, targetName: target.name, targetKind: target.kind }); } - res.json({ windows, upcoming, aliases, targets: { servers: serverRows, integrations: integrationRows, dnsProviders: providerRows } }); + res.json({ windows, upcoming, aliases, targets: { servers: serverRows, integrations: integrationRows, dnsProviders: providerRows, devices: deviceRows } }); })); const startSchema = z.object({ @@ -77,8 +78,8 @@ maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, re } // What depends on it goes down with it, so it is silenced for the same time (and says why). - const alsoSilenced: { type: "server" | "integration"; id: number; name: string }[] = []; - if (withDependents && (targetType === "server" || targetType === "integration")) { + const alsoSilenced: { type: "server" | "integration" | "device"; id: number; name: string }[] = []; + if (withDependents && (targetType === "server" || targetType === "integration" || targetType === "device")) { const impact = await impactOf(targetType, targetId); for (const d of impact?.dependents ?? []) { const also = await startOrExtendWindow(d.type, d.id, minutes, `Depends on ${result.target.name}${reason ? ` — ${reason}` : ""}`.slice(0, 200), createdBy); @@ -226,7 +227,7 @@ maintenanceRouter.delete("/aliases/:id", requireRole("operator"), asyncHandler(a })); const bulkSchema = z.object({ - scope: z.enum(["everything", "servers", "integrations", "dns_providers"]), + scope: z.enum(["everything", "servers", "integrations", "dns_providers", "devices"]), minutes: z.number().int().min(5).max(7 * 24 * 60), reason: z.string().max(200).optional(), }); @@ -243,13 +244,16 @@ maintenanceRouter.post("/bulk", requireRole("operator"), asyncHandler(async (req } const { scope, minutes, reason } = parsed.data; - const targets: { type: "server" | "integration" | "dns_provider"; id: number }[] = []; + const targets: { type: "server" | "integration" | "dns_provider" | "device"; id: number }[] = []; if (scope === "everything" || scope === "servers") { for (const s of await db.select({ id: servers.id }).from(servers)) targets.push({ type: "server", id: s.id }); } if (scope === "everything" || scope === "integrations") { for (const i of await db.select({ id: integrations.id }).from(integrations).where(eq(integrations.enabled, true))) targets.push({ type: "integration", id: i.id }); } + if (scope === "everything" || scope === "devices") { + for (const d of await db.select({ id: networkDevices.id }).from(networkDevices)) targets.push({ type: "device", id: d.id }); + } if (scope === "everything" || scope === "dns_providers") { for (const p of await db.select({ id: dnsProviders.id }).from(dnsProviders).where(eq(dnsProviders.enabled, true))) targets.push({ type: "dns_provider", id: p.id }); } diff --git a/server/src/routes/network.ts b/server/src/routes/network.ts new file mode 100644 index 0000000..a281f1a --- /dev/null +++ b/server/src/routes/network.ts @@ -0,0 +1,84 @@ +import { Router } from "express"; +import { eq } from "drizzle-orm"; +import { z } from "zod"; +import { db } from "../db/client.js"; +import { integrations, networkDevices, networkSegments } from "../db/schema.js"; +import { requireAuth, requireRole } from "../auth/middleware.js"; +import { invalidateAlertsCache } from "../services/alerts.js"; +import { dependentsOf, loadGraph, needsOfNode, nodeKey } from "../services/dependencies.js"; +import { activeSubjects } from "../services/maintenance.js"; +import { syncAllUnifi, syncStatuses, syncUnifiIntegration } from "../services/unifiSync.js"; +import { asyncHandler } from "../utils/asyncHandler.js"; + +export const networkRouter = Router(); + +networkRouter.use(requireAuth); + +/** + * The network equipment read from UniFi controllers: devices with their state, address, uptime and what they are connected through, the networks and the Wi-Fi + * names. Everyone signed in can see it (it is the same picture the dependency map and the alerts draw on); only starting a fresh read needs more. + */ +networkRouter.get("/", asyncHandler(async (_req, res) => { + const [intRows, devices, segments, statuses, graph, silenced] = await Promise.all([ + db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "unifi")), + db.select().from(networkDevices), + db.select().from(networkSegments), + syncStatuses(), + loadGraph(), + activeSubjects(), + ]); + const intName = new Map(intRows.map((i) => [i.id, i.name])); + const byExternal = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d])); + res.json({ + integrations: intRows.map((i) => ({ id: i.id, name: i.name, enabled: i.enabled, status: statuses[i.id] ?? null })), + devices: devices + .map((d) => { + const key = nodeKey("device", d.id); + const uplink = d.uplinkExternalId ? byExternal.get(`${d.integrationId}:${d.uplinkExternalId}`) : undefined; + return { + id: d.id, + integrationId: d.integrationId, + integrationName: intName.get(d.integrationId) ?? "UniFi", + siteName: d.siteName, + name: d.name, + model: d.model, + kind: d.kind, + ip: d.ip, + mac: d.mac, + state: d.state, + uptimeSeconds: d.uptimeSeconds, + firmware: d.firmware, + firmwareUpdatable: d.firmwareUpdatable, + uplink: uplink ? { id: uplink.id, name: uplink.name } : null, + offlineSince: d.offlineSince, + lastOnlineAt: d.lastOnlineAt, + updatedAt: d.updatedAt, + // How many things depend on it (directly or through others), and how many it needs: what the dependency map says about it. + dependents: dependentsOf(graph.edges, key).length, + needs: needsOfNode(graph.edges, key).length, + inMaintenance: silenced.has(key), + }; + }) + .sort((a, b) => a.name.localeCompare(b.name)), + networks: segments.filter((s) => s.kind === "network").map(({ kind: _k, ...s }) => ({ ...s, integrationName: intName.get(s.integrationId) ?? "UniFi" })).sort((a, b) => (a.vlanId ?? 0) - (b.vlanId ?? 0) || a.name.localeCompare(b.name)), + ssids: segments.filter((s) => s.kind === "ssid").map(({ kind: _k, ...s }) => ({ ...s, integrationName: intName.get(s.integrationId) ?? "UniFi" })).sort((a, b) => a.name.localeCompare(b.name)), + }); +})); + +const syncSchema = z.object({ integrationId: z.number().int().positive().optional() }); + +// Reads the controller(s) now instead of waiting for the next pass. +networkRouter.post("/sync", requireRole("operator"), asyncHandler(async (req, res) => { + const parsed = syncSchema.safeParse(req.body ?? {}); + if (!parsed.success) return res.status(400).json({ error: "invalid_body" }); + if (parsed.data.integrationId !== undefined) { + const [row] = await db.select({ id: integrations.id, type: integrations.type }).from(integrations).where(eq(integrations.id, parsed.data.integrationId)).limit(1); + if (!row || row.type !== "unifi") return res.status(404).json({ error: "not_found", message: "That isn't a UniFi integration." }); + const status = await syncUnifiIntegration(row.id); + invalidateAlertsCache(); + return res.json({ statuses: { [row.id]: status } }); + } + const statuses = await syncAllUnifi(); + invalidateAlertsCache(); + res.json({ statuses }); +})); diff --git a/server/src/routes/runbooks.ts b/server/src/routes/runbooks.ts index a0b56a4..b310928 100644 --- a/server/src/routes/runbooks.ts +++ b/server/src/routes/runbooks.ts @@ -2,7 +2,7 @@ import { Router } from "express"; import { and, eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; -import { dnsProviders, integrations, maintenanceTargetTypes, runbooks, servers } from "../db/schema.js"; +import { dnsProviders, integrations, maintenanceTargetTypes, networkDevices, runbooks, servers } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { describeTarget } from "../services/maintenance.js"; @@ -39,16 +39,18 @@ runbooksRouter.get("/", asyncHandler(async (req, res) => { // What there is, everywhere, by title only — so a page can show a "runbook" button exactly where one exists, without fetching the texts. // Notes for something that has since been removed are left out. runbooksRouter.get("/summary", asyncHandler(async (_req, res) => { - const [rows, serverIds, integrationIds, providerIds] = await Promise.all([ + const [rows, serverIds, integrationIds, providerIds, deviceIds] = await Promise.all([ db.select({ id: runbooks.id, targetType: runbooks.targetType, targetId: runbooks.targetId, category: runbooks.category, title: runbooks.title }).from(runbooks), db.select({ id: servers.id }).from(servers), db.select({ id: integrations.id }).from(integrations), db.select({ id: dnsProviders.id }).from(dnsProviders), + db.select({ id: networkDevices.id }).from(networkDevices), ]); const exists = { server: new Set(serverIds.map((r) => r.id)), integration: new Set(integrationIds.map((r) => r.id)), dns_provider: new Set(providerIds.map((r) => r.id)), + device: new Set(deviceIds.map((r) => r.id)), }; res.json({ runbooks: rows.filter((r) => exists[r.targetType].has(r.targetId)) }); })); diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts index 8299ffe..ee5af65 100644 --- a/server/src/routes/settings.ts +++ b/server/src/routes/settings.ts @@ -144,7 +144,7 @@ const updateSchema = z.object({ .partial() .optional(), healthChecks: z - .object({ serverOfflineMinutes: z.number().int().min(15).max(10080), diskUsagePercent: z.number().int().min(50).max(99), domainWarnDays: z.number().int().min(1).max(365), diskForecastDays: z.number().int().min(0).max(90), backupStaleHours: z.number().int().min(0).max(2160), restoreTestDays: z.number().int().min(0).max(730), newPortAlerts: z.boolean(), flapRaises: z.number().int().min(0).max(20) }) + .object({ serverOfflineMinutes: z.number().int().min(15).max(10080), diskUsagePercent: z.number().int().min(50).max(99), domainWarnDays: z.number().int().min(1).max(365), diskForecastDays: z.number().int().min(0).max(90), backupStaleHours: z.number().int().min(0).max(2160), restoreTestDays: z.number().int().min(0).max(730), newPortAlerts: z.boolean(), flapRaises: z.number().int().min(0).max(20), deviceOfflineMinutes: z.number().int().min(5).max(1440) }) .partial() .optional(), quietHours: z diff --git a/server/src/services/alertTypes.ts b/server/src/services/alertTypes.ts index ce6da2f..b7c38b8 100644 --- a/server/src/services/alertTypes.ts +++ b/server/src/services/alertTypes.ts @@ -26,7 +26,7 @@ export interface Alert { /** Raised and cleared over and over: its raised and cleared messages are being held back (services/flapGuard.ts). */ flapping?: boolean; /** What a maintenance window would have to be on to silence it, when there is such a thing — which is what "Silence" acts on. */ - target: { type: "server" | "integration" | "dns_provider"; id: number; name: string } | null; + target: { type: "server" | "integration" | "dns_provider" | "device"; id: number; name: string } | null; } /** One integration that couldn't be read while collecting — so the page never mistakes "couldn't check" for "all clear". */ diff --git a/server/src/services/alerts.ts b/server/src/services/alerts.ts index 136e000..f17e1e8 100644 --- a/server/src/services/alerts.ts +++ b/server/src/services/alerts.ts @@ -11,7 +11,7 @@ */ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; -import { endpointChecks, heartbeats, integrations, secrets, servers } from "../db/schema.js"; +import { endpointChecks, heartbeats, integrations, networkDevices, secrets, servers } from "../db/schema.js"; import { disksFillingSoon, getServerMetrics } from "./serverMetrics.js"; import { diskLimit, effectiveThresholds, parseThresholds } from "./serverThresholds.js"; import { getBackupCoverage, staleBackups } from "./backupCoverage.js"; @@ -64,6 +64,7 @@ const SOURCES: Record = { pbs: { label: "Proxmox Backup", link: "/pbs" }, uptimekuma: { label: "Uptime Kuma", link: "/uptime-kuma" }, osticket: { label: "osTicket", link: "/osticket" }, + unifi: { label: "UniFi", link: "/network/devices" }, secrets: { label: "Secrets", link: "/secrets" }, domains: { label: "Domains", link: "/dns?view=domains" }, endpoint: { label: "Endpoint", link: "/endpoints" }, @@ -80,6 +81,8 @@ const SEVERITY_ORDER: Record = { critical: 0, warning: 1, /** Which kind of source, and which one, a health/automation condition key belongs to. */ function originOfConditionKey(key: string): { type: string; id: number | null; category: AlertCategory } { + const device = /^offline:device:(\d+)$/.exec(key); + if (device) return { type: "unifi", id: Number(device[1]), category: "offline" }; let m = /^(?:offline|disk|failed-units|smart|zfs|new-port):server:(\d+)/.exec(key); if (m) return { type: "server", id: Number(m[1]), category: key.startsWith("offline") ? "offline" : key.startsWith("failed-units") ? "services" : key.startsWith("new-port") ? "monitoring" : "disk" }; m = /^disk:proxmox:(\d+):/.exec(key); @@ -110,16 +113,17 @@ export async function collectAlerts(): Promise { const intRows = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations); const intById = new Map(intRows.map((r) => [r.id, r])); const serverNames = new Map((await db.select({ id: servers.id, name: servers.name }).from(servers)).map((r) => [r.id, r.name])); + const deviceNames = new Map((await db.select({ id: networkDevices.id, name: networkDevices.name }).from(networkDevices)).map((r) => [r.id, r.name])); /** The thing a maintenance window would go on to silence an alert about `subject` ("server:3", "integration:1"). */ - const targetOf = (type: "server" | "integration" | "dns_provider", id: number): Alert["target"] => ({ + const targetOf = (type: "server" | "integration" | "dns_provider" | "device", id: number): Alert["target"] => ({ type, id, - name: (type === "server" ? serverNames.get(id) : type === "integration" ? intById.get(id)?.name : undefined) ?? `${type} #${id}`, + name: (type === "server" ? serverNames.get(id) : type === "device" ? deviceNames.get(id) : type === "integration" ? intById.get(id)?.name : undefined) ?? `${type} #${id}`, }); const targetOfSubject = (subject: string | null): Alert["target"] => { - const m = /^(server|integration|dns_provider):(\d+)$/.exec(subject ?? ""); - return m ? targetOf(m[1] as "server" | "integration" | "dns_provider", Number(m[2])) : null; + const m = /^(server|integration|dns_provider|device):(\d+)$/.exec(subject ?? ""); + return m ? targetOf(m[1] as "server" | "integration" | "dns_provider" | "device", Number(m[2])) : null; }; const integrationTarget = (id: number): Alert["target"] => targetOf("integration", id); /** Integration-down alerts are per kind of service; a window on any integration of that kind silences them, so offer the first. */ @@ -167,6 +171,9 @@ export async function collectAlerts(): Promise { // The servers found to be offline, for the integration failures that one may explain: the server check fills it in (and it is empty if that check fails). let offlineKnown!: (ids: Set) => void; const offlineServers = new Promise>((resolve) => (offlineKnown = resolve)); + // The same for network devices, which can explain a service that has stopped answering. + let devicesKnown!: (ids: Set) => void; + const offlineDeviceIds = new Promise>((resolve) => (devicesKnown = resolve)); await Promise.all([ check("Server and storage health", async () => { @@ -182,38 +189,44 @@ export async function collectAlerts(): Promise { const conditions = evaluateHealth(snapshot, healthChecks, now, { skipServers: grace > 0 }); // A server that is down because the one it runs on is down is folded under that one. const offlineIds = new Set(); + const offlineDevices = new Set(); for (const c of conditions) { - const m = /^offline:server:(\d+)$/.exec(c.key); - if (m) offlineIds.add(Number(m[1])); + const m = /^offline:(server|device):(\d+)$/.exec(c.key); + if (m) (m[1] === "server" ? offlineIds : offlineDevices).add(Number(m[2])); } // (Or because of a service it needs that is failing, or a server it needs that needs one.) offlineKnown(offlineIds); - const cover = await dependencyCover(offlineIds, getFailingSources().map((f) => f.source)); + devicesKnown(offlineDevices); + const cover = await dependencyCover(offlineIds, getFailingSources().map((f) => f.source), offlineDevices); for (const c of conditions) { const origin = originOfConditionKey(c.key); const subject = subjectOfConditionKey(c.key); - const offlineId = /^offline:server:(\d+)$/.exec(c.key)?.[1]; - const parentOf = offlineId ? cover.cause.get(`server:${offlineId}`) : undefined; + const offlineMatch = /^offline:(server|device):(\d+)$/.exec(c.key); + const offlineNode = offlineMatch ? `${offlineMatch[1]}:${offlineMatch[2]}` : undefined; + const parentOf = offlineNode ? cover.cause.get(offlineNode) : undefined; push({ causedBy: parentOf !== undefined ? { name: cover.graph.names.get(parentOf) ?? parentOf, alertId: alertIdOfNode(parentOf, cover.graph) ?? undefined } : undefined, - affects: offlineId ? cover.taken.get(`server:${offlineId}`)?.sort((a, b) => a.localeCompare(b)) : undefined, + affects: offlineNode ? cover.taken.get(offlineNode)?.sort((a, b) => a.localeCompare(b)) : undefined, category: origin.category, severity: c.severity ?? "warning", type: origin.type, message: c.message, key: c.key, - link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}` : undefined, + link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}` : origin.type === "unifi" ? "/network/devices" : undefined, silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject), }); } // Integrations the check couldn't read this time. (A whole-integration entry covers its nodes, so skip those.) for (const h of held) { - const m = /^(proxmox|synology):(\d+)(?::(.+))?$/.exec(h); + const m = /^(proxmox|synology|unifi):(\d+)(?::(.+))?$/.exec(h); if (!m || (m[3] && held.has(`${m[1]}:${m[2]}`))) continue; const row = intById.get(Number(m[2])); cannotCheck(`${SOURCES[m[1]].label} “${row?.name ?? `#${m[2]}`}”${m[3] ? ` (node ${m[3]})` : ""}`, "couldn't be read — see the Diagnostic Log", "Server and storage health"); } - }).finally(() => offlineKnown(new Set())), + }).finally(() => { + offlineKnown(new Set()); + devicesKnown(new Set()); + }), check("Automation runs", async () => { const { items, held } = await collectAutomation(); @@ -506,7 +519,7 @@ export async function collectAlerts(): Promise { const { notifications } = await getSettings(); const failing = getFailingSources(); // A failure explained by something it needs that is down is folded under that, like a guest under its host. - const cover = failing.length > 0 ? await dependencyCover(await offlineServers, failing.map((f) => f.source)).catch(() => null) : null; + const cover = failing.length > 0 ? await dependencyCover(await offlineServers, failing.map((f) => f.source), await offlineDeviceIds).catch(() => null) : null; for (const f of failing) { const cause = cover ? integrationTypeCause(f.source, cover) : null; const affects = cover ? takenByType(f.source, cover) : []; diff --git a/server/src/services/bulkActions.ts b/server/src/services/bulkActions.ts index efb10a1..782287e 100644 --- a/server/src/services/bulkActions.ts +++ b/server/src/services/bulkActions.ts @@ -41,7 +41,7 @@ export interface SilenceUndo { restored: { id: number; endsAt: string; reason: string | null }[]; } -type Target = { type: "server" | "integration" | "dns_provider"; id: number }; +type Target = { type: "server" | "integration" | "dns_provider" | "device"; id: number }; /** Puts each target under maintenance (and, if asked, what depends on a server). Targets that are already under it have their window extended. */ export async function silenceTargets(targets: Target[], minutes: number, reason: string | null, createdBy: string, withDependents: boolean, now: Date = new Date()): Promise<{ silenced: { type: string; id: number; name: string }[]; skipped: Skipped[]; undo: SilenceUndo | null }> { diff --git a/server/src/services/dependencies.ts b/server/src/services/dependencies.ts index 099dc91..6196551 100644 --- a/server/src/services/dependencies.ts +++ b/server/src/services/dependencies.ts @@ -3,14 +3,15 @@ * server that needs a service (a guest that only exists while Proxmox answers). When the thing depended on is down, the things that need it * are down too — and only the one that matters is worth an alert, so the rest are folded under it: shown, not announced. * - * The graph is the "runs on" links of servers (set by hand or worked out from Proxmox, see serverParents.ts) plus the dependencies written - * here. Servers and integrations are the things that can be down and be needed. (DNS providers raise no alerts of their own, so there is + * The graph is the "runs on" links of servers (set by hand or worked out from Proxmox, see serverParents.ts), the uplinks of network devices (which + * device each is connected through, as a UniFi controller says), plus the dependencies written here. Servers, network devices and integrations are the things + * that can be down and be needed. (DNS providers raise no alerts of their own, so there is * nothing to fold.) An integration is judged per kind of service, as its health is: it is folded only if every enabled instance of that * kind is explained. */ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; -import { dependencies, integrations, servers } from "../db/schema.js"; +import { dependencies, integrations, networkDevices, servers } from "../db/schema.js"; import { getInternalFlag } from "./settingsStore.js"; import { listActiveWindows } from "./maintenance.js"; import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js"; @@ -18,7 +19,7 @@ import { loadParentRows, resolveParents, type ParentLink } from "./serverParents /** Where the health monitor keeps the problems it is announcing; read here so a service's alert can tell a server it needs is down. */ export const HEALTH_STATE_FLAG = "healthActiveConditions"; -export const nodeTypes = ["server", "integration"] as const; +export const nodeTypes = ["server", "integration", "device"] as const; export type NodeType = (typeof nodeTypes)[number]; export const nodeKey = (type: NodeType, id: number) => `${type}:${id}`; @@ -128,26 +129,43 @@ export interface Graph { } export async function loadGraph(): Promise { - const [serverRows, intRows, depRows, parentRows] = await Promise.all([ + const [serverRows, intRows, depRows, parentRows, deviceRows] = await Promise.all([ db.select({ id: servers.id, name: servers.name }).from(servers), db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations), db.select().from(dependencies), loadParentRows(), + db.select({ id: networkDevices.id, name: networkDevices.name, integrationId: networkDevices.integrationId, externalId: networkDevices.externalId, uplinkExternalId: networkDevices.uplinkExternalId }).from(networkDevices), ]); const names = new Map(); for (const s of serverRows) names.set(nodeKey("server", s.id), s.name); for (const i of intRows) names.set(nodeKey("integration", i.id), i.name); + for (const d of deviceRows) names.set(nodeKey("device", d.id), d.name); const rows = depRows.map((r) => ({ id: r.id, fromType: r.fromType as NodeType, fromId: r.fromId, toType: r.toType as NodeType, toId: r.toId, createdAt: r.createdAt })); const instances = new Map(); for (const i of intRows) if (i.enabled) instances.set(i.type, [...(instances.get(i.type) ?? []), i.id]); - return { edges: buildEdges(resolveParents(parentRows), rows, (k) => names.has(k)), names, rows, instances, intRows }; + // A device needs the one it is connected through: the controller says so, and nobody has to write it. + const uplinks = uplinkEdges(deviceRows); + return { edges: buildEdges(resolveParents(parentRows), [...rows, ...uplinks], (k) => names.has(k)), names, rows, instances, intRows }; +} + +/** The edges from each device to the device it is connected through, from what the controller reports; a device whose uplink is not (or no longer) known has none. */ +export function uplinkEdges(devices: { id: number; integrationId: number; externalId: string; uplinkExternalId: string | null }[]): DependencyEdge[] { + const idOf = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d.id])); + const out: DependencyEdge[] = []; + for (const d of devices) { + if (!d.uplinkExternalId) continue; + const to = idOf.get(`${d.integrationId}:${d.uplinkExternalId}`); + if (to !== undefined && to !== d.id) out.push({ fromType: "device", fromId: d.id, toType: "device", toId: to }); + } + return out; } /** The id of the alert about a node being down, when it has one (a server's "offline", a kind of service's "failing"). */ export function alertIdOfNode(key: string, graph: Graph): string | null { - const m = /^(server|integration):(\d+)$/.exec(key); + const m = /^(server|integration|device):(\d+)$/.exec(key); if (!m) return null; if (m[1] === "server") return `offline:offline:server:${m[2]}`; + if (m[1] === "device") return `offline:offline:device:${m[2]}`; const row = graph.intRows.find((r) => r.id === Number(m[2])); return row ? `integration:failing:${row.type}` : null; } @@ -190,11 +208,12 @@ export interface Cover { graph: Graph; } -/** Works out what is down because of what, given the servers that are offline and the kinds of integration that are failing. */ -export async function dependencyCover(offlineServerIds: Iterable, failingTypes: Iterable): Promise { +/** Works out what is down because of what, given the servers and network devices that are offline and the kinds of integration that are failing. */ +export async function dependencyCover(offlineServerIds: Iterable, failingTypes: Iterable, offlineDeviceIds: Iterable = []): Promise { const graph = await loadGraph(); const down = new Set(); for (const id of offlineServerIds) down.add(nodeKey("server", id)); + for (const id of offlineDeviceIds) down.add(nodeKey("device", id)); const failing = new Set(failingTypes); for (const [type, ids] of graph.instances) if (failing.has(type)) for (const id of ids) down.add(nodeKey("integration", id)); const cause = coveredNodes(down, graph.edges); @@ -223,15 +242,15 @@ export function takenByType(type: string, cover: Cover): string[] { return out; } -/** The servers the health monitor is announcing as offline (or holding back as explained), from what it last stored. */ -export async function offlineServerIdsFromState(): Promise { +/** The servers or network devices the health monitor is announcing as offline (or holding back as explained), from what it last stored. */ +async function offlineIdsFromState(kind: "server" | "device"): Promise { try { const raw = await getInternalFlag(HEALTH_STATE_FLAG); if (!raw) return []; const ids: number[] = []; for (const key of Object.keys(JSON.parse(raw) as Record)) { - const m = /^offline:server:(\d+)$/.exec(key); - if (m) ids.push(Number(m[1])); + const m = /^offline:(server|device):(\d+)$/.exec(key); + if (m && m[1] === kind) ids.push(Number(m[2])); } return ids; } catch { @@ -239,13 +258,16 @@ export async function offlineServerIdsFromState(): Promise { } } +export const offlineServerIdsFromState = () => offlineIdsFromState("server"); +export const offlineDeviceIdsFromState = () => offlineIdsFromState("device"); + /** * Whether a kind of integration that has started failing is failing because of something it needs that is down — a server the health * monitor says is offline, or another service that is failing. Never throws: a problem here must not swallow a real outage. */ export async function integrationCausedBy(type: string, failingTypes: string[]): Promise<{ name: string } | null> { try { - const cover = await dependencyCover(await offlineServerIdsFromState(), failingTypes); + const cover = await dependencyCover(await offlineServerIdsFromState(), failingTypes, await offlineDeviceIdsFromState()); return integrationTypeCause(type, cover); } catch (err) { console.error("[dependencies] couldn't work out whether a failure is explained:", err); @@ -254,6 +276,7 @@ export async function integrationCausedBy(type: string, failingTypes: string[]): } export async function nodeExists(type: NodeType, id: number): Promise { + if (type === "device") return (await db.select({ id: networkDevices.id }).from(networkDevices).where(eq(networkDevices.id, id)).limit(1)).length > 0; if (type === "server") return (await db.select({ id: servers.id }).from(servers).where(eq(servers.id, id)).limit(1)).length > 0; return (await db.select({ id: integrations.id }).from(integrations).where(eq(integrations.id, id)).limit(1)).length > 0; } diff --git a/server/src/services/healthMonitor.ts b/server/src/services/healthMonitor.ts index aea54a7..20c9aa6 100644 --- a/server/src/services/healthMonitor.ts +++ b/server/src/services/healthMonitor.ts @@ -1,12 +1,13 @@ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; -import { integrations, serverPorts, servers } from "../db/schema.js"; +import { integrations, networkDevices, serverPorts, servers } from "../db/schema.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createProxmoxAdapter, type ProxmoxNodeStats } from "../integrations/proxmox/adapter.js"; import { createSynologyAdapter, type SynologyStorageInfo } from "../integrations/synology/adapter.js"; import { notifyHealthIssues, notifyHealthRecovered } from "./notify.js"; import { recordAudit } from "./audit.js"; import { getInternalFlag, getSettings, setInternalFlag } from "./settingsStore.js"; +import { isFresh, syncStatuses } from "./unifiSync.js"; import { activeSubjects, subjectOfConditionKey } from "./maintenance.js"; import { dependencyCover, HEALTH_STATE_FLAG } from "./dependencies.js"; import { getFailingSources } from "./integrationHealthMonitor.js"; @@ -54,14 +55,23 @@ export interface SynologySnapshot { integrationName: string; storage: SynologyStorageInfo; } +/** The network equipment of one UniFi controller, as last read; only offered when that reading is recent enough to be believed. */ +export interface UnifiSnapshot { + integrationId: number; + integrationName: string; + devices: { id: number; name: string; kind: string; model: string | null; state: string; offlineSince: string | null }[]; +} export interface HealthSnapshot { servers: ServerSnapshot[]; proxmox: ProxmoxSnapshot[]; synology: SynologySnapshot[]; + unifi?: UnifiSnapshot[]; } export interface Thresholds { serverOfflineMinutes: number; diskUsagePercent: number; + /** Minutes a network device may be offline before it is raised (10 if left out). */ + deviceOfflineMinutes?: number; } // ─── Formatting helpers ───────────────────────────────────────────────────── @@ -145,6 +155,21 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds, } } + for (const u of snapshot.unifi ?? []) { + const limitMs = (thresholds.deviceOfflineMinutes ?? 10) * 60_000; + for (const d of u.devices) { + if (d.state !== "offline" || !d.offlineSince) continue; + const age = now - parseTimestamp(d.offlineSince); + if (!Number.isFinite(age) || age <= limitMs) continue; + out.push({ + key: `offline:device:${d.id}`, + source: `unifi:${u.integrationId}`, + message: `${d.name} (${d.kind.replace("_", " ")}${d.model ? `, ${d.model}` : ""}) has been offline for ${formatDuration(age)}`, + severity: "critical", + }); + } + } + for (const px of snapshot.proxmox) { const seenShared = new Set(); for (const node of px.nodes) { @@ -331,6 +356,24 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel .from(integrations) .where(eq(integrations.enabled, true)); + // UniFi controllers are read by their own pass every few minutes; what is judged here is what that pass stored, and only while it is recent. + const unifiRows = rows.filter((r) => r.type === "unifi"); + if (unifiRows.length > 0) { + const statuses = await syncStatuses(); + const nowMs = Date.now(); + for (const row of unifiRows) { + if (!isFresh(statuses[row.id], nowMs)) { + held.add(`unifi:${row.id}`); + continue; + } + const devices = await db + .select({ id: networkDevices.id, name: networkDevices.name, kind: networkDevices.kind, model: networkDevices.model, state: networkDevices.state, offlineSince: networkDevices.offlineSince }) + .from(networkDevices) + .where(eq(networkDevices.integrationId, row.id)); + (snapshot.unifi ??= []).push({ integrationId: row.id, integrationName: row.name, devices }); + } + } + for (const row of rows) { if (row.type !== "proxmox" && row.type !== "synology") continue; try { @@ -410,24 +453,25 @@ export async function runHealthCheck(now: number = Date.now()): Promise<{ added: const current = evaluateHealth(snapshot, healthChecks, now, { skipServers: inGrace }); // A server that is down because the one it runs on is down is folded under that one: recorded, but not announced on its own. const offlineIds = new Set(); + const offlineDevices = new Set(); for (const c of current) { - const m = /^offline:server:(\d+)$/.exec(c.key); - if (m) offlineIds.add(Number(m[1])); + const m = /^offline:(server|device):(\d+)$/.exec(c.key); + if (m) (m[1] === "server" ? offlineIds : offlineDevices).add(Number(m[2])); } - // (Also when it needs a service that is failing, or runs on a server that needs one.) - const cover = await dependencyCover(offlineIds, getFailingSources().map((f) => f.source)); + // (Also when it needs a service that is failing, or runs on a server that needs one, or is connected through a device that is down.) + const cover = await dependencyCover(offlineIds, getFailingSources().map((f) => f.source), offlineDevices); const coveredKeys = new Set(); for (const child of cover.cause.keys()) { - const m = /^server:(\d+)$/.exec(child); - if (m) coveredKeys.add(`offline:server:${m[1]}`); + const m = /^(server|device):(\d+)$/.exec(child); + if (m) coveredKeys.add(`offline:${m[1]}:${m[2]}`); } const { added: announced, resolved, next, newlyDown, ended } = diffConditions(await loadState(), current, held, await activeSubjects(new Date(now)), coveredKeys); await setInternalFlag(STATE_FLAG, JSON.stringify(next)); // A host's message says what else it takes with it. const added = announced.map((c) => { - const m = /^offline:server:(\d+)$/.exec(c.key); - const children = m ? cover.taken.get(`server:${m[1]}`) : undefined; + const m = /^offline:(server|device):(\d+)$/.exec(c.key); + const children = m ? cover.taken.get(`${m[1]}:${m[2]}`) : undefined; return children?.length ? { ...c, message: `${c.message} — also takes down ${alsoList(children)}` } : c; }); diff --git a/server/src/services/maintenance.ts b/server/src/services/maintenance.ts index 6d348fd..f866aea 100644 --- a/server/src/services/maintenance.ts +++ b/server/src/services/maintenance.ts @@ -1,6 +1,6 @@ import { and, eq, gt, lt, lte } from "drizzle-orm"; import { db } from "../db/client.js"; -import { dnsProviders, integrations, maintenanceWindows, servers } from "../db/schema.js"; +import { dnsProviders, integrations, maintenanceWindows, networkDevices, servers } from "../db/schema.js"; export type ActiveWindow = typeof maintenanceWindows.$inferSelect; @@ -27,6 +27,8 @@ export function subjectOfConditionKey(key: string): string | null { if (m) return `server:${m[1]}`; m = /^(?:endpoint(?:-cert)?|heartbeat(?:-fail)?):\d+:server:(\d+)$/.exec(key); if (m) return `server:${m[1]}`; + m = /^offline:device:(\d+)$/.exec(key); + if (m) return `device:${m[1]}`; m = /^disk:proxmox:(\d+):/.exec(key); if (m) return `integration:${m[1]}`; m = /^(?:synology-volume|synology-disk|disk:synology):(\d+):/.exec(key); @@ -110,6 +112,10 @@ export async function describeTarget(targetType: ActiveWindow["targetType"], tar const [r] = await db.select({ name: servers.name }).from(servers).where(eq(servers.id, targetId)).limit(1); return r ? { name: r.name, kind: "Server" } : null; } + if (targetType === "device") { + const [r] = await db.select({ name: networkDevices.name, kind: networkDevices.kind }).from(networkDevices).where(eq(networkDevices.id, targetId)).limit(1); + return r ? { name: r.name, kind: `Network device (${r.kind.replace("_", " ")})` } : null; + } if (targetType === "integration") { const [r] = await db.select({ name: integrations.name, type: integrations.type }).from(integrations).where(eq(integrations.id, targetId)).limit(1); return r ? { name: r.name, kind: `Integration (${r.type})` } : null; diff --git a/server/src/services/notify.ts b/server/src/services/notify.ts index 9d08244..13f9d7b 100644 --- a/server/src/services/notify.ts +++ b/server/src/services/notify.ts @@ -606,6 +606,7 @@ const SOURCE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; export function sourceLabel(source: string): string { diff --git a/server/src/services/settingsStore.ts b/server/src/services/settingsStore.ts index 4020458..b217cb5 100644 --- a/server/src/services/settingsStore.ts +++ b/server/src/services/settingsStore.ts @@ -117,6 +117,8 @@ export interface HealthCheckSettings { newPortAlerts: boolean; /** An alert raised this many times within an hour is "flapping": one message says so and its further raised/cleared messages are held until it has been quiet for an hour. 0 turns it off. */ flapRaises: number; + /** A network device (switch, access point, gateway) that a UniFi controller has not seen online for this many minutes is raised as offline. */ + deviceOfflineMinutes: number; } /** The monthly report: last month's availability, incidents, updates and renewals, in one message on a day of the month. Off until switched on. */ @@ -287,7 +289,7 @@ const DEFAULTS: AppSettings = { selfBackup: { enabled: true, time: "03:30", keep: 14 }, profilePictures: { gravatar: false, identityProvider: false }, signIn: { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" }, - healthChecks: { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3 }, + healthChecks: { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10 }, // Docker's default bridge (172.17.0.0/16) and the pool it hands custom networks from (172.18–31) live here, and every // Docker host repeats them. Shown on the Consistency page, where it can be removed if 172.16/12 is used as a real LAN. consistency: { excludedRanges: ["172.16.0.0/12"] }, diff --git a/server/src/services/unifiSync.ts b/server/src/services/unifiSync.ts new file mode 100644 index 0000000..5e54cf2 --- /dev/null +++ b/server/src/services/unifiSync.ts @@ -0,0 +1,166 @@ +/** + * Keeps the network equipment of every UniFi integration in the database: the devices (state, IP, uptime, firmware, uplink), and the networks and Wi-Fi names beside + * them. A pass runs every few minutes and on request. The rows are what the Network devices page shows, what the dependency map and the offline alerts are + * built from — so none of those talk to the controller themselves, and a controller that is down costs only the freshness of what they show. + * + * What is kept is small and exact: a device that has gone offline carries `offlineSince` until it is back, which is what an "offline" alert counts from. + */ +import { and, eq, inArray, or } from "drizzle-orm"; +import { db } from "../db/client.js"; +import { dependencies, integrations, networkDevices, networkSegments } from "../db/schema.js"; +import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; +import { createUnifiAdapter, type UnifiDevice, type UnifiInventory } from "../integrations/unifi/adapter.js"; +import { getInternalFlag, setInternalFlag } from "./settingsStore.js"; + +export const SYNC_INTERVAL_MS = 5 * 60_000; +/** A device's state is only as good as the last pass: after this long without a good one, offline alerts are held rather than judged. */ +export const STALE_AFTER_MS = 20 * 60_000; +const STATUS_FLAG = "unifiSync"; + +export interface SyncStatus { + at: string; + ok: boolean; + error: string | null; + sites: string[]; + mode: "api_key" | "login" | null; + devices: number; + networks: number; + ssids: number; +} + +type DeviceRow = typeof networkDevices.$inferSelect; + +/** What a device's offline bookkeeping becomes now. Pure. `offlineSince` starts when it is first seen not online and stays until it is online again. */ +export function trackOffline(previous: { offlineSince: string | null; lastOnlineAt: string | null } | undefined, state: UnifiDevice["state"], nowIso: string): { offlineSince: string | null; lastOnlineAt: string | null } { + const lastOnlineAt = previous?.lastOnlineAt ?? null; + if (state === "online") return { offlineSince: null, lastOnlineAt: nowIso }; + if (state === "offline") return { offlineSince: previous?.offlineSince ?? nowIso, lastOnlineAt }; + // Updating, being adopted or unknown: neither back nor newly gone, so what was known stays. + return { offlineSince: previous?.offlineSince ?? null, lastOnlineAt }; +} + +async function readStatuses(): Promise> { + try { + const raw = await getInternalFlag(STATUS_FLAG); + return raw ? (JSON.parse(raw) as Record) : {}; + } catch { + return {}; + } +} + +export async function syncStatuses(): Promise> { + return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v])); +} + +async function writeStatus(integrationId: number, status: SyncStatus): Promise { + const all = await readStatuses(); + all[String(integrationId)] = status; + await setInternalFlag(STATUS_FLAG, JSON.stringify(all)); +} + +/** Writes one controller's inventory: updates what is there, adds what is new, removes what the controller no longer has. */ +export async function storeInventory(integrationId: number, inventory: UnifiInventory, now: Date = new Date()): Promise { + const nowIso = now.toISOString(); + const existing = await db.select().from(networkDevices).where(eq(networkDevices.integrationId, integrationId)); + const byExternal = new Map(existing.map((r) => [r.externalId, r])); + const seen = new Set(); + for (const d of inventory.devices) { + if (seen.has(d.externalId)) continue; + seen.add(d.externalId); + const prev = byExternal.get(d.externalId); + const track = trackOffline(prev, d.state, nowIso); + const values = { + siteName: d.siteName, + name: d.name, + model: d.model, + kind: d.kind, + ip: d.ip, + mac: d.mac, + state: d.state, + uptimeSeconds: d.uptimeSeconds, + firmware: d.firmware, + firmwareUpdatable: d.firmwareUpdatable, + uplinkExternalId: d.uplinkExternalId, + offlineSince: track.offlineSince, + lastOnlineAt: track.lastOnlineAt, + updatedAt: nowIso, + }; + if (prev) await db.update(networkDevices).set(values).where(eq(networkDevices.id, prev.id)); + else await db.insert(networkDevices).values({ integrationId, externalId: d.externalId, firstSeenAt: nowIso, ...values }); + } + const gone = existing.filter((r) => !seen.has(r.externalId)).map((r) => r.id); + if (gone.length > 0) await db.delete(networkDevices).where(inArray(networkDevices.id, gone)); + + const segments: (typeof networkSegments.$inferInsert)[] = [ + ...inventory.networks.map((n) => ({ integrationId, kind: "network" as const, externalId: n.externalId, siteName: n.siteName, name: n.name, enabled: n.enabled, vlanId: n.vlanId, subnet: n.subnet, purpose: n.purpose, security: null, networkName: null, updatedAt: nowIso })), + ...inventory.ssids.map((s) => ({ integrationId, kind: "ssid" as const, externalId: s.externalId, siteName: s.siteName, name: s.name, enabled: s.enabled, vlanId: s.vlanId, subnet: null, purpose: null, security: s.security, networkName: s.networkName, updatedAt: nowIso })), + ]; + await db.delete(networkSegments).where(eq(networkSegments.integrationId, integrationId)); + if (segments.length > 0) await db.insert(networkSegments).values(segments); +} + +/** Reads one UniFi integration and stores what it says. Never throws: how it went is the returned status, and what was stored before is left alone when it failed. */ +export async function syncUnifiIntegration(integrationId: number, now: Date = new Date()): Promise { + let status: SyncStatus; + try { + const loaded = await loadIntegrationConfig(integrationId); + if (!loaded || loaded.integration.type !== "unifi") throw new Error("not a UniFi integration"); + const inventory = await createUnifiAdapter(loaded.config as never).fetchInventory(); + await storeInventory(integrationId, inventory, now); + status = { at: now.toISOString(), ok: true, error: null, sites: inventory.sites, mode: inventory.mode, devices: inventory.devices.length, networks: inventory.networks.length, ssids: inventory.ssids.length }; + } catch (err) { + const previous = (await readStatuses())[String(integrationId)]; + // The time of the last good pass is kept: it is what says how stale the stored states are. + status = { at: previous?.ok ? previous.at : (previous?.at ?? now.toISOString()), ok: false, error: err instanceof Error ? err.message : String(err), sites: previous?.sites ?? [], mode: previous?.mode ?? null, devices: previous?.devices ?? 0, networks: previous?.networks ?? 0, ssids: previous?.ssids ?? 0 }; + console.error(`[unifi] couldn't read integration ${integrationId}:`, status.error); + } + try { + await writeStatus(integrationId, status); + } catch (err) { + console.error("[unifi] couldn't record the result:", err); + } + return status; +} + +export async function syncAllUnifi(now: Date = new Date()): Promise> { + const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "unifi"), eq(integrations.enabled, true))); + const out: Record = {}; + for (const r of rows) out[r.id] = await syncUnifiIntegration(r.id, now); + return out; +} + +/** + * Forgets everything read from a controller — when its integration is removed. Dependencies written by hand that pointed at one of its devices go too: + * they would never be shown again, and a device that comes back under a new integration is a new device. + */ +export async function removeIntegrationData(integrationId: number): Promise { + const ids = (await db.select({ id: networkDevices.id }).from(networkDevices).where(eq(networkDevices.integrationId, integrationId))).map((r) => r.id); + if (ids.length > 0) { + await db.delete(dependencies).where(or(and(eq(dependencies.fromType, "device"), inArray(dependencies.fromId, ids)), and(eq(dependencies.toType, "device"), inArray(dependencies.toId, ids)))); + await db.delete(networkDevices).where(inArray(networkDevices.id, ids)); + } + await db.delete(networkSegments).where(eq(networkSegments.integrationId, integrationId)); + const all = await readStatuses(); + if (String(integrationId) in all) { + delete all[String(integrationId)]; + await setInternalFlag(STATUS_FLAG, JSON.stringify(all)); + } +} + +/** Whether the stored states of an integration can be trusted: it has been read successfully within the last while. */ +export function isFresh(status: SyncStatus | undefined, nowMs: number): boolean { + return !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS; +} + +export type { DeviceRow }; + +let timer: ReturnType | null = null; + +export function initUnifiSync(): void { + if (timer) return; + const pass = () => void syncAllUnifi().catch((err) => console.error("[unifi] pass failed:", err)); + timer = setInterval(pass, SYNC_INTERVAL_MS); + // Not awaited, and not at once: the controller is not needed to start, and the first pass should not compete with the migrations and the first health pass. + setTimeout(pass, 5_000); + console.log(`[unifi] reading network equipment from UniFi controllers every ${SYNC_INTERVAL_MS / 60000} minutes`); +} diff --git a/server/test/unifi.test.ts b/server/test/unifi.test.ts new file mode 100644 index 0000000..394cb7f --- /dev/null +++ b/server/test/unifi.test.ts @@ -0,0 +1,490 @@ +/** + * UniFi: reading a controller either way (API key, or a login), what is kept, when a device is called offline, and how network devices take part in the + * dependency map, the alerts and the pages that list them. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; + +const dir = mkdtempSync(join(tmpdir(), "hm-unifi-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); +process.env.HEALTH_STARTUP_GRACE_MS = "0"; + +const express = (await import("express")).default; +const { db } = await import("../src/db/client.js"); +const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, dependencies, maintenanceWindows } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { encryptSecret } = await import("../src/crypto.js"); +const adapterModule = await import("../src/integrations/unifi/adapter.js"); +const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy } = adapterModule; +const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses } = await import("../src/services/unifiSync.js"); +const { evaluateHealth } = await import("../src/services/healthMonitor.js"); +const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js"); +const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js"); +const { networkRouter } = await import("../src/routes/network.js"); +const { validateIntegrationConfig } = await import("../src/integrations/fieldSchemas.js"); +const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); +const { setInternalFlag } = await import("../src/services/settingsStore.js"); +const { eq } = await import("drizzle-orm"); + +await runMigrations(); + +// ─── A pretend controller ─────────────────────────────────────────────────── + +const MAC = { gw: "00:11:22:33:44:01", sw: "00:11:22:33:44:02", ap: "00:11:22:33:44:03" }; +const SECRET_PASSPHRASE = "correct-horse-battery-staple"; + +const siteList = { offset: 0, limit: 200, count: 1, totalCount: 1, data: [{ id: "site-1", internalReference: "default", name: "Default" }] }; +const deviceList = { + offset: 0, + limit: 200, + count: 3, + totalCount: 3, + data: [ + { id: "d-gw", macAddress: "00:11:22:33:44:01", ipAddress: "192.168.1.1", name: "Gateway", model: "UDM Pro", state: "ONLINE", firmwareVersion: "4.0.6", firmwareUpdatable: false, features: ["switching"] }, + { id: "d-sw", macAddress: "00:11:22:33:44:02", ipAddress: "192.168.1.2", name: "Rack switch", model: "USW-24-PoE", state: "ONLINE", firmwareVersion: "7.0.50", firmwareUpdatable: true, features: ["switching"] }, + { id: "d-ap", macAddress: "00:11:22:33:44:03", ipAddress: "192.168.1.3", name: "Hallway AP", model: "U6 Pro", state: "OFFLINE", firmwareVersion: "6.6.55", firmwareUpdatable: false, features: ["accessPoint"] }, + ], +}; +const detail: Record = { "d-sw": { uplink: { deviceId: "d-gw" } }, "d-ap": { uplink: { deviceId: "d-sw" } }, "d-gw": {} }; +const stats: Record = { "d-gw": { uptimeSec: 864000 }, "d-sw": { uptimeSec: 3600 }, "d-ap": {} }; +const networkList = { offset: 0, limit: 200, count: 2, totalCount: 2, data: [{ id: "n-1", name: "Default", enabled: true, vlanId: 1, management: "GATEWAY" }, { id: "n-2", name: "IoT", enabled: true, vlanId: 20, management: "GATEWAY" }] }; +const networkDetail: Record = { "n-1": { ipv4Configuration: { hostIpAddress: "192.168.1.1", prefixLength: 24 } }, "n-2": { ipv4Configuration: { hostIpAddress: "192.168.20.1", prefixLength: 24 } } }; +const wifiList = { + offset: 0, + limit: 200, + count: 2, + totalCount: 2, + data: [ + { id: "w-1", name: "Home", enabled: true, securityConfiguration: { type: "WPA2_PERSONAL" }, network: { type: "NATIVE" } }, + { id: "w-2", name: "IoT-net", enabled: true, securityConfiguration: { type: "WPA3_PERSONAL" }, network: { type: "SPECIFIC", networkId: "n-2" } }, + ], +}; + +const legacyDevices = [ + { _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false }, + { _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } }, + { _id: "x3", mac: "00:11:22:33:44:03", ip: "192.168.1.3", name: "Hallway AP", model: "U6PRO", type: "uap", state: 0, version: "6.6.55", uplink: { uplink_mac: "00:11:22:33:44:02", type: "wire" } }, +]; +const legacyNetworks = [{ _id: "ln-1", name: "Default", purpose: "corporate", vlan_enabled: false, ip_subnet: "192.168.1.1/24" }, { _id: "ln-2", name: "IoT", purpose: "corporate", vlan_enabled: true, vlan: "20", ip_subnet: "192.168.20.1/24" }]; +const legacyWlans = [{ _id: "lw-1", name: "Home", enabled: true, security: "wpapsk", x_passphrase: SECRET_PASSPHRASE, networkconf_id: "ln-1" }, { _id: "lw-2", name: "Guests", enabled: false, security: "open", networkconf_id: "ln-2" }]; + +type Mode = "os-key" | "selfhosted-key" | "os-login" | "selfhosted-login"; +let mode: Mode = "os-key"; +let controller: Server; +let controllerUrl = ""; +let loginsSeen = 0; +let logoutsSeen = 0; + +function reply(res: ServerResponse, status: number, body?: unknown) { + res.writeHead(status, { "content-type": "application/json" }); + res.end(body === undefined ? "" : JSON.stringify(body)); +} + +function handleApi(url: URL, res: ServerResponse, strip: string) { + const path = url.pathname.slice(strip.length); + const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path); + if (path === "/sites") return reply(res, 200, siteList); + if (!m) return reply(res, 404, { message: "no such endpoint" }); + if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList); + if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList); + return reply(res, 200, wifiList); +} + +function handleLegacy(url: URL, res: ServerResponse, strip: string) { + const path = url.pathname.slice(strip.length); + if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] }); + if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices }); + if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks }); + if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans }); + return reply(res, 404, {}); +} + +function route(req: IncomingMessage, res: ServerResponse) { + const url = new URL(req.url ?? "/", "http://x"); + if (mode === "os-key" || mode === "selfhosted-key") { + if (req.headers["x-api-key"] !== "good-key") return reply(res, 401, { message: "bad key" }); + const prefix = mode === "os-key" ? "/proxy/network/integration/v1" : "/integration/v1"; + if (!url.pathname.startsWith(prefix)) return reply(res, 404, { message: "not here" }); + return handleApi(url, res, prefix); + } + const os = mode === "os-login"; + const loginPath = os ? "/api/auth/login" : "/api/login"; + if (req.method === "POST" && url.pathname === loginPath) { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const { username, password } = JSON.parse(body || "{}"); + if (username !== "reader" || password !== "pw") return reply(res, 401, { message: "nope" }); + loginsSeen++; + res.setHeader("set-cookie", ["TOKEN=abc123; Path=/; HttpOnly", "other=1; Path=/"]); + if (os) res.setHeader("x-csrf-token", "csrf-1"); + reply(res, 200, { ok: true }); + }); + return; + } + if (req.method === "POST" && url.pathname === (os ? "/api/auth/logout" : "/api/logout")) { + logoutsSeen++; + return reply(res, 200, {}); + } + if (!String(req.headers.cookie ?? "").includes("TOKEN=abc123")) return reply(res, 401, {}); + return handleLegacy(url, res, os ? "/proxy/network" : ""); +} + +// ─── The adapter ──────────────────────────────────────────────────────────── + +before(async () => { + controller = await new Promise((resolve) => { + const s = createServer(route).listen(0, "127.0.0.1", () => resolve(s)); + }); + controllerUrl = `http://127.0.0.1:${(controller.address() as AddressInfo).port}`; +}); +after(() => { + controller.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows may still hold the database file + } +}); + +describe("normalising what a controller says", () => { + test("a MAC address is written one way, and anything else is not a MAC address", () => { + assert.equal(normaliseMac("AA-BB-CC-DD-EE-FF"), "aa:bb:cc:dd:ee:ff"); + assert.equal(normaliseMac("aabbccddeeff"), "aa:bb:cc:dd:ee:ff"); + assert.equal(normaliseMac("not a mac"), null); + assert.equal(normaliseMac(undefined), null); + }); + + test("the kind of device comes from its model, features or type — a gateway with a built-in switch is a gateway", () => { + assert.equal(deviceKind("UDM Pro", ["switching"], null), "gateway"); + assert.equal(deviceKind("USW-24-PoE", ["switching"], null), "switch"); + assert.equal(deviceKind("U6 Pro", ["accessPoint"], null), "access_point"); + assert.equal(deviceKind(null, [], "uap"), "access_point"); + assert.equal(deviceKind("UCG-Max", [], null), "gateway"); + assert.equal(deviceKind("Mystery", [], null), "other"); + }); + + test("only OFFLINE-like states are offline; adopting and updating devices are not a problem", () => { + assert.equal(stateFromApi("ONLINE"), "online"); + assert.equal(stateFromApi("OFFLINE"), "offline"); + assert.equal(stateFromApi("CONNECTION_INTERRUPTED"), "offline"); + assert.equal(stateFromApi("UPDATING"), "updating"); + assert.equal(stateFromApi("PENDING_ADOPTION"), "pending"); + assert.equal(stateFromApi("something new"), "other"); + assert.equal(stateFromLegacy(1), "online"); + assert.equal(stateFromLegacy(0), "offline"); + assert.equal(stateFromLegacy(6), "offline"); + assert.equal(stateFromLegacy(4), "updating"); + assert.equal(stateFromLegacy(7), "pending"); + assert.equal(stateFromLegacy(99), "other"); + }); + + test("a device from the Integration API gets its uplink as a MAC, and a missing detail only costs the uplink", () => { + const macById = new Map([["d-gw", MAC.gw], ["d-sw", MAC.sw]]); + const d = deviceFromApi(deviceList.data[1], detail["d-sw"], stats["d-sw"], "Default", macById)!; + assert.deepEqual([d.externalId, d.uplinkExternalId, d.uptimeSeconds, d.kind, d.firmwareUpdatable], [MAC.sw, MAC.gw, 3600, "switch", true]); + const bare = deviceFromApi(deviceList.data[1], null, null, "Default", macById)!; + assert.deepEqual([bare.uplinkExternalId, bare.uptimeSeconds, bare.name], [null, null, "Rack switch"]); + assert.equal(deviceFromApi({ name: "no mac" }, null, null, "Default", macById), null); + }); + + test("the classic API's device and Wi-Fi: the uplink MAC is read, and a passphrase is never carried over", () => { + const d = deviceFromLegacy(legacyDevices[2], "Default")!; + assert.deepEqual([d.uplinkExternalId, d.state, d.kind, d.model], [MAC.sw, "offline", "access_point", "U6PRO"]); + const s = ssidFromLegacy(legacyWlans[0], new Map([["ln-1", "Default"]]), "Default")!; + assert.deepEqual([s.name, s.security, s.networkName], ["Home", "WPA personal", "Default"]); + assert.ok(!JSON.stringify(s).includes(SECRET_PASSPHRASE)); + }); +}); + +describe("reading a controller", () => { + const cfg = (extra: Record) => ({ url: controllerUrl, ...extra }) as never; + + test("with an API key on a UniFi OS console: sites, devices with uplinks and uptime, networks with their ranges, Wi-Fi names", async () => { + mode = "os-key"; + const inv = await createUnifiAdapter(cfg({ apiKey: "good-key" })).fetchInventory(); + assert.equal(inv.mode, "api_key"); + assert.deepEqual(inv.sites, ["Default"]); + const by = Object.fromEntries(inv.devices.map((d) => [d.name, d])); + assert.deepEqual([by["Gateway"].kind, by["Gateway"].uptimeSeconds, by["Gateway"].uplinkExternalId], ["gateway", 864000, null]); + assert.deepEqual([by["Rack switch"].uplinkExternalId, by["Hallway AP"].uplinkExternalId], [MAC.gw, MAC.sw]); + assert.deepEqual([by["Hallway AP"].state, by["Hallway AP"].uptimeSeconds], ["offline", null]); + assert.deepEqual(inv.networks.map((n) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]); + assert.deepEqual(inv.ssids.map((s) => [s.name, s.security, s.networkName]), [["Home", "WPA2", "Default"], ["IoT-net", "WPA3", "IoT"]]); + }); + + test("a self-hosted controller answers without /proxy/network: the other form of the address is found when the first is not there", async () => { + mode = "selfhosted-key"; + const viaProbe = await createUnifiAdapter(cfg({ apiKey: "good-key" })).fetchInventory(); + assert.equal(viaProbe.devices.length, 3); + const viaFlag = await createUnifiAdapter(cfg({ apiKey: "good-key", selfHosted: true })).fetchInventory(); + assert.equal(viaFlag.devices.length, 3); + }); + + test("a key that is not accepted says so, and a site that does not exist says so", async () => { + mode = "os-key"; + await assert.rejects(createUnifiAdapter(cfg({ apiKey: "wrong" })).fetchInventory(), /did not accept the API key/); + await assert.rejects(createUnifiAdapter(cfg({ apiKey: "good-key", site: "Garage" })).fetchInventory(), /no site called/); + const only = await createUnifiAdapter(cfg({ apiKey: "good-key", site: "default" })).fetchInventory(); + assert.equal(only.devices.length, 3); + }); + + test("with a login on a UniFi OS console: the session cookie and CSRF token are used, the Wi-Fi passphrase is dropped, and the session is given back", async () => { + mode = "os-login"; + loginsSeen = 0; + logoutsSeen = 0; + const inv = await createUnifiAdapter(cfg({ username: "reader", password: "pw" })).fetchInventory(); + assert.equal(inv.mode, "login"); + assert.equal(inv.devices.length, 3); + assert.equal(inv.devices.find((d) => d.name === "Hallway AP")!.uplinkExternalId, MAC.sw); + assert.deepEqual(inv.networks.map((n) => [n.name, n.vlanId, n.subnet]), [["Default", null, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]); + assert.deepEqual(inv.ssids.map((s) => [s.name, s.enabled, s.security, s.networkName]), [["Home", true, "WPA personal", "Default"], ["Guests", false, "Open", "IoT"]]); + assert.ok(!JSON.stringify(inv).includes(SECRET_PASSPHRASE)); + assert.deepEqual([loginsSeen, logoutsSeen], [1, 1]); + }); + + test("with a login on a self-hosted controller, and the wrong password", async () => { + mode = "selfhosted-login"; + const inv = await createUnifiAdapter(cfg({ username: "reader", password: "pw", selfHosted: true })).fetchInventory(); + assert.equal(inv.devices.length, 3); + await assert.rejects(createUnifiAdapter(cfg({ username: "reader", password: "no" })).fetchInventory(), /did not accept the username and password/); + }); + + test("ping says whether it can get in", async () => { + mode = "os-key"; + assert.equal((await createUnifiAdapter(cfg({ apiKey: "good-key" })).ping()).ok, true); + const bad = await createUnifiAdapter(cfg({ apiKey: "wrong" })).ping(); + assert.equal(bad.ok, false); + assert.match(bad.error ?? "", /API key/); + }); + + test("the form needs a key, or a username with its password", () => { + assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x" }), ["apiKey"]); + assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", username: "u" }), ["password"]); + assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", apiKey: "k" }), []); + assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", username: "u", password: "p" }), []); + }); +}); + +// ─── What is kept ─────────────────────────────────────────────────────────── + +describe("keeping what was read", () => { + test("a device is offline from the first time it is seen not online, until it is online again", () => { + const t0 = "2026-01-01T10:00:00.000Z"; + const t1 = "2026-01-01T10:05:00.000Z"; + const t2 = "2026-01-01T10:10:00.000Z"; + let s = trackOffline(undefined, "online", t0); + assert.deepEqual(s, { offlineSince: null, lastOnlineAt: t0 }); + s = trackOffline(s, "offline", t1); + assert.deepEqual(s, { offlineSince: t1, lastOnlineAt: t0 }); + s = trackOffline(s, "offline", t2); + assert.equal(s.offlineSince, t1, "still counted from the first time"); + s = trackOffline(s, "updating", t2); + assert.equal(s.offlineSince, t1, "updating says nothing either way"); + s = trackOffline(s, "online", t2); + assert.deepEqual(s, { offlineSince: null, lastOnlineAt: t2 }); + }); + + test("freshness: only a good, recent read can be believed", () => { + const now = Date.parse("2026-01-01T12:00:00.000Z"); + const status = (at: string, ok = true) => ({ at, ok, error: null, sites: [], mode: null, devices: 0, networks: 0, ssids: 0 }); + assert.equal(isFresh(undefined, now), false); + assert.equal(isFresh(status("2026-01-01T11:55:00.000Z"), now), true); + assert.equal(isFresh(status("2026-01-01T11:00:00.000Z"), now), false); + assert.equal(isFresh(status("2026-01-01T11:55:00.000Z", false), now), false); + }); +}); + +describe("a controller in the database", () => { + let integrationId = 0; + let gwId = 0; + let swId = 0; + let apId = 0; + let webId = 0; + + before(async () => { + await db.insert(users).values([ + { oidcSub: "admin", name: "Ada", role: "admin" }, + { oidcSub: "viewer", name: "Vic", role: "viewer" }, + { oidcSub: "operator", name: "Olga", role: "operator" }, + ]); + mode = "os-key"; + const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning(); + const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning(); + integrationId = row.id; + webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id; + }); + + test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => { + const status = await syncUnifiIntegration(integrationId); + assert.equal(status.ok, true); + assert.deepEqual([status.devices, status.networks, status.ssids, status.mode], [3, 2, 2, "api_key"]); + const rows = await db.select().from(networkDevices); + assert.equal(rows.length, 3); + gwId = rows.find((r) => r.name === "Gateway")!.id; + swId = rows.find((r) => r.name === "Rack switch")!.id; + apId = rows.find((r) => r.name === "Hallway AP")!.id; + const ap = rows.find((r) => r.id === apId)!; + assert.deepEqual([ap.state, ap.kind, ap.ip, ap.uplinkExternalId], ["offline", "access_point", "192.168.1.3", MAC.sw]); + assert.ok(ap.offlineSince, "offline since the first look"); + assert.equal((await db.select().from(networkSegments)).length, 4); + assert.equal((await syncStatuses())[integrationId].ok, true); + }); + + test("a second read keeps when the offline began, and a device that is gone from the controller is removed", async () => { + const before = (await db.select().from(networkDevices).where(eq(networkDevices.id, apId)))[0].offlineSince; + await new Promise((r) => setTimeout(r, 15)); + await syncUnifiIntegration(integrationId, new Date()); + assert.equal((await db.select().from(networkDevices).where(eq(networkDevices.id, apId)))[0].offlineSince, before); + assert.equal((await db.select().from(networkDevices)).length, 3, "updated in place, not added again"); + }); + + test("a controller that cannot be read leaves what was stored, and says why", async () => { + mode = "selfhosted-key"; // the console form of the address now 404s... but the probe finds the other form, so break the key instead + const [cred] = await db.select().from(integrationCredentials); + await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "revoked" })) }).where(eq(integrationCredentials.id, cred.id)); + const status = await syncUnifiIntegration(integrationId); + assert.equal(status.ok, false); + assert.match(status.error ?? "", /API key/); + assert.equal((await db.select().from(networkDevices)).length, 3); + await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).where(eq(integrationCredentials.id, cred.id)); + mode = "os-key"; + assert.equal((await syncUnifiIntegration(integrationId)).ok, true); + }); + + test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => { + const graph = await loadGraph(); + assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]); + assert.deepEqual(graph.edges.get(`device:${swId}`), [`device:${gwId}`]); + assert.equal(graph.edges.get(`device:${gwId}`), undefined); + assert.equal(graph.rows.length, 0, "none of them is a written dependency"); + assert.equal(alertIdOfNode(`device:${swId}`, graph), `offline:offline:device:${swId}`); + assert.deepEqual(uplinkEdges([{ id: 1, integrationId: 1, externalId: "a", uplinkExternalId: "zz" }]), [], "an uplink that is not known is none"); + }); + + test("a server written as needing the access point is folded under whatever of them is the root cause", async () => { + await db.insert(dependencies).values({ fromType: "server", fromId: webId, toType: "device", toId: apId }); + const cover = await dependencyCover([webId], [], [apId, swId]); + assert.equal(cover.cause.get(`device:${apId}`), `device:${swId}`, "the access point is down because the switch is"); + assert.equal(cover.cause.get(`server:${webId}`), `device:${swId}`, "and so is the server that needs it"); + assert.equal(cover.cause.get(`device:${swId}`), undefined, "the switch stands alone: nothing it needs is down"); + assert.deepEqual([...(cover.taken.get(`device:${swId}`) ?? [])].sort(), ["Hallway AP", "web"]); + // with only the access point down, it is its own cause + const alone = await dependencyCover([], [], [apId]); + assert.equal(alone.cause.size, 0); + }); + + test("a device offline for longer than the limit is a critical offline alert about it", () => { + const device = (state: string, since: string | null) => ({ id: 7, name: "Hallway AP", kind: "access_point", model: "U6 Pro", state, offlineSince: since }); + const snap = (devices: ReturnType[]) => ({ servers: [], proxmox: [], synology: [], unifi: [{ integrationId: 3, integrationName: "Home UniFi", devices }] }); + const now = Date.parse("2026-01-01T12:00:00.000Z"); + const limits = { serverOfflineMinutes: 60, diskUsagePercent: 90, deviceOfflineMinutes: 10 }; + const five = evaluateHealth(snap([device("offline", "2026-01-01T11:55:00.000Z")]), limits, now); + assert.deepEqual(five, [], "five minutes is not yet"); + const twenty = evaluateHealth(snap([device("offline", "2026-01-01T11:40:00.000Z")]), limits, now); + assert.equal(twenty.length, 1); + assert.deepEqual([twenty[0].key, twenty[0].source, twenty[0].severity], ["offline:device:7", "unifi:3", "critical"]); + assert.match(twenty[0].message, /Hallway AP \(access point, U6 Pro\) has been offline for 20 min/); + assert.deepEqual(evaluateHealth(snap([device("updating", "2026-01-01T11:00:00.000Z")]), limits, now), [], "updating is not offline"); + assert.deepEqual(evaluateHealth(snap([device("online", null)]), limits, now), []); + assert.equal(subjectOfConditionKey("offline:device:7"), "device:7", "maintenance on a device holds its alert"); + }); + + test("a maintenance window can be put on a device, and describes it", async () => { + const described = await describeTarget("device", apId); + assert.deepEqual(described, { name: "Hallway AP", kind: "Network device (access point)" }); + assert.equal(await describeTarget("device", 99999), null); + await db.insert(maintenanceWindows).values({ targetType: "device", targetId: swId, startedAt: new Date(Date.now() - 1000).toISOString(), endsAt: new Date(Date.now() + 3600_000).toISOString(), reason: "rack work" }); + }); + + test("on the Alerts page: the offline device, who it is about and where to go, silenced by maintenance, and held back when the controller has not been read for a while", async () => { + await db.update(networkDevices).set({ offlineSince: new Date(Date.now() - 30 * 60_000).toISOString() }).where(eq(networkDevices.id, apId)); + invalidateAlertsCache(); + const alertId = `offline:offline:device:${apId}`; + let report = await getAlerts(true); + const alert = report.alerts.find((a) => a.id === alertId)!; + assert.ok(alert, "the access point is raised"); + assert.deepEqual([alert.severity, alert.category, alert.source, alert.link, alert.target?.type, alert.target?.name, alert.silenced], ["critical", "offline", "UniFi", "/network/devices", "device", "Hallway AP", false]); + assert.match(alert.message, /has been offline for 30 min/); + + const [window] = await db.insert(maintenanceWindows).values({ targetType: "device", targetId: apId, startedAt: new Date(Date.now() - 1000).toISOString(), endsAt: new Date(Date.now() + 3600_000).toISOString() }).returning(); + invalidateAlertsCache(); + report = await getAlerts(true); + assert.equal(report.alerts.find((a) => a.id === alertId)!.silenced, true); + await db.delete(maintenanceWindows).where(eq(maintenanceWindows.id, window.id)); + + // Not read for longer than anyone should trust it: neither raised nor cleared, and the page says it cannot tell. + const stale = { [integrationId]: { at: new Date(Date.now() - 3600_000).toISOString(), ok: true, error: null, sites: [], mode: "api_key", devices: 3, networks: 2, ssids: 2 } }; + await setInternalFlag("unifiSync", JSON.stringify(stale)); + invalidateAlertsCache(); + report = await getAlerts(true); + assert.equal(report.alerts.some((a) => a.id === alertId), false); + assert.ok(report.couldntCheck.some((c) => /UniFi/.test(c.name)), "it says it could not check"); + assert.equal((await syncUnifiIntegration(integrationId)).ok, true); + invalidateAlertsCache(); + }); + + describe("the page's data", () => { + let app: Server; + let base = ""; + let who = "viewer"; + before(async () => { + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: who } }; + next(); + }); + a.use("/api/network", networkRouter); + app = await new Promise((resolve) => { + const s = a.listen(0, "127.0.0.1", () => resolve(s)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/network`; + }); + after(() => app.close()); + + test("everyone signed in sees the devices with their address, uptime, uplink and what depends on them", async () => { + const res = await fetch(base); + assert.equal(res.status, 200); + const body = (await res.json()) as any; + const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d])); + assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]); + assert.equal(by["Hallway AP"].state, "offline"); + assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind them"); + assert.equal(by["Hallway AP"].needs, 2); + assert.equal(by["Rack switch"].inMaintenance, true); + assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]); + assert.deepEqual(body.ssids.map((s: any) => [s.name, s.networkName]).sort(), [["Home", "Default"], ["IoT-net", "IoT"]]); + assert.equal(body.integrations[0].status.ok, true); + assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE)); + }); + + test("reading again needs an operator", async () => { + who = "viewer"; + assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403); + who = "operator"; + const res = await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId }) }); + assert.equal(res.status, 200); + assert.equal(((await res.json()) as any).statuses[integrationId].ok, true); + const other = await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId: 424242 }) }); + assert.equal(other.status, 404); + }); + }); + + test("removing the integration removes what was read from it, and the dependencies written about its devices", async () => { + await removeIntegrationData(integrationId); + assert.equal((await db.select().from(networkDevices)).length, 0); + assert.equal((await db.select().from(networkSegments)).length, 0); + assert.equal((await db.select().from(dependencies)).length, 0); + assert.equal((await syncStatuses())[integrationId], undefined); + }); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index 32581b3..7bda53b 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -6,6 +6,7 @@ import Dashboard from "./pages/Dashboard"; import Users from "./pages/Users"; import Secrets from "./pages/Secrets"; import Ipam from "./pages/Ipam"; +import NetworkDevices from "./pages/NetworkDevices"; import Ports from "./pages/Ports"; import Dns from "./pages/Dns"; import Servers from "./pages/Servers"; @@ -139,6 +140,7 @@ function Shelled({ user }: { user: CurrentUser }) { } /> } /> } /> + } /> } /> } /> } /> diff --git a/web/src/api/client.ts b/web/src/api/client.ts index b0b8f81..f9886ec 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -173,10 +173,10 @@ export interface SessionSummary { expiresAt: string | null; } -export type MaintenanceTargetType = "server" | "integration" | "dns_provider"; +export type MaintenanceTargetType = "server" | "integration" | "dns_provider" | "device"; /** A whole group at once: every server, every enabled integration, every enabled DNS provider, or all of those. */ -export type MaintenanceBulkScope = "everything" | "servers" | "integrations" | "dns_providers"; +export type MaintenanceBulkScope = "everything" | "servers" | "integrations" | "dns_providers" | "devices"; export interface MaintenanceWindow { id: number; @@ -206,6 +206,8 @@ export interface MaintenanceTargets { servers: { id: number; name: string }[]; integrations: { id: number; name: string; type: string }[]; dnsProviders: { id: number; name: string; providerType: string }[]; + /** Network devices read from a UniFi controller. */ + devices: { id: number; name: string; kind: string }[]; } export interface AuditLogEntry { @@ -512,6 +514,8 @@ export interface HealthCheckSettings { newPortAlerts: boolean; /** An alert raised this many times within an hour is "flapping": one message says so and its further messages are held until it has been quiet for an hour. 0 is off. */ flapRaises: number; + /** Minutes a UniFi device may be offline before it is raised. */ + deviceOfflineMinutes: number; } /** The monthly report: last month's availability, incidents, updates and renewals, in one message on a day of the month. */ @@ -1109,7 +1113,7 @@ export interface LifecycleReport { export type AssetKind = "server" | "storage" | "network" | "power" | "client" | "other"; -export type DependencyNodeType = "server" | "integration"; +export type DependencyNodeType = "server" | "integration" | "device"; /** Something that would be affected if another went down (or that it needs): `distance` 1 is directly, 2 through one other, and so on. */ export interface DependencyImpactItem { @@ -1136,7 +1140,7 @@ export interface DependencyGraphNode { export interface DependencyGraph { nodes: DependencyGraphNode[]; /** From the thing that is needed to the thing that needs it. */ - edges: { from: string; to: string; kind: "written" | "runs-on" }[]; + edges: { from: string; to: string; kind: "written" | "runs-on" | "uplink" }[]; } export interface DependencyNode { key: string; @@ -1152,6 +1156,71 @@ export interface DependenciesResponse { nodes: DependencyNode[]; } +export type NetworkDeviceKind = "gateway" | "switch" | "access_point" | "other"; +export type NetworkDeviceState = "online" | "offline" | "updating" | "pending" | "other"; + +/** A switch, access point or gateway read from a UniFi controller. */ +export interface NetworkDevice { + id: number; + integrationId: number; + integrationName: string; + siteName: string | null; + name: string; + model: string | null; + kind: NetworkDeviceKind; + ip: string | null; + mac: string | null; + state: NetworkDeviceState; + uptimeSeconds: number | null; + firmware: string | null; + firmwareUpdatable: boolean; + /** The device it is connected through, as the controller says. */ + uplink: { id: number; name: string } | null; + offlineSince: string | null; + lastOnlineAt: string | null; + updatedAt: string; + /** How many things need it (directly or through others), and how many it needs. */ + dependents: number; + needs: number; + inMaintenance: boolean; +} + +/** A network (VLAN) or a Wi-Fi name a controller has set up. */ +export interface NetworkSegment { + id: number; + integrationId: number; + integrationName: string; + externalId: string; + siteName: string | null; + name: string; + enabled: boolean; + vlanId: number | null; + subnet: string | null; + purpose: string | null; + security: string | null; + networkName: string | null; + updatedAt: string; +} + +export interface UnifiSyncStatus { + /** When the controller was last read successfully. */ + at: string; + ok: boolean; + error: string | null; + sites: string[]; + mode: "api_key" | "login" | null; + devices: number; + networks: number; + ssids: number; +} + +export interface NetworkOverview { + integrations: { id: number; name: string; enabled: boolean; status: UnifiSyncStatus | null }[]; + devices: NetworkDevice[]; + networks: NetworkSegment[]; + ssids: NetworkSegment[]; +} + /** A piece of hardware in the inventory. */ export interface Asset { id: number; @@ -1566,7 +1635,7 @@ export interface ManualTaskInput { enabled?: boolean; } -export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket"; +export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi"; export interface IntegrationField { key: string; @@ -2154,6 +2223,10 @@ export const api = { request<{ minSeverity: string | null; categories: AlertCategory[] | null }>(`/api/push/${id}`, { method: "PATCH", body: JSON.stringify(data) }), test: () => request<{ sent: number; removed: number; failed: number }>("/api/push/test", { method: "POST" }), }, + network: { + overview: () => request("/api/network"), + sync: (integrationId?: number) => request<{ statuses: Record }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }), + }, dependencies: { list: () => request("/api/dependencies"), impact: (type: DependencyNodeType, id: number) => request(`/api/dependencies/impact?type=${type}&id=${id}`), diff --git a/web/src/components/CommandPalette.tsx b/web/src/components/CommandPalette.tsx index 07193fb..50262c5 100644 --- a/web/src/components/CommandPalette.tsx +++ b/web/src/components/CommandPalette.tsx @@ -42,6 +42,7 @@ const INTEGRATION_TYPE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; const DNS_PROVIDER_LABELS: Record = { @@ -350,6 +351,7 @@ export default function CommandPalette({ ...targets.servers.map((s) => ({ type: "server" as const, id: s.id, name: s.name, kind: "server" })), ...targets.integrations.map((i) => ({ type: "integration" as const, id: i.id, name: i.name, kind: i.type })), ...targets.dnsProviders.map((p) => ({ type: "dns_provider" as const, id: p.id, name: p.name, kind: "DNS provider" })), + ...targets.devices.map((d) => ({ type: "device" as const, id: d.id, name: d.name, kind: "network device" })), ]; for (const t of targetList) { for (const [minutes, words] of [ diff --git a/web/src/components/DependencyMap.tsx b/web/src/components/DependencyMap.tsx index 58a0697..61057b3 100644 --- a/web/src/components/DependencyMap.tsx +++ b/web/src/components/DependencyMap.tsx @@ -13,6 +13,8 @@ const COL_GAP = 120; const STATUS_SYMBOL: Record = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" }; const STATUS_WORD: Record = { ok: "working", bad: "problem", warn: "check", unknown: "no status" }; +const KIND_LABEL: Record = { server: "Server", integration: "Integration", device: "Network device" }; + interface Placed extends DependencyGraphNode { x: number; y: number; @@ -142,17 +144,17 @@ export default function DependencyMap() { const upPath = (e.to === active || sets.up.has(e.to)) && sets.up.has(e.from); cls = downPath ? "map-edge map-edge-down" : upPath ? "map-edge map-edge-up" : "map-edge map-dim"; } - return ${e.to}`} d={`M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2},${y2}`} className={cls} fill="none" strokeDasharray={e.kind === "runs-on" ? "5 4" : undefined} />; + return ${e.to}`} d={`M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2},${y2}`} className={cls} fill="none" strokeDasharray={e.kind !== "written" ? "5 4" : undefined} />; })} {[...view.placed.values()].map((n) => ( ))} diff --git a/web/src/components/ImpactNote.tsx b/web/src/components/ImpactNote.tsx index 486cf25..ecd26f1 100644 --- a/web/src/components/ImpactNote.tsx +++ b/web/src/components/ImpactNote.tsx @@ -26,14 +26,14 @@ export default function ImpactNote({ const keyOf = targets.map((t) => `${t.type}:${t.id}`).sort().join(","); useEffect(() => { - const own = targets.filter((t) => t.type === "server" || t.type === "integration"); + const own = targets.filter((t) => t.type === "server" || t.type === "integration" || t.type === "device"); if (own.length === 0) { setItems([]); return; } let alive = true; setItems(null); - Promise.all(own.map((t) => api.dependencies.impact(t.type as "server" | "integration", t.id).catch(() => null))) + Promise.all(own.map((t) => api.dependencies.impact(t.type as "server" | "integration" | "device", t.id).catch(() => null))) .then((all) => { if (!alive) return; const selected = new Set(own.map((t) => `${t.type}:${t.id}`)); diff --git a/web/src/components/IntegrationEditForm.tsx b/web/src/components/IntegrationEditForm.tsx index 51882bb..864d0e1 100644 --- a/web/src/components/IntegrationEditForm.tsx +++ b/web/src/components/IntegrationEditForm.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { api, type IntegrationField, type IntegrationSummary, type IntegrationType } from "../api/client"; +import { readableError } from "../utils/errors"; import { BlockSkeleton } from "./Skeleton"; const TYPE_LABELS: Record = { @@ -13,6 +14,7 @@ const TYPE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; export default function IntegrationEditForm({ @@ -85,7 +87,7 @@ export default function IntegrationEditForm({ await api.integrations.update(integration.id, { name, config: collectOverrides() }); onSaved(); } catch (err) { - setError(err instanceof Error ? err.message : String(err)); + setError(readableError(err)); } finally { setSaving(false); } diff --git a/web/src/components/IntegrationForm.tsx b/web/src/components/IntegrationForm.tsx index 28b01dd..979f687 100644 --- a/web/src/components/IntegrationForm.tsx +++ b/web/src/components/IntegrationForm.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { api, type IntegrationField, type IntegrationType } from "../api/client"; +import { readableError } from "../utils/errors"; const TYPE_LABELS: Record = { tailscale: "Tailscale", @@ -12,6 +13,7 @@ const TYPE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () => void; onCancel: () => void }) { @@ -52,7 +54,7 @@ export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () const result = await api.integrations.test({ type, config: values }); setTestResult(result); } catch (err) { - setTestResult({ ok: false, error: err instanceof Error ? err.message : String(err) }); + setTestResult({ ok: false, error: readableError(err) }); } finally { setTesting(false); } @@ -67,7 +69,7 @@ export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () await api.integrations.create({ type, name, config: values }); onCreated(); } catch (err) { - setError(err instanceof Error ? err.message : String(err)); + setError(readableError(err)); } finally { setSaving(false); } diff --git a/web/src/components/RecurringMaintenance.tsx b/web/src/components/RecurringMaintenance.tsx index cefe346..1e92138 100644 --- a/web/src/components/RecurringMaintenance.tsx +++ b/web/src/components/RecurringMaintenance.tsx @@ -87,6 +87,7 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { const groups: { label: string; type: MaintenanceTargetType; items: { id: number; name: string }[] }[] = [ { label: "Servers", type: "server", items: targets?.servers ?? [] }, { label: "Integrations", type: "integration", items: targets?.integrations ?? [] }, + { label: "Network devices", type: "device", items: targets?.devices ?? [] }, { label: "DNS providers", type: "dns_provider", items: targets?.dnsProviders ?? [] }, ]; diff --git a/web/src/components/SilenceButton.tsx b/web/src/components/SilenceButton.tsx index 4d6d62a..ca82de9 100644 --- a/web/src/components/SilenceButton.tsx +++ b/web/src/components/SilenceButton.tsx @@ -1,5 +1,5 @@ import { useState } from "react"; -import { api, type AlertItem } from "../api/client"; +import { api, type AlertItem, type MaintenanceTargetType } from "../api/client"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; @@ -14,11 +14,11 @@ const CHOICES = [ * about that server or integration, not just this one alert — which is what a maintenance window is — so it says so, and the * Maintenance page is where to end it early. The choices open in place, so nothing is clipped by the table around it. */ -export default function SilenceButton({ alert, onDone }: { alert: AlertItem; onDone: () => void }) { +export default function SilenceButton({ alert, target: given, onDone }: { alert?: AlertItem; /** Instead of an alert: silence this thing directly. */ target?: { type: MaintenanceTargetType; id: number; name: string }; onDone: () => void }) { const [choosing, setChoosing] = useState(false); const [busy, setBusy] = useState(false); - const target = alert.target; - if (!target || alert.silenced) return null; + const target = alert?.target ?? given; + if (!target || alert?.silenced) return null; async function silence(minutes: number, words: string) { if (!target) return; @@ -28,7 +28,7 @@ export default function SilenceButton({ alert, onDone }: { alert: AlertItem; onD targetType: target.type, targetId: target.id, minutes, - reason: `Silenced from the Alerts page: ${alert.message}`.slice(0, 200), + reason: (alert ? `Silenced from the Alerts page: ${alert.message}` : `Silenced from the Network devices page`).slice(0, 200), }); toast.success(`${target.name} is silenced for ${words} — every alert about it. End it early under Maintenance.`); // The sidebar badge and the maintenance banner listen for this. diff --git a/web/src/components/WallView.tsx b/web/src/components/WallView.tsx index 2a2f306..2666d67 100644 --- a/web/src/components/WallView.tsx +++ b/web/src/components/WallView.tsx @@ -15,6 +15,7 @@ const TYPE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup", osticket: "osTicket", + unifi: "UniFi", }; export type WallLevel = "critical" | "warning" | "ok" | "unsure"; diff --git a/web/src/layout/nav.tsx b/web/src/layout/nav.tsx index c964dcf..65c0dcd 100644 --- a/web/src/layout/nav.tsx +++ b/web/src/layout/nav.tsx @@ -4,6 +4,7 @@ import { IconServer2, IconWorld, IconNetwork, + IconRouter, IconKey, IconPlugConnected, IconBrandDocker, @@ -92,6 +93,7 @@ export const NAV: NavEntry[] = [ icon: , items: [ { to: "/dns", label: "DNS", icon: }, + { to: "/network/devices", label: "Network devices", icon: }, { to: "/ipam", label: "IP Addresses", icon: }, { to: "/ports", label: "Ports", icon: }, { to: "/consistency", label: "Consistency", icon: }, diff --git a/web/src/pages/Integrations.tsx b/web/src/pages/Integrations.tsx index e69f591..cd14e68 100644 --- a/web/src/pages/Integrations.tsx +++ b/web/src/pages/Integrations.tsx @@ -25,6 +25,7 @@ const TYPE_LABELS: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; /** The page each kind of integration gets once it is connected. */ @@ -39,6 +40,7 @@ const TYPE_PAGES: Record = { phpipam: "/ipam", pbs: "/pbs", osticket: "/osticket", + unifi: "/network/devices", }; /** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */ diff --git a/web/src/pages/Maintenance.tsx b/web/src/pages/Maintenance.tsx index ebe47d7..c9690d5 100644 --- a/web/src/pages/Maintenance.tsx +++ b/web/src/pages/Maintenance.tsx @@ -265,9 +265,10 @@ export default function Maintenance({ user }: { user: CurrentUser }) { setKind(e.target.value as typeof kind)}> + + {(Object.keys(KIND_LABELS) as NetworkDeviceKind[]).map((k) => ( + + ))} + + + + } + shown={sorted?.length} + total={devices.length} + onExport={exportCsv} + exportDisabled={!sorted || sorted.length === 0} + /> +
+ + + + label="Status" sortKeyName="stateRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="IP address" sortKeyName="ip" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="Uptime" sortKeyName="uptimeSeconds" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="Firmware" sortKeyName="firmware" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="Connected through" sortKeyName="uplinkName" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + label="Needed by" sortKeyName="dependents" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> + {canAct && ( + + )} + + + + {(pageItems ?? []).map((d) => ( + + + + + + + + + {canAct && ( + + )} + + ))} + {(sorted ?? []).length === 0 && ( + { tableSearch.setQuery(""); setKind("all"); setStatus("all"); } } + : { title: "No devices yet", hint: "The controller has not reported any, or has not been read yet. Press Read now." })} + /> + )} + +
+ Actions +
+ + {d.inMaintenance && ( + + maintenance + + )} + + {d.name} +
+ {KIND_LABELS[d.kind]} + {d.model ? ` · ${d.model}` : ""} + {data.integrations.length > 1 ? ` · ${d.integrationName}` : ""} + {d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""} +
+ {d.mac &&
{d.mac}
} +
+ {d.ip ? ( + + {d.ip} + + + ) : ( + — + )} + + {d.state === "online" ? uptimeWords(d.uptimeSeconds) : —} + + {d.firmware ?? —} + {d.firmwareUpdatable && update available} + + {d.uplink ? d.uplink.name : {d.kind === "gateway" ? "(the internet)" : "—"}} + + {d.dependents > 0 ? ( + + {d.dependents} {d.dependents === 1 ? "thing" : "things"} + + ) : ( + nothing + )} + +
+ {!d.inMaintenance && void load()} />} + +
+
+
+ + + + )} + + {data && data.integrations.length > 0 && view === "wifi" && } + + ); +} + +function enabledBadge(on: boolean) { + return on ? On : Off; +} + +function NetworksAndWifi({ data }: { data: NetworkOverview }) { + const many = data.integrations.length > 1; + const where = (s: NetworkSegment) => [many ? s.integrationName : null, s.siteName && s.siteName !== "Default" ? s.siteName : null].filter(Boolean).join(" · "); + return ( + <> +
+
+

Networks

+
+
+ + + + + + + + + + + + {data.networks.map((n) => ( + + + + + + + + ))} + {data.networks.length === 0 && } + +
NameVLANAddress rangePurposeState
+ {n.name} + {where(n) &&
{where(n)}
} +
{n.vlanId ?? —}{n.subnet ?? —}{n.purpose ?? —}{enabledBadge(n.enabled)}
+
+
+ +
+
+

Wi-Fi names

+
+
+ + + + + + + + + + + + {data.ssids.map((s) => ( + + + + + + + + ))} + {data.ssids.length === 0 && } + +
Name (SSID)SecurityNetworkVLANState
+ {s.name} + {where(s) &&
{where(s)}
} +
{s.security ?? —}{s.networkName ?? —}{s.vlanId ?? —}{enabledBadge(s.enabled)}
+
+
Passphrases are never read from the controller.
+
+ + ); +} diff --git a/web/src/pages/settings/BadgeSettings.tsx b/web/src/pages/settings/BadgeSettings.tsx index dca1bfa..535f548 100644 --- a/web/src/pages/settings/BadgeSettings.tsx +++ b/web/src/pages/settings/BadgeSettings.tsx @@ -23,6 +23,7 @@ const INTEGRATION_NAMES: Record = { phpipam: "phpIPAM", pbs: "Proxmox Backup Server", osticket: "osTicket", + unifi: "UniFi", }; function ColorList({ diff --git a/web/src/pages/settings/NotificationSettings.tsx b/web/src/pages/settings/NotificationSettings.tsx index 2a79cca..1b0ac31 100644 --- a/web/src/pages/settings/NotificationSettings.tsx +++ b/web/src/pages/settings/NotificationSettings.tsx @@ -82,7 +82,7 @@ const DIGEST_DAYS: { value: number; label: string }[] = [ { value: 6, label: "Saturday" }, { value: 0, label: "Sunday" }, ]; -const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3 }; +const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10 }; const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, day: 1, time: "08:00" }; type TestResult = { ok: boolean; message: string } | null; @@ -735,6 +735,15 @@ export default function NotificationSettings() { hint="From each agent server's own history, shown on the Alerts page and dashboard (not sent as a notification). Needs a few days of steady growth to say anything. 0 turns it off." onChange={(v) => setHealthChecks((h) => ({ ...h, diskForecastDays: v }))} /> + setHealthChecks((h) => ({ ...h, deviceOfflineMinutes: v }))} + /> ); @@ -59,7 +60,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) { const parse = (key: string) => { const [type, id] = key.split(":"); - return { type: type as "server" | "integration", id: Number(id) }; + return { type: type as "server" | "integration" | "device", id: Number(id) }; }; async function add(e: React.FormEvent) { @@ -95,7 +96,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) { return ( <>

- Say what needs what: Gitea needs the server it is installed on; a Proxmox guest needs the Proxmox it runs on. When the thing that is needed is down, what needs it is down too — and its alert is + Say what needs what: Gitea needs the server it is installed on; a Proxmox guest needs the Proxmox it runs on; a server needs the switch it is plugged into. When the thing that is needed is down, what needs it is down too — and its alert is held back under the first one on the Alerts page instead of adding to the noise. A service that was down for its own reasons still alerts once what it needs is back.

@@ -170,16 +171,18 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) { {data && data.runsOn.length > 0 && (
-

Servers that run on servers

+

Set elsewhere

+
+
+ A server’s “runs on” is set on the server itself, or worked out from the Proxmox node it is a guest of. A network device’s “connected through” is what its UniFi controller says. They count here too.
-
These are set on each server (“runs on”), or worked out from the Proxmox node it is a guest of. They count here too.
{data.runsOn.map((r) => ( ${r.to.key}`}> - + ))}
{r.from.name}runs on{r.from.key.startsWith("device:") && r.to.key.startsWith("device:") ? "is connected through" : "runs on"} {r.to.name}