@nr-connect/node-red 0.0.0-stage → 1.0.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.
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+
3
+ const { version: PLUGIN_VERSION = "1.0.0" } = require("../package.json");
4
+
5
+ function compareStrings(a, b) {
6
+ if (a < b) return -1;
7
+ if (a > b) return 1;
8
+ return 0;
9
+ }
10
+
11
+ /**
12
+ * Discover all FlowFuse Dashboard 2.0 `ui-page` configuration nodes deployed in Node-RED.
13
+ * @param {{ nodes?: { eachNode?: Function } }} RED
14
+ * @returns {Array<{ id: string, name: string, path: string, icon: string }>}
15
+ */
16
+ function discoverDashboardPages(RED) {
17
+ const pages = [];
18
+ if (!RED?.nodes?.eachNode) return pages;
19
+
20
+ try {
21
+ RED.nodes.eachNode((node) => {
22
+ if (node && node.type === "ui-page") {
23
+ pages.push({
24
+ id: node.id,
25
+ name: node.name || "Untitled Page",
26
+ path: node.path || "/",
27
+ icon: node.icon || "mdi-view-dashboard",
28
+ });
29
+ }
30
+ });
31
+ } catch {
32
+ // RED.nodes.eachNode throws during early plugin load before activeFlowConfig is initialized.
33
+ return [];
34
+ }
35
+
36
+ pages.sort(
37
+ (a, b) =>
38
+ compareStrings(String(a.id || ""), String(b.id || "")) ||
39
+ compareStrings(String(a.path || ""), String(b.path || "")) ||
40
+ compareStrings(String(a.name || ""), String(b.name || "")) ||
41
+ compareStrings(String(a.icon || ""), String(b.icon || ""))
42
+ );
43
+
44
+ return pages;
45
+ }
46
+
47
+ /**
48
+ * Detect the installed `@flowfuse/node-red-dashboard` version if available.
49
+ * @param {{ nodes?: { eachNode?: Function } }} RED
50
+ * @returns {string}
51
+ */
52
+ function detectDashboardVersion(RED) {
53
+ try {
54
+ const pkg = require("@flowfuse/node-red-dashboard/package.json");
55
+ if (pkg && pkg.version) return pkg.version;
56
+ } catch {
57
+ // Fallback when D2 is not installed in the same package scope
58
+ }
59
+ const pages = discoverDashboardPages(RED);
60
+ return pages.length > 0 ? "detected" : "not-installed";
61
+ }
62
+
63
+ /**
64
+ * Detect and normalize Node-RED's configured `httpAdminRoot` (Editor path).
65
+ * Returns `"/"` by default, a normalized path such as `"/admin"` when customized,
66
+ * or `undefined` when the Editor is explicitly disabled (`httpAdminRoot: false`).
67
+ *
68
+ * @param {{ settings?: { httpAdminRoot?: string | false } }} RED
69
+ * @returns {string | undefined}
70
+ */
71
+ function detectEditorPath(RED) {
72
+ const raw = RED?.settings?.httpAdminRoot;
73
+ if (raw === false) return undefined;
74
+ if (typeof raw !== "string") return "/";
75
+ const trimmed = raw.trim();
76
+ if (!trimmed || trimmed === "/") return "/";
77
+ const withLeading = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
78
+ const normalized = withLeading.replace(/\/+$/, "");
79
+ return normalized || "/";
80
+ }
81
+
82
+ /**
83
+ * Sync discovered `ui-page` nodes and instance telemetry with the NR Connect portal API.
84
+ *
85
+ * @param {object} RED
86
+ * @param {{ tunnelId: string, apiUrl: string, rawToken: string }} pluginConfig
87
+ * @param {object} [extraTelemetry]
88
+ * @param {Function} [fetchImpl]
89
+ * @returns {Promise<{ ok: boolean, pagesCount: number, response?: object }>}
90
+ */
91
+ async function syncWithPortal(RED, pluginConfig, extraTelemetry = {}, fetchImpl = globalThis.fetch) {
92
+ if (!pluginConfig || !pluginConfig.apiUrl || !pluginConfig.rawToken) {
93
+ return { ok: false, pagesCount: 0 };
94
+ }
95
+ if (typeof fetchImpl !== "function") {
96
+ throw new Error("Global fetch API is unavailable for portal sync");
97
+ }
98
+
99
+ const pages = discoverDashboardPages(RED);
100
+ const editorPath =
101
+ typeof extraTelemetry.editorPath === "string"
102
+ ? extraTelemetry.editorPath
103
+ : detectEditorPath(RED);
104
+ const endpoint = `${pluginConfig.apiUrl.replace(/\/+$/, "")}/api/agent/sync`;
105
+
106
+ const body = {
107
+ tunnelId: pluginConfig.tunnelId,
108
+ nrVersion: typeof RED.version === "function" ? RED.version() : "unknown",
109
+ d2Version: extraTelemetry.d2Version || detectDashboardVersion(RED),
110
+ platform: `${process.platform}-${process.arch}`,
111
+ daemonState: extraTelemetry.daemonState || "connected",
112
+ pluginVersion: extraTelemetry.pluginVersion || PLUGIN_VERSION,
113
+ ...(editorPath ? { editorPath } : {}),
114
+ ...(extraTelemetry.connectorVersion
115
+ ? { connectorVersion: extraTelemetry.connectorVersion }
116
+ : {}),
117
+ ...(extraTelemetry.connectorSource
118
+ ? { connectorSource: extraTelemetry.connectorSource }
119
+ : {}),
120
+ ...(extraTelemetry.reason ? { reason: extraTelemetry.reason } : {}),
121
+ pages,
122
+ };
123
+
124
+ const res = await fetchImpl(endpoint, {
125
+ method: "POST",
126
+ headers: {
127
+ "Content-Type": "application/json",
128
+ Authorization: `Bearer ${pluginConfig.rawToken}`,
129
+ },
130
+ body: JSON.stringify(body),
131
+ });
132
+
133
+ if (!res.ok) {
134
+ const errText = await res.text().catch(() => "");
135
+ const err = new Error(`Portal sync returned HTTP ${res.status}: ${errText}`);
136
+ err.status = res.status;
137
+ throw err;
138
+ }
139
+
140
+ const response = await res.json().catch(() => ({}));
141
+ return { ok: true, pagesCount: pages.length, response };
142
+ }
143
+
144
+ module.exports = {
145
+ discoverDashboardPages,
146
+ detectDashboardVersion,
147
+ detectEditorPath,
148
+ syncWithPortal,
149
+ };
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+
3
+ const CONFIG_CACHE_TTL_MS = 5 * 60 * 1000;
4
+ const DEFAULT_FETCH_TIMEOUT_MS = 15 * 1000;
5
+
6
+ let activeConfigProvider = null;
7
+ const configChangeListeners = new Set();
8
+ const configCache = new Map();
9
+ const swCache = new Map();
10
+
11
+ function createTimeoutSignal(timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
12
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
13
+ return AbortSignal.timeout(timeoutMs);
14
+ }
15
+ return undefined;
16
+ }
17
+
18
+ function notifyActiveConfigChange() {
19
+ const current = getActiveConfig();
20
+ for (const listener of configChangeListeners) {
21
+ try {
22
+ listener(current);
23
+ } catch {
24
+ // Ignore listener errors so other subscribers still receive updates
25
+ }
26
+ }
27
+ }
28
+
29
+ function onActiveConfigChange(listener) {
30
+ if (typeof listener !== "function") return () => {};
31
+ configChangeListeners.add(listener);
32
+ return () => {
33
+ configChangeListeners.delete(listener);
34
+ };
35
+ }
36
+
37
+ function setActiveConfigProvider(provider) {
38
+ activeConfigProvider = typeof provider === "function" ? provider : null;
39
+ notifyActiveConfigChange();
40
+ }
41
+
42
+ function getActiveConfig() {
43
+ return activeConfigProvider ? activeConfigProvider() : null;
44
+ }
45
+
46
+ function clearPushConfigCache() {
47
+ configCache.clear();
48
+ swCache.clear();
49
+ }
50
+
51
+ function normalizeBaseUrl(apiUrl) {
52
+ return String(apiUrl || "").trim().replace(/\/+$/, "");
53
+ }
54
+
55
+ /**
56
+ * Fetch public Firebase Web Push config from the NR Connect portal (`GET /api/push/config`)
57
+ * with a short in-memory cache per portal base URL.
58
+ *
59
+ * @param {{ apiUrl?: string } | null} config
60
+ * @param {Function} [fetchImpl]
61
+ * @param {number} [nowMs]
62
+ */
63
+ async function fetchPushClientConfig(
64
+ config,
65
+ fetchImpl = globalThis.fetch,
66
+ nowMs = Date.now()
67
+ ) {
68
+ const apiUrl = normalizeBaseUrl(config?.apiUrl);
69
+ if (!apiUrl) {
70
+ return { configured: false, reason: "not_connected", firebaseConfig: null, vapidKey: null };
71
+ }
72
+ if (typeof fetchImpl !== "function") {
73
+ throw new Error("Global fetch API is unavailable for push config lookup");
74
+ }
75
+
76
+ const cached = configCache.get(apiUrl);
77
+ if (cached && nowMs - cached.fetchedAt < CONFIG_CACHE_TTL_MS) {
78
+ return cached.value;
79
+ }
80
+
81
+ const signal = createTimeoutSignal();
82
+ const res = await fetchImpl(`${apiUrl}/api/push/config`, {
83
+ method: "GET",
84
+ headers: { Accept: "application/json" },
85
+ ...(signal ? { signal } : {}),
86
+ });
87
+
88
+ if (!res.ok) {
89
+ const errText = await res.text().catch(() => "");
90
+ const err = new Error(`Portal push config returned HTTP ${res.status}: ${errText}`);
91
+ err.status = res.status;
92
+ throw err;
93
+ }
94
+
95
+ const data = await res.json();
96
+ const value = {
97
+ configured: Boolean(data?.configured && data?.firebaseConfig && data?.vapidKey),
98
+ firebaseConfig: data?.firebaseConfig || null,
99
+ vapidKey: data?.vapidKey || null,
100
+ };
101
+
102
+ configCache.set(apiUrl, { fetchedAt: nowMs, value });
103
+ return value;
104
+ }
105
+
106
+ /**
107
+ * Fallback Service Worker loader when accessing Node-RED directly (e.g. localhost dev
108
+ * without Cloudflare Edge Worker proxying `/api/push/sw.js`).
109
+ */
110
+ async function fetchPushServiceWorkerFallback(
111
+ config,
112
+ fetchImpl = globalThis.fetch,
113
+ nowMs = Date.now()
114
+ ) {
115
+ const apiUrl = normalizeBaseUrl(config?.apiUrl);
116
+ if (!apiUrl || typeof fetchImpl !== "function") {
117
+ return [
118
+ "// NR Connect FCM Service Worker fallback (connect NR Connect to enable push).",
119
+ "self.addEventListener('install', () => self.skipWaiting());",
120
+ "self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));",
121
+ "",
122
+ ].join("\n");
123
+ }
124
+
125
+ const cached = swCache.get(apiUrl);
126
+ if (cached && nowMs - cached.fetchedAt < CONFIG_CACHE_TTL_MS) {
127
+ return cached.value;
128
+ }
129
+
130
+ const signal = createTimeoutSignal();
131
+ const res = await fetchImpl(`${apiUrl}/api/push/sw.js`, {
132
+ method: "GET",
133
+ headers: { Accept: "application/javascript, */*" },
134
+ ...(signal ? { signal } : {}),
135
+ });
136
+ if (!res.ok) {
137
+ throw new Error(`Portal SW endpoint returned HTTP ${res.status}`);
138
+ }
139
+ const script = await res.text();
140
+ swCache.set(apiUrl, { fetchedAt: nowMs, value: script });
141
+ return script;
142
+ }
143
+
144
+ /**
145
+ * Register or unregister a browser FCM token for the verified Dashboard user via `apps/portal`.
146
+ */
147
+ async function registerDeviceToken(
148
+ config,
149
+ user,
150
+ payload,
151
+ action = "register",
152
+ fetchImpl = globalThis.fetch
153
+ ) {
154
+ const apiUrl = normalizeBaseUrl(config?.apiUrl);
155
+ if (!apiUrl || !config?.rawToken || !config?.tunnelId) {
156
+ const err = new Error("NR Connect is not connected to the portal");
157
+ err.status = 503;
158
+ throw err;
159
+ }
160
+ if (!user?.email) {
161
+ const err = new Error("Verified user identity is required");
162
+ err.status = 401;
163
+ throw err;
164
+ }
165
+ const token = typeof payload?.token === "string" ? payload.token.trim() : "";
166
+ if (token.length < 10) {
167
+ const err = new Error("Valid push registration is required");
168
+ err.status = 400;
169
+ throw err;
170
+ }
171
+ if (typeof fetchImpl !== "function") {
172
+ throw new Error("Global fetch API is unavailable for push registration");
173
+ }
174
+
175
+ const method = action === "unregister" ? "DELETE" : "POST";
176
+ const signal = createTimeoutSignal();
177
+ const res = await fetchImpl(`${apiUrl}/api/agent/push/register`, {
178
+ method,
179
+ headers: {
180
+ "Content-Type": "application/json",
181
+ Authorization: `Bearer ${config.rawToken}`,
182
+ },
183
+ ...(signal ? { signal } : {}),
184
+ body: JSON.stringify({
185
+ tunnelId: config.tunnelId,
186
+ token,
187
+ email: user.email,
188
+ uid: user.userId || user.uid || user.email,
189
+ userAgent: typeof payload?.userAgent === "string" ? payload.userAgent.slice(0, 500) : null,
190
+ }),
191
+ });
192
+
193
+ const body = await res.json().catch(() => ({}));
194
+ if (!res.ok) {
195
+ const err = new Error(body?.error || `Portal push registration returned HTTP ${res.status}`);
196
+ err.status = res.status;
197
+ throw err;
198
+ }
199
+
200
+ return body;
201
+ }
202
+
203
+ /**
204
+ * Send an FCM push notification through `apps/portal` using the instance's `nrc_` token.
205
+ */
206
+ async function sendPushNotification(config, notification, fetchImpl = globalThis.fetch) {
207
+ const apiUrl = normalizeBaseUrl(config?.apiUrl);
208
+ if (!apiUrl || !config?.rawToken || !config?.tunnelId) {
209
+ const err = new Error("NR Connect is not connected to the portal");
210
+ err.status = 503;
211
+ throw err;
212
+ }
213
+ if (typeof fetchImpl !== "function") {
214
+ throw new Error("Global fetch API is unavailable for push delivery");
215
+ }
216
+
217
+ const signal = createTimeoutSignal();
218
+ const res = await fetchImpl(`${apiUrl}/api/agent/push/send`, {
219
+ method: "POST",
220
+ headers: {
221
+ "Content-Type": "application/json",
222
+ Authorization: `Bearer ${config.rawToken}`,
223
+ },
224
+ ...(signal ? { signal } : {}),
225
+ body: JSON.stringify({
226
+ ...notification,
227
+ tunnelId: config.tunnelId,
228
+ }),
229
+ });
230
+
231
+ const body = await res.json().catch(() => ({}));
232
+ if (!res.ok) {
233
+ const err = new Error(body?.error || `Portal push send returned HTTP ${res.status}`);
234
+ err.status = res.status;
235
+ throw err;
236
+ }
237
+
238
+ return body;
239
+ }
240
+
241
+ module.exports = {
242
+ CONFIG_CACHE_TTL_MS,
243
+ DEFAULT_FETCH_TIMEOUT_MS,
244
+ setActiveConfigProvider,
245
+ getActiveConfig,
246
+ onActiveConfigChange,
247
+ notifyActiveConfigChange,
248
+ clearPushConfigCache,
249
+ fetchPushClientConfig,
250
+ fetchPushServiceWorkerFallback,
251
+ registerDeviceToken,
252
+ sendPushNotification,
253
+ };