node-red-contrib-unifi-ultimate 1.0.11 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
3
6
  const {
4
7
  buildBaseUrlFromHost,
5
8
  normalizePort,
@@ -27,6 +30,28 @@ module.exports = function(RED) {
27
30
  const MIN_POWER_OBSERVER_INTERVAL_SECONDS = 5;
28
31
  const DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS = 15;
29
32
  const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
33
+ const PORT_OVERRIDE_CACHE_VERSION = 1;
34
+ const PORT_OVERRIDE_CACHE_SAVE_DEBOUNCE_MS = 1000;
35
+ // Sentinel stored for a port that was enabled but had no override at all, so
36
+ // re-enabling knows to remove the override we added (instead of restoring one).
37
+ const PORT_OVERRIDE_NONE = { __noOverride: true };
38
+
39
+ function portOverrideCacheKey(deviceMac, portIdx) {
40
+ const mac = String(deviceMac || "").trim().toLowerCase();
41
+ const idx = Number(portIdx);
42
+ if (!mac || !Number.isFinite(idx)) {
43
+ return "";
44
+ }
45
+ return `${mac}|${Math.trunc(idx)}`;
46
+ }
47
+
48
+ function resolvePortOverrideCacheFile(nodeId) {
49
+ const dir = (RED.settings && RED.settings.userDir)
50
+ ? RED.settings.userDir
51
+ : os.tmpdir();
52
+ const safeId = String(nodeId || "shared").replace(/[^a-z0-9._-]/gi, "_");
53
+ return path.join(dir, `unifi-ultimate-portcache-${safeId}.json`);
54
+ }
30
55
 
31
56
  function normalizePowerObserverIntervalSeconds(value) {
32
57
  const parsed = Number(value);
@@ -98,6 +123,159 @@ module.exports = function(RED) {
98
123
  node.unofficialPollObserverTimer = null;
99
124
  node.unofficialPollObserverPollInProgress = false;
100
125
 
126
+ // Persistent mirror of each switch port's "last known enabled" override.
127
+ // Disabling a port destroys its VLAN/native-network config on the
128
+ // controller, so we cannot read it back to re-enable the port correctly.
129
+ // Instead we snapshot every port's override while it is still enabled —
130
+ // seeded at startup, refreshed on every device read, and persisted to disk
131
+ // so it survives Node-RED restarts. Keyed by `${mac}|${portIdx}`; the value
132
+ // is either the override object or PORT_OVERRIDE_NONE (enabled, no override).
133
+ node.portOverrideCache = new Map();
134
+ node.portOverrideCacheFile = resolvePortOverrideCacheFile(node.id);
135
+ node.portOverrideCacheSaveTimer = null;
136
+
137
+ function loadPortOverrideCache() {
138
+ try {
139
+ const raw = fs.readFileSync(node.portOverrideCacheFile, "utf8");
140
+ const data = JSON.parse(raw);
141
+ const entries = data && typeof data === "object" ? data.entries : null;
142
+ if (entries && typeof entries === "object") {
143
+ Object.keys(entries).forEach((key) => {
144
+ node.portOverrideCache.set(key, entries[key]);
145
+ });
146
+ }
147
+ } catch (error) {
148
+ // No cache file yet (or unreadable) — start empty.
149
+ }
150
+ }
151
+
152
+ function schedulePortOverrideCacheSave() {
153
+ if (node.portOverrideCacheSaveTimer || node.isClosing) {
154
+ return;
155
+ }
156
+ node.portOverrideCacheSaveTimer = setTimeout(() => {
157
+ node.portOverrideCacheSaveTimer = null;
158
+ try {
159
+ const entries = {};
160
+ node.portOverrideCache.forEach((value, key) => {
161
+ entries[key] = value;
162
+ });
163
+ fs.writeFileSync(
164
+ node.portOverrideCacheFile,
165
+ JSON.stringify({ version: PORT_OVERRIDE_CACHE_VERSION, entries }),
166
+ "utf8"
167
+ );
168
+ } catch (error) {
169
+ // Persistence is best-effort; the in-memory cache still works.
170
+ }
171
+ }, PORT_OVERRIDE_CACHE_SAVE_DEBOUNCE_MS);
172
+ if (typeof node.portOverrideCacheSaveTimer.unref === "function") {
173
+ node.portOverrideCacheSaveTimer.unref();
174
+ }
175
+ }
176
+
177
+ // Store the last known ENABLED override for a port. `override` is the raw
178
+ // override object, or null when the enabled port had no override at all.
179
+ node.rememberEnabledPortOverride = (deviceMac, portIdx, override) => {
180
+ const key = portOverrideCacheKey(deviceMac, portIdx);
181
+ if (!key) {
182
+ return;
183
+ }
184
+ const value = override
185
+ ? JSON.parse(JSON.stringify(override))
186
+ : { ...PORT_OVERRIDE_NONE };
187
+ node.portOverrideCache.set(key, value);
188
+ schedulePortOverrideCacheSave();
189
+ };
190
+
191
+ // Refresh the cache from a freshly fetched legacy device. Only ports that
192
+ // are currently enabled update the cache; a disabled port keeps whatever
193
+ // enabled snapshot we already have, so its VLAN can be restored later.
194
+ node.ingestPortOverridesFromDevice = (device) => {
195
+ if (!device || typeof device !== "object") {
196
+ return;
197
+ }
198
+ const mac = normalizeString(device.mac);
199
+ if (!mac) {
200
+ return;
201
+ }
202
+ const overridesByIdx = new Map();
203
+ (Array.isArray(device.port_overrides) ? device.port_overrides : []).forEach((override) => {
204
+ const idx = Number(override && override.port_idx);
205
+ if (Number.isFinite(idx)) {
206
+ overridesByIdx.set(Math.trunc(idx), override);
207
+ }
208
+ });
209
+ const indices = new Set();
210
+ (Array.isArray(device.port_table) ? device.port_table : []).forEach((port) => {
211
+ const idx = Number(port && port.port_idx);
212
+ if (Number.isFinite(idx)) {
213
+ indices.add(Math.trunc(idx));
214
+ }
215
+ });
216
+ overridesByIdx.forEach((_override, idx) => indices.add(idx));
217
+ indices.forEach((idx) => {
218
+ const override = overridesByIdx.get(idx) || null;
219
+ const forward = override ? normalizeString(override.forward) : "";
220
+ if (forward === "disabled") {
221
+ // Keep the last known enabled snapshot instead of overwriting it.
222
+ return;
223
+ }
224
+ node.rememberEnabledPortOverride(mac, idx, override);
225
+ });
226
+ };
227
+
228
+ // Return the remembered enabled override for a port (a deep clone so callers
229
+ // cannot mutate the cache), PORT_OVERRIDE_NONE when the enabled port had no
230
+ // override, or null when the port is unknown.
231
+ node.getEnabledPortOverride = (deviceMac, portIdx) => {
232
+ const key = portOverrideCacheKey(deviceMac, portIdx);
233
+ if (!key) {
234
+ return null;
235
+ }
236
+ const value = node.portOverrideCache.get(key);
237
+ if (!value) {
238
+ return null;
239
+ }
240
+ if (value.__noOverride) {
241
+ return { ...PORT_OVERRIDE_NONE };
242
+ }
243
+ return JSON.parse(JSON.stringify(value));
244
+ };
245
+
246
+ // Best-effort startup seed: read every site's devices once so the cache is
247
+ // populated with the current enabled configuration before any disable.
248
+ node.seedPortOverrideCache = async () => {
249
+ if (!String(node.getApiKey() || "").trim()) {
250
+ return;
251
+ }
252
+ let sites;
253
+ try {
254
+ sites = await node.fetchSites();
255
+ } catch (error) {
256
+ return;
257
+ }
258
+ for (const site of (Array.isArray(sites) ? sites : [])) {
259
+ if (node.isClosing) {
260
+ return;
261
+ }
262
+ const siteId = String(site && site.id || "").trim();
263
+ if (!siteId) {
264
+ continue;
265
+ }
266
+ try {
267
+ const devices = await fetchLegacyDevices(siteId);
268
+ (Array.isArray(devices) ? devices : []).forEach((device) => {
269
+ node.ingestPortOverridesFromDevice(device);
270
+ });
271
+ } catch (error) {
272
+ // Skip sites we cannot read; the cache still warms up on demand.
273
+ }
274
+ }
275
+ };
276
+
277
+ loadPortOverrideCache();
278
+
101
279
  function setNodeStatus(status) {
102
280
  if (!status || typeof status !== "object" || Array.isArray(status)) {
103
281
  return;
@@ -1343,10 +1521,18 @@ module.exports = function(RED) {
1343
1521
 
1344
1522
  async function fetchLegacyDevices(siteId) {
1345
1523
  const devices = await fetchLegacySiteCollection(siteId, "/stat/device");
1346
- return devices.map((device) => ({
1524
+ const mapped = devices.map((device) => ({
1347
1525
  ...device,
1348
1526
  siteId
1349
1527
  }));
1528
+ // Every device read is an opportunity to keep the port-override cache
1529
+ // aligned with the controller, so enable/disable can restore VLANs.
1530
+ try {
1531
+ mapped.forEach((device) => node.ingestPortOverridesFromDevice(device));
1532
+ } catch (error) {
1533
+ // Cache maintenance must never break the actual device fetch.
1534
+ }
1535
+ return mapped;
1350
1536
  }
1351
1537
 
1352
1538
  function buildLegacyClientSummary(client, siteId) {
@@ -3062,9 +3248,22 @@ module.exports = function(RED) {
3062
3248
 
3063
3249
  node.updateObserverDebugStatus();
3064
3250
 
3251
+ // Warm the port-override cache in the background so a first-ever disable
3252
+ // already has the port's enabled configuration recorded. Best-effort.
3253
+ setTimeout(() => {
3254
+ if (node.isClosing) {
3255
+ return;
3256
+ }
3257
+ node.seedPortOverrideCache().catch(() => {});
3258
+ }, 0);
3259
+
3065
3260
  node.on("close", function(done) {
3066
3261
  try {
3067
3262
  node.isClosing = true;
3263
+ if (node.portOverrideCacheSaveTimer) {
3264
+ clearTimeout(node.portOverrideCacheSaveTimer);
3265
+ node.portOverrideCacheSaveTimer = null;
3266
+ }
3068
3267
  node.nodeClients = [];
3069
3268
  node.powerObserverNodeState.clear();
3070
3269
  node.stopPowerObservationScheduler();
@@ -1358,7 +1358,7 @@
1358
1358
  <p><b>Control</b> chooses what is controlled on each target port:</p>
1359
1359
  <ul>
1360
1360
  <li><code>PoE</code> — controls Power-over-Ethernet on the port (the attached device keeps its link but loses/gains power).</li>
1361
- <li><code>Enable/Disable port</code> — administratively enables or disables the whole switch port, exactly like the UniFi <em>Port State</em> toggle. Disabling cuts <em>all</em> traffic and PoE on that port, disconnecting whatever is attached. Implemented through the UniFi port override <code>forward</code> field (verified against the controller): Disable sets <code>forward=disabled</code> and preserves the rest of the port config. Enable acts only on a disabled port (an already-enabled port is left untouched): it sets <code>forward=all</code> and, if the port had been disabled from the UniFi UI (which also blocks VLANs and clears the native network), it restores <code>tagged_vlan_mgmt=auto</code>, <code>port_security_enabled=false</code> and the site default native network.</li>
1361
+ <li><code>Enable/Disable port</code> — administratively enables or disables the whole switch port, exactly like the UniFi <em>Port State</em> toggle. Disabling cuts <em>all</em> traffic and PoE on that port, disconnecting whatever is attached. Implemented through the UniFi port override <code>forward</code> field (verified against the controller): Disable sets <code>forward=disabled</code> and preserves the rest of the port config. Enable acts only on a disabled port (an already-enabled port is left untouched): it re-enables a disabled port and restores its full configuration. The config node keeps a persistent cache of each port's last known <em>enabled</em> override (seeded at startup, refreshed on every device read and saved to disk so it survives restarts), and enable restores that whole snapshot — so the VLAN and every other property come back exactly as they were. If the port has never been seen enabled it falls back to a best-effort revert: <code>forward=all</code>, <code>tagged_vlan_mgmt=auto</code>, <code>port_security_enabled=false</code> and the site default native network.</li>
1362
1362
  </ul>
1363
1363
  <p><b>Action</b> is applied to <em>every</em> target in the list, and its choices depend on <b>Control</b>:</p>
1364
1364
  <ul>
@@ -538,23 +538,46 @@ module.exports = function(RED) {
538
538
  const portOverrides = sourceOverrides.map((port) => ({ ...port }));
539
539
  const existing = portOverrides.find((port) => Number(port && port.port_idx) === portIdx);
540
540
 
541
+ const sourcePort = Array.isArray(device && device.port_table)
542
+ ? device.port_table.find((port) => Number(port && port.port_idx) === portIdx)
543
+ : null;
544
+
541
545
  // `patch` may be a function so callers can decide the change based on
542
546
  // the current override (e.g. only re-enable a port that is actually
543
- // disabled, without clobbering its VLAN/forward configuration).
544
- const resolvedPatch = typeof patch === "function" ? patch(existing || null) : patch;
547
+ // disabled, without clobbering its VLAN/forward configuration). The
548
+ // live port_table entry and the whole device are passed too so callers
549
+ // can read state the override does not carry (e.g. the device MAC used
550
+ // to look up the remembered pre-disable override).
551
+ const resolvedPatch = typeof patch === "function" ? patch(existing || null, sourcePort || null, device) : patch;
545
552
  if (!resolvedPatch || Object.keys(resolvedPatch).length === 0) {
546
553
  return portOverrides;
547
554
  }
548
555
 
556
+ // Wholesale restore: replace the entire override for this port with the
557
+ // provided snapshot (used to bring a port back to its exact pre-disable
558
+ // config). Falls back to a plain push when there was no override yet.
559
+ if (resolvedPatch.__replaceOverride) {
560
+ const replacement = { ...resolvedPatch.__replaceOverride, port_idx: portIdx };
561
+ if (existing) {
562
+ portOverrides[portOverrides.indexOf(existing)] = replacement;
563
+ } else {
564
+ portOverrides.push(replacement);
565
+ }
566
+ return portOverrides;
567
+ }
568
+
569
+ // Wholesale removal: drop the override entirely so the port reverts to
570
+ // its port-profile / device defaults (used when the port had no
571
+ // override before this node disabled it).
572
+ if (resolvedPatch.__removeOverride) {
573
+ return portOverrides.filter((port) => Number(port && port.port_idx) !== portIdx);
574
+ }
575
+
549
576
  if (existing) {
550
577
  Object.assign(existing, resolvedPatch);
551
578
  return portOverrides;
552
579
  }
553
580
 
554
- const sourcePort = Array.isArray(device && device.port_table)
555
- ? device.port_table.find((port) => Number(port && port.port_idx) === portIdx)
556
- : null;
557
-
558
581
  portOverrides.push({
559
582
  port_idx: portIdx,
560
583
  portconf_id: sourcePort && sourcePort.portconf_id,
@@ -586,6 +609,18 @@ module.exports = function(RED) {
586
609
  throw new Error("Unable to resolve UniFi legacy device id.");
587
610
  }
588
611
 
612
+ // Feed the just-fetched (still authoritative) device into the config
613
+ // node's port-override cache before we change anything. This keeps the
614
+ // "last known enabled" snapshot fresh so a later re-enable can restore
615
+ // the exact pre-disable configuration.
616
+ if (typeof node.server.ingestPortOverridesFromDevice === "function") {
617
+ try {
618
+ node.server.ingestPortOverridesFromDevice(legacyDevice);
619
+ } catch (error) {
620
+ // Cache maintenance is best-effort; never block the actual action.
621
+ }
622
+ }
623
+
589
624
  const path = `/api/s/${encodeURIComponent(legacySiteName)}/rest/device/${encodeURIComponent(legacyDevice._id)}`;
590
625
  const portOverrides = buildPortOverrides(legacyDevice, portIdx, patch);
591
626
  setNodeStatus({ fill: "blue", shape: "dot", text: statusText });
@@ -668,7 +703,10 @@ module.exports = function(RED) {
668
703
  // (verified against the controller). forward=disabled alone can be
669
704
  // rejected/ineffective while the native network and VLANs are still
670
705
  // set, so apply the full bundle: block VLANs, clear the native
671
- // network and turn on port security.
706
+ // network and turn on port security. The port's pre-disable config
707
+ // has already been captured into the config-node cache by
708
+ // applyLegacyPortOverridePatch (before this patch runs), so enabling
709
+ // can restore it later.
672
710
  patch = {
673
711
  forward: "disabled",
674
712
  tagged_vlan_mgmt: "block_all",
@@ -677,14 +715,36 @@ module.exports = function(RED) {
677
715
  };
678
716
  } else {
679
717
  // Enable only acts on a disabled port (never clobbers an enabled
680
- // one). Besides forward=all, undo the extra hardening the UI adds
681
- // when it disables a port (VLAN block + port security) and restore
682
- // the native network to the site default when it was cleared.
718
+ // one). If the config node remembers the port's last known enabled
719
+ // override, restore it wholesale so every property (VLAN and
720
+ // anything else, now or in the future) comes back exactly as it was.
721
+ // Otherwise fall back to a best-effort revert (used when we have no
722
+ // record of the port at all): undo the UI hardening and restore the
723
+ // site default native network.
683
724
  const defaultNativeId = await fetchDefaultNativeNetworkId(scoped);
684
- patch = (existing) => {
725
+ const lookupRemembered = (device) => {
726
+ if (!device || typeof node.server.getEnabledPortOverride !== "function") {
727
+ return null;
728
+ }
729
+ try {
730
+ return node.server.getEnabledPortOverride(device.mac, portIdx);
731
+ } catch (error) {
732
+ return null;
733
+ }
734
+ };
735
+ patch = (existing, _sourcePort, device) => {
685
736
  if (!existing || String(existing.forward) !== "disabled") {
686
737
  return {};
687
738
  }
739
+ const remembered = lookupRemembered(device);
740
+ if (remembered && remembered.__noOverride) {
741
+ // The port had no override while enabled — remove the one we
742
+ // added on disable so it reverts to its profile/defaults.
743
+ return { __removeOverride: true };
744
+ }
745
+ if (remembered) {
746
+ return { __replaceOverride: remembered };
747
+ }
688
748
  const recover = {
689
749
  forward: "all",
690
750
  tagged_vlan_mgmt: "auto",
@@ -718,7 +718,13 @@
718
718
  <p><b>Network</b> selects the L3 network / VLAN to watch. The list comes from the networks configured on your controller. This is the only required field — sensible defaults handle the rest.</p>
719
719
  <p><b>Emit current clients on start</b>, when enabled, emits a <code>joined</code> event for every client already on the network at deploy. Disabled (default) only reports later changes.</p>
720
720
  <p>The node automatically debounces events (a client must be seen for a couple of polls before <code>joined</code>/<code>left</code> fires) to absorb the transient flapping UniFi shows while it classifies a freshly connected client. Polling cadence and debounce use built-in defaults.</p>
721
- <p><b>Note on timing:</b> a newly connected client can take up to about a minute to appear on its network in the UniFi data (especially guest networks), so a <code>joined</code> event may lag the physical connection. This is a controller-side limitation. Leaves are detected quickly.</p>
721
+ <p><b>Note on timing:</b> a newly connected client can take up to about a minute to appear on its network in the UniFi data (especially guest networks), so a <code>joined</code> event may lag the physical connection. This is a controller-side limitation.</p>
722
+ <p><b>Note on duplicate events:</b> you may see repeated <code>joined</code>/<code>left</code> for the same device. This comes from the UniFi controller itself, not the node:</p>
723
+ <ul>
724
+ <li><b>UniFi client flapping</b> — a well-known controller behaviour where clients are shown repeatedly connecting/disconnecting (band steering, load balancing, fast roaming, weak signal). During a single reconnect the client can bounce in and out of its network for ~1 minute before settling.</li>
725
+ <li><b>Wi‑Fi MAC randomization (Private Address)</b> — phones/tablets present a different MAC over time, so the same physical device looks like a new client joining while the old MAC leaves. This is common on guest networks.</li>
726
+ </ul>
727
+ <p>The node reports the controller's data faithfully and applies a small built-in debounce, but it cannot fully remove this upstream noise. If duplicates are a problem, debounce in your flow — for example an <code>rbe</code> ("block unless value changes") node, or a <code>delay</code> node in rate-limit mode, keyed on <code>msg.deviceName</code>/<code>msg.payload.mac</code>.</p>
722
728
 
723
729
  <p>In <b>presence</b> mode, <b>Poll (s)</b> sets the check cadence. <b>Name</b> is the node name shown in the editor. Request timeout is handled automatically.</p>
724
730
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.0.11",
3
+ "version": "1.1.0",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",