node-red-contrib-unifi-ultimate 1.1.11 → 1.1.13

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.
package/README.md CHANGED
@@ -126,22 +126,6 @@ Things you can do:
126
126
  - Play or stop a siren, control relay outputs, and test speaker or siren sound.
127
127
  - Read and select Protect Arm Profiles, then arm or disarm the local Alarm Manager from the NVR control.
128
128
 
129
- ### Automatic Cerebrum / KNX AI camera adapter
130
-
131
- Every configured **Unifi Protect Config** instance automatically publishes its cameras through the shared `node-red.knx-ai.camera-adapters.v1` runtime contract. Cerebrum and KNX AI can discover the installed provider without a Protect Device node, camera selector, or intermediate wire. They can then:
132
-
133
- - send a current camera snapshot to the chat channel;
134
- - describe a fresh snapshot with the configured vision-capable LLM;
135
- - subscribe to motion, line-crossing, intrusion-zone and loiter-zone events;
136
- - filter smart events by classifications such as people, animals, vehicles, faces, license plates and packages, and by an exact Protect line or zone;
137
- - search recorded events with time, camera and detection filters, follow explicit pagination, and retrieve the thumbnail belonging to an exact returned event.
138
-
139
- Recorded history requires the optional **History user/password** in the Protect config node. Use a dedicated local UniFi OS account that can view the required cameras. The Integration API key remains responsible for the official live-event and current-snapshot endpoints; the local account opens only the separate recorded-history session. Credentials and session cookies stay in the Node-RED credential/config node and are never published to Cerebrum, KNX AI, flows or chat context.
140
-
141
- Other camera packages can implement the same catalog, event, snapshot and recorded-history methods without adding vendor-specific code to Cerebrum.
142
-
143
-
144
-
145
129
  <br/>
146
130
  <br/>
147
131
  <p align="left">
@@ -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>
@@ -83,6 +83,95 @@ function createSnapshotError({ camera, response, retriedWithStandardQuality }) {
83
83
  return error;
84
84
  }
85
85
 
86
+ const PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS = 60 * 60 * 1000;
87
+ const PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES = 2048;
88
+
89
+ function cloneProviderMetadataWithoutRaw(value) {
90
+ if (Array.isArray(value)) return value.map(cloneProviderMetadataWithoutRaw);
91
+ if (!value || typeof value !== "object") return value;
92
+ const clone = {};
93
+ Object.entries(value).forEach(([key, nested]) => {
94
+ if (key === "raw") return;
95
+ clone[key] = cloneProviderMetadataWithoutRaw(nested);
96
+ });
97
+ return clone;
98
+ }
99
+
100
+ function sortedSemanticValues(values) {
101
+ return Array.from(new Set((Array.isArray(values) ? values : [])
102
+ .map((value) => String(value === undefined || value === null ? "" : value).trim())
103
+ .filter(Boolean)))
104
+ .sort();
105
+ }
106
+
107
+ function createProtectCameraEventDeduper({
108
+ ttlMs = PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS,
109
+ maxEntries = PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES
110
+ } = {}) {
111
+ const entries = new Map();
112
+ const normalizedTtl = Math.max(1000, Number(ttlMs) || PROTECT_CAMERA_EVENT_DEDUPE_TTL_MS);
113
+ const normalizedMaxEntries = Math.max(1, Math.floor(Number(maxEntries) || PROTECT_CAMERA_EVENT_DEDUPE_MAX_ENTRIES));
114
+ let lastPrunedAt = 0;
115
+
116
+ function prune(now, force = false) {
117
+ if (!force && entries.size < normalizedMaxEntries && now - lastPrunedAt < Math.min(normalizedTtl, 60000)) return;
118
+ entries.forEach((entry, key) => {
119
+ if (now - entry.seenAt > normalizedTtl) entries.delete(key);
120
+ });
121
+ lastPrunedAt = now;
122
+ }
123
+
124
+ return {
125
+ shouldForward(event, sourceEvent, now = Date.now()) {
126
+ if (!event || typeof event !== "object") return false;
127
+ const checkedAt = Number.isFinite(Number(now)) ? Number(now) : Date.now();
128
+ prune(checkedAt);
129
+ const eventId = String(event.eventId || "").trim();
130
+ const key = eventId
131
+ ? `id:${eventId}`
132
+ : `fallback:${event.cameraId || event.nativeCameraId || ""}:${event.eventType || ""}:${event.at || ""}`;
133
+ const rawEnd = sourceEvent && sourceEvent.end !== undefined && sourceEvent.end !== null
134
+ ? String(sourceEvent.end)
135
+ : null;
136
+ const fingerprint = JSON.stringify({
137
+ source: event.source || "",
138
+ controllerId: event.controllerId || "",
139
+ controllerName: event.controllerName || "",
140
+ cameraId: event.cameraId || "",
141
+ nativeCameraId: event.nativeCameraId || "",
142
+ cameraName: event.cameraName || "",
143
+ eventId,
144
+ eventType: event.eventType || "",
145
+ at: event.at || "",
146
+ active: event.active === true,
147
+ end: rawEnd,
148
+ scopeId: event.scopeId || "",
149
+ scopeName: event.scopeName || "",
150
+ scopeIds: sortedSemanticValues(event.scopeIds),
151
+ objectTypes: sortedSemanticValues(event.objectTypes)
152
+ });
153
+ const previous = entries.get(key);
154
+ const isDuplicate = previous
155
+ && previous.fingerprint === fingerprint
156
+ && checkedAt - previous.seenAt <= normalizedTtl;
157
+
158
+ // Refresh insertion order even for duplicates so a noisy active event
159
+ // remains suppressed until it has actually gone quiet for the TTL.
160
+ entries.delete(key);
161
+ entries.set(key, { fingerprint, seenAt: checkedAt });
162
+ if (entries.size > normalizedMaxEntries) {
163
+ const oldestKey = entries.keys().next().value;
164
+ if (oldestKey !== undefined) entries.delete(oldestKey);
165
+ }
166
+ return !isDuplicate;
167
+ },
168
+ clear() {
169
+ entries.clear();
170
+ lastPrunedAt = 0;
171
+ }
172
+ };
173
+ }
174
+
86
175
  module.exports = function(RED) {
87
176
  const knxAiCameraRegistry = getKnxAiCameraRegistry();
88
177
  knxAiCameraRegistry.registerAdapter({
@@ -113,66 +202,110 @@ module.exports = function(RED) {
113
202
  node.knxAiCameraRefresh = null;
114
203
  node.knxAiCameraRefreshAgain = false;
115
204
  node.knxAiCameraListeners = new Set();
116
- node.protectHistorySessionHeaders = null;
117
- node.protectHistoryAuthentication = null;
118
205
  node.protectHistoryPaginationGuard = createProtectHistoryPaginationGuard();
206
+ node.protectCameraEventDeduper = createProtectCameraEventDeduper();
207
+
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
+ }
119
226
 
120
227
  node.getApiKey = () => node.credentials && node.credentials.apiKey;
121
228
 
122
- node.getHistoryCredentials = () => ({
123
- username: String(node.credentials && node.credentials.historyUsername || "").trim(),
124
- password: String(node.credentials && node.credentials.historyPassword || "")
125
- });
126
-
127
- node.hasHistoryCredentials = () => {
128
- const credentials = node.getHistoryCredentials();
129
- 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
+ };
130
257
  };
131
258
 
132
- node.authenticateProtectHistory = async () => {
133
- if (node.protectHistorySessionHeaders) return node.protectHistorySessionHeaders;
134
- if (node.protectHistoryAuthentication) return node.protectHistoryAuthentication;
135
- const authentication = Promise.resolve().then(async () => {
136
- const credentials = node.getHistoryCredentials();
137
- if (!credentials.username || !credentials.password) {
138
- const error = new Error("UniFi Protect historical events require the optional local history username and password in the Protect config node.");
139
- error.code = "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED";
140
- throw error;
141
- }
142
- if (!node.controllerBaseUrl) throw new Error("The configured IP is empty or invalid.");
143
- const headers = {
144
- Accept: "application/json",
145
- "Content-Type": "application/json"
146
- };
147
- const body = buildRequestBody(headers, "POST", {
148
- username: credentials.username,
149
- password: credentials.password,
150
- rememberMe: false
151
- });
152
- const response = await doRequest(new URL(`${node.controllerBaseUrl}/api/auth/login`), {
153
- method: "POST",
154
- headers,
155
- timeout: 15000,
156
- rejectUnauthorized: node.rejectUnauthorized
157
- }, body);
158
- if (response.statusCode < 200 || response.statusCode >= 300) {
159
- const detail = extractProtectErrorDetail(response);
160
- const error = new Error(`UniFi OS login for Protect history failed (HTTP ${response.statusCode || "unknown"}${detail ? `: ${detail}` : ""}).`);
161
- error.code = "UNIFI_PROTECT_HISTORY_LOGIN_FAILED";
162
- error.statusCode = Number(response.statusCode) || 0;
163
- throw error;
164
- }
165
- node.protectHistorySessionHeaders = extractProtectHistorySessionHeaders(response);
166
- return node.protectHistorySessionHeaders;
167
- }).finally(() => {
168
- 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
169
279
  });
170
- node.protectHistoryAuthentication = authentication;
171
- 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);
172
295
  };
173
296
 
174
- node.executeProtectHistoryRequest = async ({ path, method = "GET", query, headers, payload, timeout = 20000 } = {}, retryAuthentication = true) => {
175
- 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;
176
309
  const normalizedPath = String(path || "").replace(/^\/+/, "");
177
310
  const requestUrl = new URL(`${node.controllerBaseUrl}/proxy/protect/api/${normalizedPath}${buildQueryString(query)}`);
178
311
  const requestMethod = String(method || "GET").toUpperCase();
@@ -185,10 +318,17 @@ module.exports = function(RED) {
185
318
  rejectUnauthorized: node.rejectUnauthorized
186
319
  }, requestBody);
187
320
  const refreshedCsrf = response && response.headers && response.headers["x-csrf-token"];
188
- if (refreshedCsrf && node.protectHistorySessionHeaders) node.protectHistorySessionHeaders["X-CSRF-Token"] = String(refreshedCsrf);
189
- if (Number(response && response.statusCode) === 401 && retryAuthentication) {
190
- node.protectHistorySessionHeaders = null;
191
- 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
+ );
192
332
  }
193
333
  return response;
194
334
  };
@@ -370,7 +510,11 @@ module.exports = function(RED) {
370
510
  };
371
511
  }).filter((camera) => camera.nativeCameraId);
372
512
  node.knxAiCameraCache = { at: Date.now(), cameras };
513
+ node.updateKnxAiCameraProviderHealth({ ok: true });
373
514
  return cameras;
515
+ }).catch((error) => {
516
+ node.updateKnxAiCameraProviderHealth({ ok: false, error });
517
+ throw error;
374
518
  }).finally(() => {
375
519
  if (node.knxAiCameraRefresh !== refresh) return;
376
520
  node.knxAiCameraRefresh = null;
@@ -458,15 +602,19 @@ module.exports = function(RED) {
458
602
  return {
459
603
  data: response.payload,
460
604
  mediaType,
461
- camera,
605
+ camera: cloneProviderMetadataWithoutRaw(camera),
462
606
  statusCode: response.statusCode
463
607
  };
464
608
  };
465
609
 
466
- node.queryKnxAiCameraEvents = async (request = {}) => {
610
+ node.queryKnxAiCameraEvents = async (request = {}, { historyCredentials, historyQueryScope } = {}) => {
467
611
  const normalized = normalizeProtectHistoryRequest(request);
468
612
  const requestSource = request && typeof request === "object" && !Array.isArray(request) ? request : {};
469
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),
470
618
  cameraId: normalized.cameraId,
471
619
  cameraName: normalized.cameraName,
472
620
  start: requestSource.from !== undefined || requestSource.start !== undefined ? normalized.start : "default",
@@ -480,12 +628,15 @@ module.exports = function(RED) {
480
628
  const response = await node.executeProtectHistoryRequest({
481
629
  path: "events",
482
630
  method: "GET",
483
- query: normalized.query,
631
+ query: Object.assign({}, normalized.query, requestedCamera
632
+ ? { cameras: [requestedCamera.nativeCameraId] }
633
+ : {}),
484
634
  timeout: 25000
485
- });
635
+ }, { historyCredentials });
486
636
  if (response.statusCode < 200 || response.statusCode >= 300) {
487
- const detail = extractProtectErrorDetail(response);
488
- 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"}).`);
489
640
  }
490
641
  const payload = Array.isArray(response.payload)
491
642
  ? response.payload
@@ -524,7 +675,11 @@ module.exports = function(RED) {
524
675
  return Object.assign({}, event, {
525
676
  endAt: Number.isFinite(parsedEnd) ? new Date(parsedEnd).toISOString() : "",
526
677
  score: Number.isFinite(Number(item.score)) ? Number(item.score) : null,
527
- 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)
528
683
  });
529
684
  }).filter(Boolean);
530
685
  const selected = selectProtectHistoryEvents(events, Object.assign({}, normalized, {
@@ -537,7 +692,7 @@ module.exports = function(RED) {
537
692
  events: payload
538
693
  });
539
694
  return {
540
- events: continuation.duplicatePage ? [] : selected,
695
+ events: continuation.duplicatePage ? [] : selected.map(cloneProviderMetadataWithoutRaw),
541
696
  from: normalized.from,
542
697
  to: normalized.to,
543
698
  offset: normalized.offset,
@@ -553,23 +708,27 @@ module.exports = function(RED) {
553
708
  };
554
709
  };
555
710
 
556
- node.takeKnxAiCameraEventSnapshot = async ({ eventId } = {}) => {
557
- 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-/, "");
558
714
  if (!id || id.length > 200) throw new Error("A valid UniFi Protect event id is required.");
559
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 = {};
560
719
  for (let attempt = 0; attempt < 4; attempt += 1) {
561
720
  response = await node.executeProtectHistoryRequest({
562
721
  path: `events/${encodeURIComponent(id)}/thumbnail`,
563
722
  method: "GET",
564
723
  headers: { Accept: "image/jpeg" },
565
724
  timeout: 25000
566
- });
725
+ }, { historyCredentials }, callSession);
567
726
  if (response.statusCode !== 404 || attempt === 3) break;
568
727
  await new Promise((resolve) => setTimeout(resolve, 500));
569
728
  }
570
729
  if (!response || response.statusCode < 200 || response.statusCode >= 300) {
571
- const detail = extractProtectErrorDetail(response);
572
- 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"}).`);
573
732
  }
574
733
  if (!Buffer.isBuffer(response.payload) || response.payload.length === 0) {
575
734
  throw new Error("UniFi Protect returned an empty or invalid event snapshot.");
@@ -680,13 +839,16 @@ module.exports = function(RED) {
680
839
 
681
840
  ws.on("close", () => {
682
841
  try {
842
+ let wasActive = false;
683
843
  if (kind === "devices" && node.wsDevices === ws) {
684
844
  node.wsDevices = null;
845
+ wasActive = true;
685
846
  }
686
847
  if (kind === "events" && node.wsEvents === ws) {
687
848
  node.wsEvents = null;
849
+ wasActive = true;
688
850
  }
689
- node.scheduleReconnect();
851
+ if (wasActive) node.scheduleReconnect();
690
852
  } catch (error) {
691
853
  }
692
854
  });
@@ -705,18 +867,43 @@ module.exports = function(RED) {
705
867
  }
706
868
  };
707
869
 
708
- node.ensureWebSockets = () => {
709
- if (node.isClosing || node.nodeClients.length === 0) {
710
- 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) {
711
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"));
712
894
 
713
- // Devices and events are split into two streams by the Protect API.
714
- 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) {
715
898
  node.attachSocket("devices", "/v1/subscribe/devices", node.broadcastDeviceUpdate);
899
+ } else if (!needsDevices) {
900
+ node.closeWebSocket("devices");
716
901
  }
717
902
 
718
- if (!node.wsEvents) {
903
+ if (needsEvents && !node.wsEvents) {
719
904
  node.attachSocket("events", "/v1/subscribe/events", node.broadcastEventUpdate);
905
+ } else if (!needsEvents) {
906
+ node.closeWebSocket("events");
720
907
  }
721
908
  };
722
909
 
@@ -726,21 +913,8 @@ module.exports = function(RED) {
726
913
  node.reconnectTimer = null;
727
914
  }
728
915
 
729
- if (node.wsDevices) {
730
- try {
731
- node.wsDevices.close();
732
- } catch (error) {
733
- }
734
- node.wsDevices = null;
735
- }
736
-
737
- if (node.wsEvents) {
738
- try {
739
- node.wsEvents.close();
740
- } catch (error) {
741
- }
742
- node.wsEvents = null;
743
- }
916
+ node.closeWebSocket("devices");
917
+ node.closeWebSocket("events");
744
918
  };
745
919
 
746
920
  node.addClient = (client) => {
@@ -762,11 +936,14 @@ module.exports = function(RED) {
762
936
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
763
937
  if (node.nodeClients.length === 0) {
764
938
  node.closeWebSockets();
939
+ } else {
940
+ node.ensureWebSockets();
765
941
  }
766
942
  };
767
943
 
768
944
  const knxAiBridgeClient = {
769
945
  id: `knx-ai-camera-adapter:${node.id}`,
946
+ protectStreams: ["events"],
770
947
  handleProtectDeviceUpdate(update) {
771
948
  const item = update && update.item;
772
949
  if (item && item.modelKey === "camera") {
@@ -788,8 +965,10 @@ module.exports = function(RED) {
788
965
  controllerName: node.name || node.host || node.id
789
966
  });
790
967
  if (!event) return;
968
+ if (!node.protectCameraEventDeduper.shouldForward(event, item)) return;
969
+ const publicEvent = cloneProviderMetadataWithoutRaw(event);
791
970
  node.knxAiCameraListeners.forEach((listener) => {
792
- try { listener(event); } catch (error) { }
971
+ try { listener(publicEvent); } catch (error) { }
793
972
  });
794
973
  }).catch((error) => {
795
974
  node.warn(`KNX AI camera event adapter failed: ${error && error.message ? error.message : error}`);
@@ -797,7 +976,6 @@ module.exports = function(RED) {
797
976
  }
798
977
  };
799
978
 
800
- const historyCapabilities = node.hasHistoryCredentials() ? ["event_history", "event_snapshot"] : [];
801
979
  const knxAiProvider = {
802
980
  id: `unifi-ultimate:${node.id}`,
803
981
  adapterId: "unifi-ultimate",
@@ -805,9 +983,31 @@ module.exports = function(RED) {
805
983
  packageName: "node-red-contrib-unifi-ultimate",
806
984
  controllerId: node.id,
807
985
  controllerName: node.name || node.host || node.id,
808
- capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"].concat(historyCapabilities),
809
- listCameras: (options) => node.listKnxAiCameras(options),
986
+ eventRetention: "none",
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",
1007
+ listCameras: async (options) => (await node.listKnxAiCameras(options)).map(cloneProviderMetadataWithoutRaw),
810
1008
  takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
1009
+ queryEvents: (request, options) => node.queryKnxAiCameraEvents(request, options),
1010
+ takeEventSnapshot: (request, options) => node.takeKnxAiCameraEventSnapshot(request, options),
811
1011
  subscribe(listener) {
812
1012
  if (typeof listener !== "function") return () => { };
813
1013
  const wasEmpty = node.knxAiCameraListeners.size === 0;
@@ -819,20 +1019,17 @@ module.exports = function(RED) {
819
1019
  };
820
1020
  }
821
1021
  };
822
- if (node.hasHistoryCredentials()) {
823
- knxAiProvider.queryEvents = (request) => node.queryKnxAiCameraEvents(request);
824
- knxAiProvider.takeEventSnapshot = (request) => node.takeKnxAiCameraEventSnapshot(request);
825
- }
826
1022
  node.knxAiCameraProvider = knxAiProvider;
827
1023
  knxAiCameraRegistry.registerProvider(knxAiProvider);
828
1024
 
829
1025
  node.on("close", function(done) {
830
1026
  try {
831
1027
  node.isClosing = true;
1028
+ node.updateKnxAiCameraProviderHealth({ ok: false, error: "The UniFi Protect config node is closing." });
832
1029
  knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
833
1030
  node.knxAiCameraListeners.clear();
834
- node.protectHistorySessionHeaders = null;
835
1031
  node.protectHistoryPaginationGuard.clear();
1032
+ node.protectCameraEventDeduper.clear();
836
1033
  node.removeClient(knxAiBridgeClient);
837
1034
  node.closeWebSockets();
838
1035
  } catch (error) {
@@ -846,9 +1043,7 @@ module.exports = function(RED) {
846
1043
 
847
1044
  RED.nodes.registerType("unifi-protect-config", UnifiProtectConfigNode, {
848
1045
  credentials: {
849
- apiKey: { type: "password" },
850
- historyUsername: { type: "text" },
851
- historyPassword: { type: "password" }
1046
+ apiKey: { type: "password" }
852
1047
  }
853
1048
  });
854
1049
 
@@ -26,8 +26,13 @@ function normalizeSearchText(value) {
26
26
  // This is the vendor-neutral KNX AI camera adapter contract. Keep this registry
27
27
  // shape aligned with KNX Ultimate: an adapter describes package capabilities,
28
28
  // while each configured controller registers a provider implementing
29
- // listCameras(), takeSnapshot(), and subscribe(). The shared Symbol avoids any
30
- // direct package dependency or flow wiring.
29
+ // listCameras(), takeSnapshot(), and subscribe(). Optional queryEvents() and
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
34
+ // eventRetention: "none" keep their live feed transient in consumers. The
35
+ // shared Symbol avoids any direct package dependency or flow wiring.
31
36
  function getKnxAiCameraRegistry() {
32
37
  const existing = globalThis[KNX_AI_CAMERA_REGISTRY_KEY];
33
38
  if (existing && existing.version === 1 && existing.adapters instanceof Map && existing.providers instanceof Map) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.11",
3
+ "version": "1.1.13",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",