node-red-contrib-unifi-ultimate 1.1.12 → 1.1.14

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.
@@ -79,6 +79,7 @@ module.exports = function(RED) {
79
79
  node.isClosing = false;
80
80
  node.activeDoorbells = new Map();
81
81
  node.activeDoorbellRequests = new Map();
82
+ node.doorbellStateUpdatedAt = new Map();
82
83
  node.doorbellLogPollTimer = null;
83
84
  node.doorbellLogPollInFlight = false;
84
85
  node.doorbellLogPollCursor = 0;
@@ -243,25 +244,23 @@ module.exports = function(RED) {
243
244
 
244
245
  const normalizedEntry = entry && typeof entry === "object" ? { ...entry } : {};
245
246
  normalizedEntry.requestId = normalizeString(normalizedEntry.requestId);
247
+ normalizedEntry.updatedAt = Number(normalizedEntry.updatedAt) || Date.now();
246
248
  node.activeDoorbells.set(normalizedId, normalizedEntry);
249
+ node.doorbellStateUpdatedAt.set(normalizedId, normalizedEntry.updatedAt);
247
250
 
248
251
  if (normalizedEntry.requestId) {
249
252
  node.activeDoorbellRequests.set(normalizedEntry.requestId, normalizedId);
250
253
  }
251
254
  };
252
255
 
253
- node.clearActiveDoorbell = (deviceId, expectedRequestIds) => {
256
+ node.clearActiveDoorbell = (deviceId, expectedRequestIds, updatedAt = Date.now()) => {
254
257
  const normalizedId = normalizeString(deviceId);
255
258
  if (!normalizedId) {
256
259
  return false;
257
260
  }
258
261
 
259
262
  const current = node.activeDoorbells.get(normalizedId);
260
- if (!current) {
261
- return false;
262
- }
263
-
264
- const requestId = normalizeString(current.requestId);
263
+ const requestId = normalizeString(current && current.requestId);
265
264
  const expectedIds = Array.isArray(expectedRequestIds)
266
265
  ? expectedRequestIds.map((value) => normalizeString(value)).filter(Boolean)
267
266
  : [];
@@ -271,6 +270,16 @@ module.exports = function(RED) {
271
270
  return false;
272
271
  }
273
272
 
273
+ // Remember completions even without an active entry: a delayed
274
+ // incoming log must not re-enable cancel for a call that has ended.
275
+ node.doorbellStateUpdatedAt.set(normalizedId, Math.max(
276
+ node.doorbellStateUpdatedAt.get(normalizedId) || 0,
277
+ updatedAt
278
+ ));
279
+ if (!current) {
280
+ return false;
281
+ }
282
+
274
283
  node.activeDoorbells.delete(normalizedId);
275
284
  if (requestId && node.activeDoorbellRequests.get(requestId) === normalizedId) {
276
285
  node.activeDoorbellRequests.delete(requestId);
@@ -407,15 +416,31 @@ module.exports = function(RED) {
407
416
  const eventType = normalizeEventName(event.type);
408
417
  const logKey = normalizeEventName(event.log_key);
409
418
  const deviceId = node.extractDoorbellDeviceIdFromLogEntry(entry);
419
+ const isIncoming = eventType === DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST;
420
+ const isCompleted = eventType === DOORBELL_LOG_EVENT_DOOR_UNLOCK && logKey.includes("access.doorbell.");
421
+ const publishedMs = Number(event.published);
422
+
423
+ // Logs are historical evidence. Without a timestamp they cannot
424
+ // safely establish that a ring is still active.
425
+ if ((!isIncoming && !isCompleted) || !deviceId || !Number.isFinite(publishedMs) || publishedMs <= 0) {
426
+ return false;
427
+ }
428
+
429
+ const current = node.getActiveDoorbell(deviceId);
430
+ const lastUpdatedAt = node.doorbellStateUpdatedAt.get(deviceId) || 0;
431
+ if (publishedMs < lastUpdatedAt || (isIncoming && publishedMs === lastUpdatedAt)) {
432
+ return false;
433
+ }
410
434
 
411
435
  // Doorbell request log means a ring has just started.
412
- if (eventType === DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST) {
413
- if (!deviceId) {
436
+ if (isIncoming) {
437
+ // Polling is a fallback, not a replacement for a live call.
438
+ // Overwriting it loses the websocket request id and reduces
439
+ // its lifetime from three minutes to the 25-second log window.
440
+ if (current && current.source !== "logs") {
414
441
  return false;
415
442
  }
416
443
 
417
- const published = Number(event.published);
418
- const publishedMs = Number.isFinite(published) && published > 0 ? published : Date.now();
419
444
  const expiresAt = Math.min(
420
445
  publishedMs + DOORBELL_LOG_ACTIVE_WINDOW_MS,
421
446
  Date.now() + DOORBELL_LOG_ACTIVE_WINDOW_MS
@@ -437,11 +462,8 @@ module.exports = function(RED) {
437
462
  // Access writes call-end outcomes as access.door.unlock with a
438
463
  // doorbell-specific log key (for example "missed"). Treat those as
439
464
  // completion signals and clear the tracked ring.
440
- if (eventType === DOORBELL_LOG_EVENT_DOOR_UNLOCK && logKey.includes("access.doorbell.")) {
441
- if (!deviceId) {
442
- return false;
443
- }
444
- node.clearActiveDoorbell(deviceId);
465
+ if (isCompleted) {
466
+ node.clearActiveDoorbell(deviceId, [], publishedMs);
445
467
  return true;
446
468
  }
447
469
 
@@ -473,7 +495,13 @@ module.exports = function(RED) {
473
495
  }
474
496
 
475
497
  const logPayload = extractAccessData(response.payload);
476
- const hits = Array.isArray(logPayload && logPayload.hits) ? logPayload.hits : [];
498
+ // Access returns newest-first batches. Apply starts before their
499
+ // corresponding completions, independent of API response order.
500
+ const hits = Array.isArray(logPayload && logPayload.hits)
501
+ ? logPayload.hits.slice().sort((left, right) =>
502
+ (Number(left && left._source && left._source.event && left._source.event.published) || 0)
503
+ - (Number(right && right._source && right._source.event && right._source.event.published) || 0))
504
+ : [];
477
505
  let matchedEvents = 0;
478
506
 
479
507
  for (const entry of hits) {
@@ -558,7 +586,12 @@ module.exports = function(RED) {
558
586
  Array.from(node.activeDoorbells.entries()).forEach(([deviceId, entry]) => {
559
587
  const expiresAt = Number(entry && entry.expiresAt);
560
588
  if (Number.isFinite(expiresAt) && expiresAt > 0 && expiresAt <= now) {
561
- node.clearActiveDoorbell(deviceId);
589
+ node.clearActiveDoorbell(deviceId, [], expiresAt);
590
+ }
591
+ });
592
+ node.doorbellStateUpdatedAt.forEach((updatedAt, deviceId) => {
593
+ if (updatedAt + ACTIVE_DOORBELL_TTL_MS <= now) {
594
+ node.doorbellStateUpdatedAt.delete(deviceId);
562
595
  }
563
596
  });
564
597
  };
@@ -600,8 +633,7 @@ module.exports = function(RED) {
600
633
  node.markDoorbellCanceled = (deviceId) => {
601
634
  const normalizedId = normalizeString(deviceId);
602
635
  if (!normalizedId) {
603
- node.activeDoorbells.clear();
604
- node.activeDoorbellRequests.clear();
636
+ Array.from(node.activeDoorbells.keys()).forEach((id) => node.clearActiveDoorbell(id));
605
637
  return;
606
638
  }
607
639
 
@@ -736,6 +768,7 @@ module.exports = function(RED) {
736
768
  node.isClosing = true;
737
769
  node.activeDoorbells.clear();
738
770
  node.activeDoorbellRequests.clear();
771
+ node.doorbellStateUpdatedAt.clear();
739
772
  node.closeWebSocket();
740
773
  node.stopDoorbellLogPolling();
741
774
  } catch (error) {
@@ -1155,7 +1155,7 @@
1155
1155
  <p>For <code>Set Temporary Lock Rule</code>, choose <code>Custom Duration</code> to reveal the minutes field. Legacy <code>ended_time</code> is still available only as fallback compatibility.</p>
1156
1156
  <p><code>Receive Events</code> fetches the current state once and then subscribes to events provided by the shared UniFi Access config node. The config node maintains the official notifications WebSocket and fans out events to runtime nodes. In this mode, <code>All</code> emits every event for the selected device/door, while specific <code>Event</code> choices filter to official UniFi Access event families (for example doorbell, door unlock, DPS, emergency, schedule, and temporary unlock events). The input pin is hidden and listening starts automatically after deploy/restart.</p>
1157
1157
  <p><code>Trigger Doorbell</code> and <code>Cancel Doorbell</code> use a manual <code>Room Name</code> field when needed. The node does not currently discover Intercom directory names automatically.</p>
1158
- <p><code>Cancel Doorbell</code> uses a shared safe-cancel guard in the UniFi Access config node with a 3 minute tracking window. Tracking is updated by websocket events and a fallback system-log poller.</p>
1158
+ <p><code>Cancel Doorbell</code> only runs while the selected device has a tracked active ring. WebSocket events and <code>Trigger Doorbell</code> requests are tracked for up to 3 minutes, or until the call ends. A fallback system-log poller requires <code>view:system_log</code> permission and uses a shorter 25 second window when no live call is tracked; it does not shorten live tracking. Delayed logs cannot reactivate a completed call or clear a newer one.</p>
1159
1159
  <p>Visitors support state reads and the official visitor-status event. Access policies, schedules, holiday groups, and door groups are read-only. <code>Read Door Group Topology</code> returns the complete hierarchy documented by Access.</p>
1160
1160
  <p><code>Recent System Log</code> lists entries from the previous 24 hours, up to the first 200 results. It is read-only and requires the token's <code>view:system_log</code> permission.</p>
1161
1161
  <p><b>Emit periodically</b> repeats read-only actions at the selected interval and sends each result to the flow. It is hidden for <code>Receive Events</code> and write actions.</p>
@@ -21,9 +21,7 @@
21
21
  rejectUnauthorized: { value: false }
22
22
  },
23
23
  credentials: {
24
- apiKey: { type: "password", required: true },
25
- historyUsername: { type: "text" },
26
- historyPassword: { type: "password" }
24
+ apiKey: { type: "password", required: true }
27
25
  },
28
26
  label: function () {
29
27
  return this.name || this.host || "Unifi Protect Config";
@@ -33,13 +31,9 @@
33
31
  const $hostInput = $("#node-config-input-host");
34
32
  const $port = $("#node-config-input-port");
35
33
  const $apiKey = $("#node-config-input-apiKey");
36
- const $historyUsername = $("#node-config-input-historyUsername");
37
34
  const $allowSelfSigned = $("#node-config-input-allowSelfSigned");
38
35
  const $portRow = $port.closest(".form-row");
39
36
  const $apiKeyRow = $apiKey.closest(".form-row");
40
- const $historyUsernameRow = $historyUsername.closest(".form-row");
41
- const $historyPasswordRow = $("#node-config-input-historyPassword").closest(".form-row");
42
- const $historyHintRow = $("#node-config-row-history-hint");
43
37
  const $securityRow = $allowSelfSigned.closest(".form-row");
44
38
  const $advancedRow = $("#node-config-row-advanced");
45
39
 
@@ -53,9 +47,6 @@
53
47
  const hasHost = String($hostInput.val() || node.host || "").trim() !== "";
54
48
  $portRow.toggle(hasHost);
55
49
  $apiKeyRow.toggle(hasHost);
56
- $historyUsernameRow.toggle(hasHost);
57
- $historyPasswordRow.toggle(hasHost);
58
- $historyHintRow.toggle(hasHost);
59
50
  $securityRow.toggle(hasHost);
60
51
  $advancedRow.toggle(hasHost);
61
52
  }
@@ -103,18 +94,6 @@
103
94
  <label for="node-config-input-apiKey"><i class="fa fa-key"></i> API Key</label>
104
95
  <input type="password" id="node-config-input-apiKey" placeholder="Paste your UniFi Protect API key">
105
96
  </div>
106
- <div id="node-config-row-history-hint" class="form-row">
107
- <label><i class="fa fa-history"></i> History</label>
108
- <span>Optional local UniFi OS account for recorded events and event snapshots</span>
109
- </div>
110
- <div class="form-row">
111
- <label for="node-config-input-historyUsername"><i class="fa fa-user"></i> History user</label>
112
- <input type="text" id="node-config-input-historyUsername" autocomplete="username" placeholder="Local UniFi OS username">
113
- </div>
114
- <div class="form-row">
115
- <label for="node-config-input-historyPassword"><i class="fa fa-lock"></i> History password</label>
116
- <input type="password" id="node-config-input-historyPassword" autocomplete="current-password" placeholder="Local UniFi OS password">
117
- </div>
118
97
  <div class="form-row">
119
98
  <label for="node-config-input-allowSelfSigned"><i class="fa fa-lock"></i> Security</label>
120
99
  <input type="checkbox" id="node-config-input-allowSelfSigned" style="display:inline-block; width:auto; vertical-align:top;">
@@ -137,7 +116,7 @@
137
116
  <p><b>Controller</b> accepts the UniFi OS host or IP address. The node builds the Protect integration URL automatically.</p>
138
117
  <p><b>Port</b> is optional. Leave it empty to use the default <code>443</code>. Set it when your UniFi OS server listens on a custom port (for example <code>11443</code>). A port embedded directly in the Controller field (<code>host:port</code>) takes precedence over this field.</p>
139
118
  <p><b>API Key</b> is required for authentication and is sent automatically as <code>X-API-Key</code>.</p>
140
- <p><b>History user/password</b> are optional and enable recorded-event searches and event thumbnails for Cerebrum/KNX AI. Enter a dedicated <b>local UniFi OS account</b> that can view the required Protect cameras. The official Integration API key covers live events and current snapshots but does not expose the recorded-event archive. These credentials remain in the Node-RED credential store; the camera adapter never publishes them.</p>
119
+ <p>Recorded-event searches require a dedicated local UniFi OS account. Those history credentials belong to the calling consumer (for example Cerebrum), are supplied only with the individual history request, and are never stored by this config node. The official Integration API key covers live events and current snapshots but does not expose the recorded-event archive.</p>
141
120
  <p><b>Security</b> &mdash; <b>Allow self-signed certificate</b> is enabled by default because UniFi controllers almost always present a self-signed certificate. Leave it checked for UniFi OS setups. Uncheck it only if your controller serves a certificate signed by a trusted certificate authority and you want strict verification.</p>
142
121
  <p><b>Name</b> is the config node name shown in the editor.</p>
143
122
 
@@ -147,6 +126,6 @@
147
126
 
148
127
  <h3>Automatic KNX AI camera adapter</h3>
149
128
  <p>If <code>node-red-contrib-knx-ultimate</code> is installed, this config node automatically publishes its available cameras to the KNX AI chat runtime. No Protect Device node, camera selector, or wire to KNX AI is required.</p>
150
- <p>KNX AI and Cerebrum can request snapshots directly and subscribe to motion, smart line, intrusion-zone, and loiter-zone events. When the optional local history credentials are configured, they can also search recorded events with explicit pagination and retrieve the JPEG thumbnail belonging to an exact event. Persistent notification rules remain owned by the AI chat context. API keys, credentials, cookies, and raw controller responses stay private inside this config node.</p>
129
+ <p>KNX AI and Cerebrum can request snapshots directly and subscribe to motion, smart line, intrusion-zone, and loiter-zone events. A caller that supplies <code>{ historyCredentials }</code> as the separate second argument of an individual history operation can also search recorded events with explicit pagination and retrieve the JPEG thumbnail belonging to an exact event. The provider neither stores nor returns those credentials; its temporary login session exists only for that operation. Persistent notification rules remain owned by the AI chat context. API keys, credentials, cookies, and raw controller responses stay private.</p>
151
130
  <p>The provider uses the generic <code>node-red.knx-ai.camera-adapters.v1</code> runtime contract, allowing other camera suites to expose the same capabilities independently.</p>
152
131
  </script>
@@ -202,67 +202,110 @@ module.exports = function(RED) {
202
202
  node.knxAiCameraRefresh = null;
203
203
  node.knxAiCameraRefreshAgain = false;
204
204
  node.knxAiCameraListeners = new Set();
205
- node.protectHistorySessionHeaders = null;
206
- node.protectHistoryAuthentication = null;
207
205
  node.protectHistoryPaginationGuard = createProtectHistoryPaginationGuard();
208
206
  node.protectCameraEventDeduper = createProtectCameraEventDeduper();
209
207
 
210
- node.getApiKey = () => node.credentials && node.credentials.apiKey;
208
+ // Historical credentials used to belong to this config node. Remove any
209
+ // legacy values from the runtime credential cache so a subsequent deploy
210
+ // also removes them from Node-RED's encrypted credential file. History
211
+ // callers now own those credentials and provide them for each operation.
212
+ if (node.credentials && typeof node.credentials === "object") {
213
+ const hadLegacyHistoryCredentials = Object.prototype.hasOwnProperty.call(node.credentials, "historyUsername")
214
+ || Object.prototype.hasOwnProperty.call(node.credentials, "historyPassword");
215
+ if (hadLegacyHistoryCredentials) {
216
+ const apiKey = node.credentials.apiKey;
217
+ node.credentials = apiKey === undefined ? {} : { apiKey };
218
+ if (RED.nodes && typeof RED.nodes.addCredentials === "function") {
219
+ // Do not log either the old credentials or failures from this
220
+ // best-effort migration. Node-RED persists the sanitized cache
221
+ // through its normal encrypted credential/deploy lifecycle.
222
+ Promise.resolve(RED.nodes.addCredentials(node.id, node.credentials)).catch(() => { });
223
+ }
224
+ }
225
+ }
211
226
 
212
- node.getHistoryCredentials = () => ({
213
- username: String(node.credentials && node.credentials.historyUsername || "").trim(),
214
- password: String(node.credentials && node.credentials.historyPassword || "")
215
- });
227
+ node.getApiKey = () => node.credentials && node.credentials.apiKey;
216
228
 
217
- node.hasHistoryCredentials = () => {
218
- const credentials = node.getHistoryCredentials();
219
- return Boolean(credentials.username && credentials.password);
229
+ const providerIsConfigured = () => Boolean(node.baseUrl && node.getApiKey());
230
+ node.knxAiCameraProviderHealth = {
231
+ connected: false,
232
+ ready: false,
233
+ status: providerIsConfigured() ? "degraded" : "unavailable",
234
+ checkedAt: "",
235
+ lastSeenAt: "",
236
+ lastError: providerIsConfigured()
237
+ ? "The UniFi Protect camera catalog has not been checked yet."
238
+ : "The UniFi Protect host or API key is not configured."
239
+ };
240
+ node.updateKnxAiCameraProviderHealth = ({ ok, error } = {}) => {
241
+ const checkedAt = new Date().toISOString();
242
+ const configured = providerIsConfigured() && !node.isClosing;
243
+ const healthy = configured && ok === true;
244
+ const message = healthy
245
+ ? ""
246
+ : String(error && (error.message || error) || (configured
247
+ ? "The UniFi Protect camera catalog is unavailable."
248
+ : "The UniFi Protect host or API key is not configured."));
249
+ node.knxAiCameraProviderHealth = {
250
+ connected: healthy,
251
+ ready: healthy,
252
+ status: healthy ? "healthy" : "unavailable",
253
+ checkedAt,
254
+ lastSeenAt: healthy ? checkedAt : node.knxAiCameraProviderHealth.lastSeenAt,
255
+ lastError: message.slice(0, 500)
256
+ };
220
257
  };
221
258
 
222
- node.authenticateProtectHistory = async () => {
223
- if (node.protectHistorySessionHeaders) return node.protectHistorySessionHeaders;
224
- if (node.protectHistoryAuthentication) return node.protectHistoryAuthentication;
225
- const authentication = Promise.resolve().then(async () => {
226
- const credentials = node.getHistoryCredentials();
227
- if (!credentials.username || !credentials.password) {
228
- const error = new Error("UniFi Protect historical events require the optional local history username and password in the Protect config node.");
229
- error.code = "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED";
230
- throw error;
231
- }
232
- if (!node.controllerBaseUrl) throw new Error("The configured IP is empty or invalid.");
233
- const headers = {
234
- Accept: "application/json",
235
- "Content-Type": "application/json"
236
- };
237
- const body = buildRequestBody(headers, "POST", {
238
- username: credentials.username,
239
- password: credentials.password,
240
- rememberMe: false
241
- });
242
- const response = await doRequest(new URL(`${node.controllerBaseUrl}/api/auth/login`), {
243
- method: "POST",
244
- headers,
245
- timeout: 15000,
246
- rejectUnauthorized: node.rejectUnauthorized
247
- }, body);
248
- if (response.statusCode < 200 || response.statusCode >= 300) {
249
- const detail = extractProtectErrorDetail(response);
250
- const error = new Error(`UniFi OS login for Protect history failed (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
251
- error.code = "UNIFI_PROTECT_HISTORY_LOGIN_FAILED";
252
- error.statusCode = Number(response.statusCode) || 0;
253
- throw error;
254
- }
255
- node.protectHistorySessionHeaders = extractProtectHistorySessionHeaders(response);
256
- return node.protectHistorySessionHeaders;
257
- }).finally(() => {
258
- if (node.protectHistoryAuthentication === authentication) node.protectHistoryAuthentication = null;
259
+ node.authenticateProtectHistory = async (historyCredentials) => {
260
+ const source = historyCredentials && typeof historyCredentials === "object" && !Array.isArray(historyCredentials)
261
+ ? historyCredentials
262
+ : {};
263
+ const username = String(source.username || "").trim();
264
+ const password = String(source.password || "");
265
+ if (!username || !password) {
266
+ const error = new Error("UniFi Protect historical events require a local history username and password supplied by the caller.");
267
+ error.code = "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED";
268
+ throw error;
269
+ }
270
+ if (!node.controllerBaseUrl) throw new Error("The configured IP is empty or invalid.");
271
+ const headers = {
272
+ Accept: "application/json",
273
+ "Content-Type": "application/json"
274
+ };
275
+ const body = buildRequestBody(headers, "POST", {
276
+ username,
277
+ password,
278
+ rememberMe: false
259
279
  });
260
- node.protectHistoryAuthentication = authentication;
261
- return authentication;
280
+ const response = await doRequest(new URL(`${node.controllerBaseUrl}/api/auth/login`), {
281
+ method: "POST",
282
+ headers,
283
+ timeout: 15000,
284
+ rejectUnauthorized: node.rejectUnauthorized
285
+ }, body);
286
+ if (response.statusCode < 200 || response.statusCode >= 300) {
287
+ // Controller error bodies are deliberately excluded: some UniFi
288
+ // versions may echo submitted login fields in diagnostic details.
289
+ const error = new Error(`UniFi OS login for Protect history failed (HTTP ${response.statusCode || "unknown"}).`);
290
+ error.code = "UNIFI_PROTECT_HISTORY_LOGIN_FAILED";
291
+ error.statusCode = Number(response.statusCode) || 0;
292
+ throw error;
293
+ }
294
+ return extractProtectHistorySessionHeaders(response);
262
295
  };
263
296
 
264
- node.executeProtectHistoryRequest = async ({ path, method = "GET", query, headers, payload, timeout = 20000 } = {}, retryAuthentication = true) => {
265
- const sessionHeaders = await node.authenticateProtectHistory();
297
+ node.executeProtectHistoryRequest = async (
298
+ { path, method = "GET", query, headers, payload, timeout = 20000 } = {},
299
+ { historyCredentials, retryAuthentication = true } = {},
300
+ callSession = {}
301
+ ) => {
302
+ // The session may be reused only by HTTP attempts belonging to one
303
+ // provider operation (for example delayed thumbnail retries). This
304
+ // object is local to that operation and never retained on the node.
305
+ if (!callSession.sessionHeaders) {
306
+ callSession.sessionHeaders = await node.authenticateProtectHistory(historyCredentials);
307
+ }
308
+ const sessionHeaders = callSession.sessionHeaders;
266
309
  const normalizedPath = String(path || "").replace(/^\/+/, "");
267
310
  const requestUrl = new URL(`${node.controllerBaseUrl}/proxy/protect/api/${normalizedPath}${buildQueryString(query)}`);
268
311
  const requestMethod = String(method || "GET").toUpperCase();
@@ -275,10 +318,17 @@ module.exports = function(RED) {
275
318
  rejectUnauthorized: node.rejectUnauthorized
276
319
  }, requestBody);
277
320
  const refreshedCsrf = response && response.headers && response.headers["x-csrf-token"];
278
- if (refreshedCsrf && node.protectHistorySessionHeaders) node.protectHistorySessionHeaders["X-CSRF-Token"] = String(refreshedCsrf);
279
- if (Number(response && response.statusCode) === 401 && retryAuthentication) {
280
- node.protectHistorySessionHeaders = null;
281
- return node.executeProtectHistoryRequest({ path, method, query, headers, payload, timeout }, false);
321
+ if (refreshedCsrf) callSession.sessionHeaders["X-CSRF-Token"] = String(refreshedCsrf);
322
+ if (Number(response && response.statusCode) === 401
323
+ && retryAuthentication
324
+ && callSession.authenticationRetries !== 1) {
325
+ callSession.authenticationRetries = 1;
326
+ callSession.sessionHeaders = null;
327
+ return node.executeProtectHistoryRequest(
328
+ { path, method, query, headers, payload, timeout },
329
+ { historyCredentials, retryAuthentication: false },
330
+ callSession
331
+ );
282
332
  }
283
333
  return response;
284
334
  };
@@ -460,7 +510,11 @@ module.exports = function(RED) {
460
510
  };
461
511
  }).filter((camera) => camera.nativeCameraId);
462
512
  node.knxAiCameraCache = { at: Date.now(), cameras };
513
+ node.updateKnxAiCameraProviderHealth({ ok: true });
463
514
  return cameras;
515
+ }).catch((error) => {
516
+ node.updateKnxAiCameraProviderHealth({ ok: false, error });
517
+ throw error;
464
518
  }).finally(() => {
465
519
  if (node.knxAiCameraRefresh !== refresh) return;
466
520
  node.knxAiCameraRefresh = null;
@@ -553,10 +607,14 @@ module.exports = function(RED) {
553
607
  };
554
608
  };
555
609
 
556
- node.queryKnxAiCameraEvents = async (request = {}) => {
610
+ node.queryKnxAiCameraEvents = async (request = {}, { historyCredentials, historyQueryScope } = {}) => {
557
611
  const normalized = normalizeProtectHistoryRequest(request);
558
612
  const requestSource = request && typeof request === "object" && !Array.isArray(request) ? request : {};
559
613
  const paginationKey = JSON.stringify({
614
+ // This is an opaque, non-secret caller id (for example a
615
+ // Cerebrum node id). It prevents otherwise identical paginated
616
+ // searches from different callers contaminating each other.
617
+ historyQueryScope: String(historyQueryScope || "").trim().slice(0, 200),
560
618
  cameraId: normalized.cameraId,
561
619
  cameraName: normalized.cameraName,
562
620
  start: requestSource.from !== undefined || requestSource.start !== undefined ? normalized.start : "default",
@@ -570,12 +628,15 @@ module.exports = function(RED) {
570
628
  const response = await node.executeProtectHistoryRequest({
571
629
  path: "events",
572
630
  method: "GET",
573
- query: normalized.query,
631
+ query: Object.assign({}, normalized.query, requestedCamera
632
+ ? { cameras: [requestedCamera.nativeCameraId] }
633
+ : {}),
574
634
  timeout: 25000
575
- });
635
+ }, { historyCredentials });
576
636
  if (response.statusCode < 200 || response.statusCode >= 300) {
577
- const detail = extractProtectErrorDetail(response);
578
- throw new Error(`Unable to retrieve UniFi Protect historical events (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
637
+ // History responses are source-owned and may contain sensitive
638
+ // controller diagnostics. Expose only the status code upstream.
639
+ throw new Error(`Unable to retrieve UniFi Protect historical events (HTTP ${response.statusCode || "unknown"}).`);
579
640
  }
580
641
  const payload = Array.isArray(response.payload)
581
642
  ? response.payload
@@ -614,7 +675,11 @@ module.exports = function(RED) {
614
675
  return Object.assign({}, event, {
615
676
  endAt: Number.isFinite(parsedEnd) ? new Date(parsedEnd).toISOString() : "",
616
677
  score: Number.isFinite(Number(item.score)) ? Number(item.score) : null,
617
- thumbnailAvailable: Boolean(item.thumbnail || item.thumbnailId)
678
+ // Protect does not consistently include thumbnail/thumbnailId
679
+ // in historical event rows even though the event-id endpoint
680
+ // can return the JPEG. The endpoint is the authoritative
681
+ // availability check; an exact event id is enough to try it.
682
+ thumbnailAvailable: Boolean(event.eventId)
618
683
  });
619
684
  }).filter(Boolean);
620
685
  const selected = selectProtectHistoryEvents(events, Object.assign({}, normalized, {
@@ -643,23 +708,27 @@ module.exports = function(RED) {
643
708
  };
644
709
  };
645
710
 
646
- node.takeKnxAiCameraEventSnapshot = async ({ eventId } = {}) => {
647
- const id = String(eventId || "").trim().replace(/^e-/, "");
711
+ node.takeKnxAiCameraEventSnapshot = async (request = {}, { historyCredentials } = {}) => {
712
+ const requestSource = request && typeof request === "object" && !Array.isArray(request) ? request : {};
713
+ const id = String(requestSource.eventId || "").trim().replace(/^e-/, "");
648
714
  if (!id || id.length > 200) throw new Error("A valid UniFi Protect event id is required.");
649
715
  let response;
716
+ // This session is scoped to the current provider invocation and lets
717
+ // 404 thumbnail retries avoid creating additional UniFi OS sessions.
718
+ const callSession = {};
650
719
  for (let attempt = 0; attempt < 4; attempt += 1) {
651
720
  response = await node.executeProtectHistoryRequest({
652
721
  path: `events/${encodeURIComponent(id)}/thumbnail`,
653
722
  method: "GET",
654
723
  headers: { Accept: "image/jpeg" },
655
724
  timeout: 25000
656
- });
725
+ }, { historyCredentials }, callSession);
657
726
  if (response.statusCode !== 404 || attempt === 3) break;
658
727
  await new Promise((resolve) => setTimeout(resolve, 500));
659
728
  }
660
729
  if (!response || response.statusCode < 200 || response.statusCode >= 300) {
661
- const detail = extractProtectErrorDetail(response);
662
- throw new Error(`Unable to retrieve the UniFi Protect event snapshot (HTTP ${response && response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
730
+ // Do not forward controller response bodies into chat/tool errors.
731
+ throw new Error(`Unable to retrieve the UniFi Protect event snapshot (HTTP ${response && response.statusCode || "unknown"}).`);
663
732
  }
664
733
  if (!Buffer.isBuffer(response.payload) || response.payload.length === 0) {
665
734
  throw new Error("UniFi Protect returned an empty or invalid event snapshot.");
@@ -770,13 +839,16 @@ module.exports = function(RED) {
770
839
 
771
840
  ws.on("close", () => {
772
841
  try {
842
+ let wasActive = false;
773
843
  if (kind === "devices" && node.wsDevices === ws) {
774
844
  node.wsDevices = null;
845
+ wasActive = true;
775
846
  }
776
847
  if (kind === "events" && node.wsEvents === ws) {
777
848
  node.wsEvents = null;
849
+ wasActive = true;
778
850
  }
779
- node.scheduleReconnect();
851
+ if (wasActive) node.scheduleReconnect();
780
852
  } catch (error) {
781
853
  }
782
854
  });
@@ -795,18 +867,43 @@ module.exports = function(RED) {
795
867
  }
796
868
  };
797
869
 
798
- node.ensureWebSockets = () => {
799
- if (node.isClosing || node.nodeClients.length === 0) {
800
- return;
870
+ const clientNeedsProtectStream = (client, kind, handlerName) => {
871
+ if (!client || typeof client[handlerName] !== "function") return false;
872
+ if (!Array.isArray(client.protectStreams)) return true;
873
+ return client.protectStreams.some((stream) => String(stream || "").trim().toLowerCase() === kind);
874
+ };
875
+
876
+ node.closeWebSocket = (kind) => {
877
+ const propertyName = kind === "devices" ? "wsDevices" : "wsEvents";
878
+ const socket = node[propertyName];
879
+ if (!socket) return;
880
+ // Clear ownership before close so the close callback knows this was
881
+ // intentional and does not schedule an unnecessary reconnect.
882
+ node[propertyName] = null;
883
+ try {
884
+ socket.close();
885
+ } catch (error) {
801
886
  }
887
+ };
888
+
889
+ node.ensureWebSockets = () => {
890
+ if (node.isClosing) return;
891
+
892
+ const needsDevices = node.nodeClients.some((client) => clientNeedsProtectStream(client, "devices", "handleProtectDeviceUpdate"));
893
+ const needsEvents = node.nodeClients.some((client) => clientNeedsProtectStream(client, "events", "handleProtectEventUpdate"));
802
894
 
803
- // Devices and events are split into two streams by the Protect API.
804
- if (!node.wsDevices) {
895
+ // Devices and events are independent Protect streams. Open only the
896
+ // streams requested by active clients and close any no longer used.
897
+ if (needsDevices && !node.wsDevices) {
805
898
  node.attachSocket("devices", "/v1/subscribe/devices", node.broadcastDeviceUpdate);
899
+ } else if (!needsDevices) {
900
+ node.closeWebSocket("devices");
806
901
  }
807
902
 
808
- if (!node.wsEvents) {
903
+ if (needsEvents && !node.wsEvents) {
809
904
  node.attachSocket("events", "/v1/subscribe/events", node.broadcastEventUpdate);
905
+ } else if (!needsEvents) {
906
+ node.closeWebSocket("events");
810
907
  }
811
908
  };
812
909
 
@@ -816,21 +913,8 @@ module.exports = function(RED) {
816
913
  node.reconnectTimer = null;
817
914
  }
818
915
 
819
- if (node.wsDevices) {
820
- try {
821
- node.wsDevices.close();
822
- } catch (error) {
823
- }
824
- node.wsDevices = null;
825
- }
826
-
827
- if (node.wsEvents) {
828
- try {
829
- node.wsEvents.close();
830
- } catch (error) {
831
- }
832
- node.wsEvents = null;
833
- }
916
+ node.closeWebSocket("devices");
917
+ node.closeWebSocket("events");
834
918
  };
835
919
 
836
920
  node.addClient = (client) => {
@@ -852,11 +936,14 @@ module.exports = function(RED) {
852
936
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
853
937
  if (node.nodeClients.length === 0) {
854
938
  node.closeWebSockets();
939
+ } else {
940
+ node.ensureWebSockets();
855
941
  }
856
942
  };
857
943
 
858
944
  const knxAiBridgeClient = {
859
945
  id: `knx-ai-camera-adapter:${node.id}`,
946
+ protectStreams: ["events"],
860
947
  handleProtectDeviceUpdate(update) {
861
948
  const item = update && update.item;
862
949
  if (item && item.modelKey === "camera") {
@@ -889,7 +976,6 @@ module.exports = function(RED) {
889
976
  }
890
977
  };
891
978
 
892
- const historyCapabilities = node.hasHistoryCredentials() ? ["event_history", "event_snapshot"] : [];
893
979
  const knxAiProvider = {
894
980
  id: `unifi-ultimate:${node.id}`,
895
981
  adapterId: "unifi-ultimate",
@@ -898,9 +984,30 @@ module.exports = function(RED) {
898
984
  controllerId: node.id,
899
985
  controllerName: node.name || node.host || node.id,
900
986
  eventRetention: "none",
901
- capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"].concat(historyCapabilities),
987
+ get connected() {
988
+ return node.knxAiCameraProviderHealth.connected;
989
+ },
990
+ get ready() {
991
+ return node.knxAiCameraProviderHealth.ready;
992
+ },
993
+ isReady() {
994
+ return node.knxAiCameraProviderHealth.ready === true;
995
+ },
996
+ get health() {
997
+ return Object.assign({}, node.knxAiCameraProviderHealth);
998
+ },
999
+ get lastError() {
1000
+ return node.knxAiCameraProviderHealth.lastError;
1001
+ },
1002
+ get lastSeenAt() {
1003
+ return node.knxAiCameraProviderHealth.lastSeenAt;
1004
+ },
1005
+ capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines", "event_history", "event_snapshot"],
1006
+ historyCredentialsMode: "per_call",
902
1007
  listCameras: async (options) => (await node.listKnxAiCameras(options)).map(cloneProviderMetadataWithoutRaw),
903
1008
  takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
1009
+ queryEvents: (request, options) => node.queryKnxAiCameraEvents(request, options),
1010
+ takeEventSnapshot: (request, options) => node.takeKnxAiCameraEventSnapshot(request, options),
904
1011
  subscribe(listener) {
905
1012
  if (typeof listener !== "function") return () => { };
906
1013
  const wasEmpty = node.knxAiCameraListeners.size === 0;
@@ -912,19 +1019,15 @@ module.exports = function(RED) {
912
1019
  };
913
1020
  }
914
1021
  };
915
- if (node.hasHistoryCredentials()) {
916
- knxAiProvider.queryEvents = (request) => node.queryKnxAiCameraEvents(request);
917
- knxAiProvider.takeEventSnapshot = (request) => node.takeKnxAiCameraEventSnapshot(request);
918
- }
919
1022
  node.knxAiCameraProvider = knxAiProvider;
920
1023
  knxAiCameraRegistry.registerProvider(knxAiProvider);
921
1024
 
922
1025
  node.on("close", function(done) {
923
1026
  try {
924
1027
  node.isClosing = true;
1028
+ node.updateKnxAiCameraProviderHealth({ ok: false, error: "The UniFi Protect config node is closing." });
925
1029
  knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
926
1030
  node.knxAiCameraListeners.clear();
927
- node.protectHistorySessionHeaders = null;
928
1031
  node.protectHistoryPaginationGuard.clear();
929
1032
  node.protectCameraEventDeduper.clear();
930
1033
  node.removeClient(knxAiBridgeClient);
@@ -940,9 +1043,7 @@ module.exports = function(RED) {
940
1043
 
941
1044
  RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
942
1045
  credentials: {
943
- apiKey: { type: "password" },
944
- historyUsername: { type: "text" },
945
- historyPassword: { type: "password" }
1046
+ apiKey: { type: "password" }
946
1047
  }
947
1048
  });
948
1049
 
@@ -27,7 +27,10 @@ function normalizeSearchText(value) {
27
27
  // shape aligned with KNX Ultimate: an adapter describes package capabilities,
28
28
  // while each configured controller registers a provider implementing
29
29
  // listCameras(), takeSnapshot(), and subscribe(). Optional queryEvents() and
30
- // takeEventSnapshot() expose recorded evidence on demand. Providers declaring
30
+ // takeEventSnapshot() expose recorded evidence on demand. A provider requiring
31
+ // private history authentication accepts it separately from public query data:
32
+ // queryEvents(request, { historyCredentials, historyQueryScope }) and
33
+ // takeEventSnapshot(request, { historyCredentials }). Providers declaring
31
34
  // eventRetention: "none" keep their live feed transient in consumers. The
32
35
  // shared Symbol avoids any direct package dependency or flow wiring.
33
36
  function getKnxAiCameraRegistry() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.12",
3
+ "version": "1.1.14",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",
@@ -82,4 +82,4 @@
82
82
  "bugs": {
83
83
  "url": "https://github.com/Supergiovane/node-red-contrib-unifi-ultimate/issues"
84
84
  }
85
- }
85
+ }