@nr-connect/node-red 0.0.0-stage → 1.0.1

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,917 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const {
7
+ fetchPushClientConfig,
8
+ fetchPushServiceWorkerFallback,
9
+ registerDeviceToken,
10
+ } = require("./pushAgent");
11
+ const {
12
+ filterDashboardSetupPayload,
13
+ hasWorkerHeaders,
14
+ isDashboardItemAllowed,
15
+ } = require("./dashboardRbac");
16
+
17
+ const MAX_REPLAY_DRIFT_MS = 120000; // 2 minutes past
18
+ const MAX_FUTURE_DRIFT_MS = 30000; // 30 seconds future skew
19
+ const MAX_FCM_BODY_BYTES = 16384;
20
+
21
+ function hasCloudflareProxyHeaders(req) {
22
+ if (!req || !req.headers) return false;
23
+ const has = (name) => Boolean(req.headers[name] ?? req.headers[name.toLowerCase()]);
24
+ return has("cf-connecting-ip") || has("cf-ray") || has("cf-visitor");
25
+ }
26
+
27
+ function getFullRequestPathname(req) {
28
+ const raw = req?.originalUrl || req?.url || req?.path || "";
29
+ if (!raw || typeof raw !== "string") return "";
30
+ return raw.split("?")[0].split("#")[0];
31
+ }
32
+
33
+ /**
34
+ * Verify X-NR-Connect-* HMAC-SHA256 headers injected by the Cloudflare Edge Worker.
35
+ * Uses constant-time comparison, enforces bounded clock skew, and verifies method+path
36
+ * binding when `X-NR-Connect-Signature-V2` is present.
37
+ *
38
+ * @param {{ method?: string, originalUrl?: string, url?: string, path?: string, headers?: Record<string, string | string[] | undefined> }} req
39
+ * @param {string} sharedSecret
40
+ * @param {number} [nowMs]
41
+ * @returns {{ user: { userId: string, email: string, name?: string, role: string }, allowedPages: string[] } | null}
42
+ */
43
+ function verifyWorkerHeaders(req, sharedSecret, nowMs = Date.now()) {
44
+ if (!req || !req.headers || !sharedSecret) return null;
45
+
46
+ const getHeader = (name) => {
47
+ const val = req.headers[name] ?? req.headers[name.toLowerCase()];
48
+ return Array.isArray(val) ? val[0] : val;
49
+ };
50
+
51
+ const timestamp = getHeader("x-nr-connect-timestamp");
52
+ const userJson = getHeader("x-nr-connect-user");
53
+ const pagesJson = getHeader("x-nr-connect-allowed-pages");
54
+ const signature = getHeader("x-nr-connect-signature");
55
+ const signatureV2 = getHeader("x-nr-connect-signature-v2");
56
+
57
+ if (!timestamp || !userJson || !pagesJson || !signature) {
58
+ return null;
59
+ }
60
+
61
+ const parsedTs = Number(timestamp);
62
+ if (
63
+ !Number.isFinite(parsedTs) ||
64
+ nowMs - parsedTs > MAX_REPLAY_DRIFT_MS ||
65
+ parsedTs - nowMs > MAX_FUTURE_DRIFT_MS
66
+ ) {
67
+ return null;
68
+ }
69
+
70
+ const payload = `${timestamp}.${userJson}.${pagesJson}`;
71
+ const expectedSigHex = crypto
72
+ .createHmac("sha256", sharedSecret)
73
+ .update(payload)
74
+ .digest("hex");
75
+
76
+ const sigBuf = Buffer.from(String(signature).trim().toLowerCase(), "utf8");
77
+ const expectedBuf = Buffer.from(expectedSigHex, "utf8");
78
+
79
+ if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) {
80
+ return null;
81
+ }
82
+
83
+ if (signatureV2) {
84
+ const method = typeof req.method === "string" && req.method ? req.method.toUpperCase() : "";
85
+ const pathname = getFullRequestPathname(req);
86
+ if (method && pathname) {
87
+ const payloadV2 = `${timestamp}.${method}.${pathname}.${userJson}.${pagesJson}`;
88
+ const expectedSigV2Hex = crypto
89
+ .createHmac("sha256", sharedSecret)
90
+ .update(payloadV2)
91
+ .digest("hex");
92
+ const sigV2Buf = Buffer.from(String(signatureV2).trim().toLowerCase(), "utf8");
93
+ const expectedV2Buf = Buffer.from(expectedSigV2Hex, "utf8");
94
+ if (
95
+ sigV2Buf.length !== expectedV2Buf.length ||
96
+ !crypto.timingSafeEqual(sigV2Buf, expectedV2Buf)
97
+ ) {
98
+ return null;
99
+ }
100
+ }
101
+ }
102
+
103
+ try {
104
+ const user = JSON.parse(userJson);
105
+ const allowedPages = JSON.parse(pagesJson);
106
+ if (!user || typeof user !== "object" || !Array.isArray(allowedPages)) {
107
+ return null;
108
+ }
109
+ return { user, allowedPages };
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Determine whether a Require secure access request should bypass via loopback IP
117
+ * or the presence of `~/.node-red/.nr-connect-unlock`.
118
+ *
119
+ * @param {{ ip?: string, socket?: { remoteAddress?: string }, connection?: { remoteAddress?: string } }} req
120
+ * @param {string} [userDir]
121
+ * @returns {boolean}
122
+ */
123
+ function isLocalEscapeHatchActive(req, userDir) {
124
+ if (hasCloudflareProxyHeaders(req)) {
125
+ return false;
126
+ }
127
+
128
+ const remoteAddr =
129
+ req?.socket?.remoteAddress || req?.connection?.remoteAddress || req?.ip || "";
130
+ const isLoopback =
131
+ remoteAddr === "127.0.0.1" ||
132
+ remoteAddr === "::1" ||
133
+ remoteAddr === "::ffff:127.0.0.1";
134
+
135
+ if (isLoopback) {
136
+ return true;
137
+ }
138
+
139
+ if (userDir) {
140
+ try {
141
+ if (fs.existsSync(path.join(userDir, ".nr-connect-unlock"))) {
142
+ return true;
143
+ }
144
+ } catch {
145
+ // Ignore filesystem check errors
146
+ }
147
+ }
148
+
149
+ return false;
150
+ }
151
+
152
+ function getNormalizedRequestPath(req) {
153
+ const raw = req?.path || req?.url || req?.originalUrl || "";
154
+ return String(raw).split("?")[0];
155
+ }
156
+
157
+ function matchDebugStoreItemId(req) {
158
+ const reqPath = getNormalizedRequestPath(req).replace(/\/+$/, "");
159
+ const match = reqPath.match(/\/_debug\/(?:datastore|statestore)\/([^/?#]+)$/);
160
+ if (!match) return null;
161
+ try {
162
+ return decodeURIComponent(match[1]);
163
+ } catch {
164
+ return match[1];
165
+ }
166
+ }
167
+
168
+ function isDashboardSetupRequest(req) {
169
+ const urlPath = (req.path || "").split("?")[0];
170
+ const originalPath = (req.originalUrl || "").split("?")[0];
171
+ return (
172
+ urlPath === "/dashboard/_setup" ||
173
+ urlPath === "/ui/_setup" ||
174
+ originalPath.endsWith("/dashboard/_setup") ||
175
+ originalPath.endsWith("/ui/_setup")
176
+ );
177
+ }
178
+
179
+ function matchPushRoute(req) {
180
+ const reqPath = getNormalizedRequestPath(req);
181
+ if (/\/(dashboard|ui)\/_fcm\/config$/.test(reqPath)) return "config";
182
+ if (/\/(dashboard|ui)\/_fcm\/register$/.test(reqPath)) return "register";
183
+ if (/\/(dashboard|ui)\/nr-connect-push-sw\.js$/.test(reqPath)) return "sw";
184
+ return null;
185
+ }
186
+
187
+ function matchProfileRoute(req) {
188
+ return /\/(dashboard|ui)\/_nrc\/me$/.test(getNormalizedRequestPath(req));
189
+ }
190
+
191
+ function sanitizeProfilePhotoUrl(raw) {
192
+ if (typeof raw !== "string") return null;
193
+ const v = raw.trim();
194
+ if (!v || v.length > 2048) return null;
195
+ try {
196
+ return new URL(v).protocol === "https:" ? v : null;
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ function handleProfileEndpoint(req, res, config) {
203
+ const method = String(req?.method || "GET").toUpperCase();
204
+ if (method !== "GET" && method !== "HEAD") {
205
+ return sendJson(res, 405, { error: "Method not allowed" });
206
+ }
207
+ res.setHeader?.("Cache-Control", "no-store");
208
+
209
+ const verifiedUser =
210
+ req.nrConnectUser && typeof req.nrConnectUser === "object" ? req.nrConnectUser : null;
211
+ if (verifiedUser?.email) {
212
+ const apiUrl = typeof config?.apiUrl === "string" ? config.apiUrl.replace(/\/+$/, "") : "";
213
+ return sendJson(res, 200, {
214
+ user: {
215
+ name: String(verifiedUser.name || verifiedUser.email.split("@")[0]),
216
+ email: String(verifiedUser.email),
217
+ role: String(verifiedUser.role || "viewer"),
218
+ photoUrl: sanitizeProfilePhotoUrl(verifiedUser.photoUrl),
219
+ },
220
+ local: false,
221
+ signOutBaseUrl: apiUrl ? `${apiUrl}/signout` : null,
222
+ });
223
+ }
224
+
225
+ const devEmail =
226
+ process.env.NODE_ENV !== "production" &&
227
+ isLoopbackRequest(req) &&
228
+ !hasCloudflareProxyHeaders(req) &&
229
+ process.env.NR_CONNECT_DEV_USER_EMAIL
230
+ ? process.env.NR_CONNECT_DEV_USER_EMAIL.trim().toLowerCase()
231
+ : null;
232
+ if (devEmail) {
233
+ return sendJson(res, 200, {
234
+ user: {
235
+ name: devEmail.split("@")[0],
236
+ email: devEmail,
237
+ role: "admin",
238
+ photoUrl: null,
239
+ },
240
+ local: true,
241
+ signOutBaseUrl: null,
242
+ });
243
+ }
244
+
245
+ return sendJson(res, 200, { user: null, local: true, signOutBaseUrl: null });
246
+ }
247
+
248
+ function isLoopbackRequest(req) {
249
+ const remoteAddr =
250
+ req?.socket?.remoteAddress || req?.connection?.remoteAddress || req?.ip || "";
251
+ return (
252
+ remoteAddr === "127.0.0.1" ||
253
+ remoteAddr === "::1" ||
254
+ remoteAddr === "::ffff:127.0.0.1"
255
+ );
256
+ }
257
+
258
+ function readJsonBody(req, maxBytes = MAX_FCM_BODY_BYTES) {
259
+ if (req && req.body && typeof req.body === "object" && !Buffer.isBuffer(req.body)) {
260
+ return Promise.resolve(req.body);
261
+ }
262
+ if (typeof req?.body === "string") {
263
+ try {
264
+ return Promise.resolve(JSON.parse(req.body));
265
+ } catch {
266
+ const err = new Error("Invalid JSON body");
267
+ err.status = 400;
268
+ return Promise.reject(err);
269
+ }
270
+ }
271
+ if (!req || typeof req.on !== "function") {
272
+ return Promise.resolve({});
273
+ }
274
+
275
+ return new Promise((resolve, reject) => {
276
+ let totalBytes = 0;
277
+ const chunks = [];
278
+ let settled = false;
279
+
280
+ req.on("data", (chunk) => {
281
+ if (settled) return;
282
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
283
+ totalBytes += buf.length;
284
+ if (totalBytes > maxBytes) {
285
+ settled = true;
286
+ const err = new Error("Request payload too large");
287
+ err.status = 413;
288
+ reject(err);
289
+ return;
290
+ }
291
+ chunks.push(buf);
292
+ });
293
+
294
+ req.on("end", () => {
295
+ if (settled) return;
296
+ settled = true;
297
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
298
+ if (!raw) {
299
+ resolve({});
300
+ return;
301
+ }
302
+ try {
303
+ resolve(JSON.parse(raw));
304
+ } catch {
305
+ const err = new Error("Invalid JSON body");
306
+ err.status = 400;
307
+ reject(err);
308
+ }
309
+ });
310
+
311
+ req.on("error", (err) => {
312
+ if (settled) return;
313
+ settled = true;
314
+ reject(err);
315
+ });
316
+ });
317
+ }
318
+
319
+ function sendJson(res, status, data) {
320
+ if (typeof res.status === "function" && typeof res.json === "function") {
321
+ return res.status(status).json(data);
322
+ }
323
+ res.statusCode = status;
324
+ res.setHeader?.("Content-Type", "application/json; charset=utf-8");
325
+ res.end?.(JSON.stringify(data));
326
+ }
327
+
328
+ async function handlePushEndpoint(routeType, req, res, config, options) {
329
+ const fetchImpl = options?.fetchImpl || globalThis.fetch;
330
+ const method = String(req?.method || "GET").toUpperCase();
331
+
332
+ if (routeType === "config") {
333
+ if (method !== "GET" && method !== "HEAD") {
334
+ return sendJson(res, 405, { error: "Method not allowed" });
335
+ }
336
+ try {
337
+ const result = await fetchPushClientConfig(config, fetchImpl);
338
+ return sendJson(res, 200, result);
339
+ } catch (err) {
340
+ return sendJson(res, err?.status || 502, {
341
+ configured: false,
342
+ error: err?.message || "Failed to fetch push configuration",
343
+ });
344
+ }
345
+ }
346
+
347
+ if (routeType === "sw") {
348
+ if (method !== "GET" && method !== "HEAD") {
349
+ return sendJson(res, 405, { error: "Method not allowed" });
350
+ }
351
+ try {
352
+ const script = await fetchPushServiceWorkerFallback(config, fetchImpl);
353
+ res.statusCode = 200;
354
+ res.setHeader?.("Content-Type", "application/javascript; charset=utf-8");
355
+ res.setHeader?.("Cache-Control", "no-cache, no-store, must-revalidate");
356
+ if (typeof res.send === "function") {
357
+ return res.send(method === "HEAD" ? "" : script);
358
+ }
359
+ return res.end?.(method === "HEAD" ? undefined : script);
360
+ } catch (err) {
361
+ res.statusCode = 502;
362
+ res.setHeader?.("Content-Type", "application/javascript; charset=utf-8");
363
+ const msg = `// Failed to load service worker: ${err?.message || "unknown error"}`;
364
+ return typeof res.send === "function" ? res.send(msg) : res.end?.(msg);
365
+ }
366
+ }
367
+
368
+ if (routeType === "register") {
369
+ if (method !== "POST" && method !== "DELETE") {
370
+ return sendJson(res, 405, { error: "Method not allowed" });
371
+ }
372
+
373
+ if (!config || !config.rawToken || !config.apiUrl) {
374
+ return sendJson(res, 503, {
375
+ error: "NR Connect is not connected to the portal.",
376
+ });
377
+ }
378
+
379
+ const devEmail =
380
+ process.env.NODE_ENV !== "production" &&
381
+ !req.nrConnectUser &&
382
+ isLoopbackRequest(req) &&
383
+ !hasCloudflareProxyHeaders(req) &&
384
+ process.env.NR_CONNECT_DEV_USER_EMAIL
385
+ ? process.env.NR_CONNECT_DEV_USER_EMAIL.trim().toLowerCase()
386
+ : null;
387
+ const effectiveUser =
388
+ req.nrConnectUser ||
389
+ (devEmail ? { userId: devEmail, email: devEmail, role: "admin" } : null);
390
+
391
+ if (!effectiveUser?.email) {
392
+ return sendJson(res, 401, {
393
+ error: "Verified Dashboard user identity required. Open via your NR Connect URL.",
394
+ });
395
+ }
396
+
397
+ try {
398
+ const body = await readJsonBody(req);
399
+ const action = method === "DELETE" ? "unregister" : "register";
400
+ const result = await registerDeviceToken(
401
+ config,
402
+ effectiveUser,
403
+ {
404
+ token: body?.token,
405
+ userAgent: req.headers?.["user-agent"] || null,
406
+ },
407
+ action,
408
+ fetchImpl
409
+ );
410
+ return sendJson(res, 200, result);
411
+ } catch (err) {
412
+ return sendJson(res, err?.status || 500, {
413
+ error: err?.message || "Push registration failed",
414
+ });
415
+ }
416
+ }
417
+ }
418
+
419
+ function getHeaderValue(req, name) {
420
+ if (!req || !req.headers) return "";
421
+ const val = req.headers[name] ?? req.headers[name.toLowerCase()];
422
+ if (Array.isArray(val)) return String(val[0] || "");
423
+ return typeof val === "string" ? val : "";
424
+ }
425
+
426
+ /**
427
+ * Determine whether an incoming HTTP request is a browser page navigation
428
+ * (safe to 302-redirect to the secure NR Connect URL) rather than an API/XHR/subresource call.
429
+ *
430
+ * @param {{ method?: string, headers?: Record<string, string | string[] | undefined> }} req
431
+ * @returns {boolean}
432
+ */
433
+ function isBrowserNavigationRequest(req) {
434
+ const method = String(req?.method || "GET").toUpperCase();
435
+ if (method !== "GET" && method !== "HEAD") {
436
+ return false;
437
+ }
438
+
439
+ const xRequestedWith = getHeaderValue(req, "x-requested-with").trim().toLowerCase();
440
+ if (xRequestedWith === "xmlhttprequest") {
441
+ return false;
442
+ }
443
+
444
+ const secFetchMode = getHeaderValue(req, "sec-fetch-mode").trim().toLowerCase();
445
+ if (secFetchMode) {
446
+ return secFetchMode === "navigate";
447
+ }
448
+
449
+ const accept = getHeaderValue(req, "accept").toLowerCase();
450
+ return accept.includes("text/html");
451
+ }
452
+
453
+ /**
454
+ * Build a safe HTTPS redirect URL under the instance's NR Connect origin,
455
+ * preserving the requested path and query string while preventing open redirects.
456
+ *
457
+ * @param {string | null | undefined} baseUrlRaw
458
+ * @param {{ originalUrl?: string, url?: string }} req
459
+ * @returns {string | null}
460
+ */
461
+ function buildSecureRedirectUrl(baseUrlRaw, req) {
462
+ if (typeof baseUrlRaw !== "string" || !baseUrlRaw.trim()) return null;
463
+ let baseUrl;
464
+ try {
465
+ baseUrl = new URL(baseUrlRaw.trim());
466
+ } catch {
467
+ return null;
468
+ }
469
+ if (baseUrl.protocol !== "https:") {
470
+ return null;
471
+ }
472
+
473
+ const rawTarget = req?.originalUrl || req?.url || "/";
474
+ // Collapse leading slashes so protocol-relative paths like "//evil.com" cannot escape baseUrl.origin
475
+ const safePath = "/" + String(rawTarget).replace(/^\/+/, "");
476
+ try {
477
+ const target = new URL(safePath, baseUrl.origin);
478
+ if (target.origin !== baseUrl.origin) {
479
+ return baseUrl.href;
480
+ }
481
+ return target.href;
482
+ } catch {
483
+ return baseUrl.href;
484
+ }
485
+ }
486
+
487
+ function sendSecureRedirect(res, location) {
488
+ res.setHeader?.("Cache-Control", "no-store");
489
+ if (typeof res.redirect === "function") {
490
+ return res.redirect(302, location);
491
+ }
492
+ res.statusCode = 302;
493
+ res.setHeader?.("Location", location);
494
+ res.end?.();
495
+ }
496
+
497
+ function verifyOrRejectWorkerRequest(req, res, config, logger, forbiddenDirectMessage) {
498
+ const verified = verifyWorkerHeaders(req, config.sharedSecret);
499
+ if (verified) {
500
+ req.nrConnectUser = verified.user;
501
+ req.nrConnectAllowedPages = verified.allowedPages;
502
+ return { allowed: true, verified };
503
+ }
504
+
505
+ if (hasWorkerHeaders(req) || hasCloudflareProxyHeaders(req)) {
506
+ logger?.warn?.("[NR Connect] Rejected request with invalid, expired, or missing worker signature");
507
+ res.status(403).json({
508
+ error: "Forbidden: Invalid or expired NR Connect signature.",
509
+ });
510
+ return { allowed: false, verified: null };
511
+ }
512
+
513
+ if (config.requireSecureAccess && !isLocalEscapeHatchActive(req, config.userDir)) {
514
+ if (isBrowserNavigationRequest(req)) {
515
+ const redirectUrl = buildSecureRedirectUrl(config.url, req);
516
+ if (redirectUrl) {
517
+ sendSecureRedirect(res, redirectUrl);
518
+ return { allowed: false, verified: null };
519
+ }
520
+ }
521
+ res.status(403).json({ error: forbiddenDirectMessage });
522
+ return { allowed: false, verified: null };
523
+ }
524
+
525
+ return { allowed: true, verified: null };
526
+ }
527
+
528
+ /**
529
+ * Build the Express middleware that verifies Edge Worker signatures, exposes Dashboard
530
+ * FCM helper endpoints ahead of Dashboard 2.0's catch-all, and guards debug/_setup routes.
531
+ *
532
+ * @param {() => ({ sharedSecret?: string, requireSecureAccess?: boolean, userDir?: string, apiUrl?: string, rawToken?: string, tunnelId?: string } | null)} getPluginConfig
533
+ * @param {{ warn?: Function }} [logger]
534
+ * @param {{ fetchImpl?: Function, RED?: object }} [options]
535
+ */
536
+ function createNrConnectMiddleware(getPluginConfig, logger = console, options = {}) {
537
+ return function nrConnectInterceptor(req, res, next) {
538
+ const config = typeof getPluginConfig === "function" ? getPluginConfig() : null;
539
+ const pushRoute = matchPushRoute(req);
540
+ const profileRoute = matchProfileRoute(req);
541
+
542
+ if (!config || !config.sharedSecret) {
543
+ if (pushRoute) {
544
+ void handlePushEndpoint(pushRoute, req, res, config, options);
545
+ return;
546
+ }
547
+ if (profileRoute) {
548
+ handleProfileEndpoint(req, res, config);
549
+ return;
550
+ }
551
+ return next();
552
+ }
553
+
554
+ const authResult = verifyOrRejectWorkerRequest(
555
+ req,
556
+ res,
557
+ config,
558
+ logger,
559
+ "Forbidden: Direct access disabled. Connect through NR Connect."
560
+ );
561
+ if (!authResult.allowed) {
562
+ return;
563
+ }
564
+
565
+ const verified = authResult.verified;
566
+
567
+ if (pushRoute) {
568
+ void handlePushEndpoint(pushRoute, req, res, config, options);
569
+ return;
570
+ }
571
+
572
+ if (profileRoute) {
573
+ handleProfileEndpoint(req, res, config);
574
+ return;
575
+ }
576
+
577
+ if (verified && !verified.allowedPages.includes("*")) {
578
+ const debugItemId = matchDebugStoreItemId(req);
579
+ if (
580
+ debugItemId &&
581
+ !isDashboardItemAllowed(options?.RED, debugItemId, verified.allowedPages)
582
+ ) {
583
+ res.status(403).json({
584
+ error: "Forbidden: Access to this dashboard item is restricted.",
585
+ });
586
+ return;
587
+ }
588
+ }
589
+
590
+ if (
591
+ verified &&
592
+ isDashboardSetupRequest(req) &&
593
+ !verified.allowedPages.includes("*")
594
+ ) {
595
+ const originalSend = res.send.bind(res);
596
+ const originalJson = res.json ? res.json.bind(res) : null;
597
+ let filteredOnce = false;
598
+
599
+ const transformBody = (body) => {
600
+ if (filteredOnce) return body;
601
+ filteredOnce = true;
602
+ const parsed = typeof body === "string" ? JSON.parse(body) : body;
603
+ const filtered = filterDashboardSetupPayload(parsed, verified.allowedPages);
604
+ return typeof body === "string" ? JSON.stringify(filtered) : filtered;
605
+ };
606
+
607
+ if (originalJson) {
608
+ res.json = function (body) {
609
+ try {
610
+ return originalJson(transformBody(body));
611
+ } catch (err) {
612
+ logger.warn?.(`[NR Connect] Failed to filter _setup JSON: ${err.message}`);
613
+ res.statusCode = 500;
614
+ return originalJson({ error: "Failed to filter dashboard configuration." });
615
+ }
616
+ };
617
+ }
618
+
619
+ res.send = function (body) {
620
+ try {
621
+ const transformed = transformBody(body);
622
+ return originalSend(
623
+ typeof transformed === "object" ? JSON.stringify(transformed) : transformed
624
+ );
625
+ } catch (err) {
626
+ logger.warn?.(`[NR Connect] Failed to filter _setup payload: ${err.message}`);
627
+ res.statusCode = 500;
628
+ return originalSend(JSON.stringify({ error: "Failed to filter dashboard configuration." }));
629
+ }
630
+ };
631
+ }
632
+
633
+ next();
634
+ };
635
+ }
636
+
637
+ function getExpressStack(app) {
638
+ if (!app) return null;
639
+ if (app._router && Array.isArray(app._router.stack)) {
640
+ return app._router.stack;
641
+ }
642
+ try {
643
+ if (app.router && Array.isArray(app.router.stack)) {
644
+ return app.router.stack;
645
+ }
646
+ } catch {
647
+ // Express 4 throws "'app.router' is deprecated!" when accessed before initialization
648
+ }
649
+ return null;
650
+ }
651
+
652
+ function findPrependIndex(stack) {
653
+ let idx = 0;
654
+ while (
655
+ idx < stack.length &&
656
+ stack[idx] &&
657
+ (stack[idx].name === "query" || stack[idx].name === "expressInit")
658
+ ) {
659
+ idx += 1;
660
+ }
661
+ return idx;
662
+ }
663
+
664
+ function prependExpressLayer(app, layerName, middleware) {
665
+ if (!app) return;
666
+
667
+ const existingStack = getExpressStack(app);
668
+ if (existingStack && existingStack.some((layer) => layer && layer.name === layerName)) {
669
+ return;
670
+ }
671
+
672
+ if (typeof app.use === "function") {
673
+ // Let Express construct a real Layer instance (works for both Express 4 and Express 5),
674
+ // then move that newly added layer ahead of all user/Node-RED routes.
675
+ const beforeStack = getExpressStack(app);
676
+ const beforeLen = beforeStack ? beforeStack.length : 0;
677
+ app.use(middleware);
678
+ const afterStack = getExpressStack(app);
679
+ if (afterStack && afterStack.length > beforeLen) {
680
+ const addedLayer = afterStack.pop();
681
+ if (addedLayer) {
682
+ if (!addedLayer.name && layerName) {
683
+ try {
684
+ addedLayer.name = layerName;
685
+ } catch {
686
+ // Ignore if Layer.name is non-writable
687
+ }
688
+ }
689
+ afterStack.splice(findPrependIndex(afterStack), 0, addedLayer);
690
+ }
691
+ }
692
+ return;
693
+ }
694
+
695
+ // Fallback for lightweight mock apps in unit tests that only expose _router/router.stack
696
+ if (existingStack) {
697
+ existingStack.splice(findPrependIndex(existingStack), 0, {
698
+ name: layerName,
699
+ keys: [],
700
+ regexp: /^\/?(?=\/|$)/i,
701
+ handle: middleware,
702
+ });
703
+ }
704
+ }
705
+
706
+ /**
707
+ * Guard RED.httpAdmin (Node-RED Flow Editor & Admin APIs) when Require secure access is active.
708
+ *
709
+ * @param {object} RED
710
+ * @param {Function} getPluginConfig
711
+ */
712
+ const ADMIN_PROTECTED_PREFIXES = [
713
+ "/admin",
714
+ "/auth",
715
+ "/comms",
716
+ "/context",
717
+ "/credentials",
718
+ "/debug",
719
+ "/diagnostics",
720
+ "/flow",
721
+ "/flows",
722
+ "/icons",
723
+ "/inject",
724
+ "/library",
725
+ "/locales",
726
+ "/nodes",
727
+ "/nr-connect",
728
+ "/plugins",
729
+ "/red",
730
+ "/settings",
731
+ "/theme",
732
+ "/vendor",
733
+ ];
734
+
735
+ function getConfiguredAdminPrefix(RED) {
736
+ const raw = RED?.settings?.httpAdminRoot;
737
+ if (typeof raw !== "string") return null;
738
+ const trimmed = raw.trim().toLowerCase();
739
+ if (!trimmed || trimmed === "/") return null;
740
+ const withLeading = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
741
+ const normalized = withLeading.replace(/\/+$/, "");
742
+ return normalized || null;
743
+ }
744
+
745
+ function isAdminEditorPath(req, RED) {
746
+ const reqPath = getFullRequestPathname(req).toLowerCase();
747
+ if (!reqPath || reqPath === "/") return true;
748
+ const customAdminPrefix = getConfiguredAdminPrefix(RED);
749
+ if (
750
+ customAdminPrefix &&
751
+ (reqPath === customAdminPrefix || reqPath.startsWith(`${customAdminPrefix}/`))
752
+ ) {
753
+ return true;
754
+ }
755
+ return ADMIN_PROTECTED_PREFIXES.some(
756
+ (prefix) => reqPath === prefix || reqPath.startsWith(`${prefix}/`)
757
+ );
758
+ }
759
+
760
+ function isNonAdminAllowedNodePath(req) {
761
+ const reqPath = getFullRequestPathname(req).toLowerCase();
762
+ return (
763
+ reqPath === "/dashboard" ||
764
+ reqPath.startsWith("/dashboard/") ||
765
+ reqPath === "/ui" ||
766
+ reqPath.startsWith("/ui/") ||
767
+ reqPath.startsWith("/resources/")
768
+ );
769
+ }
770
+
771
+ function installAdminInterceptor(RED, getPluginConfig) {
772
+ const httpAdmin = RED?.httpAdmin;
773
+ if (!httpAdmin) return;
774
+
775
+ const nrConnectAdminInterceptor = function nrConnectAdminInterceptor(req, res, next) {
776
+ const config = typeof getPluginConfig === "function" ? getPluginConfig() : null;
777
+ if (!config || !config.sharedSecret) {
778
+ return next();
779
+ }
780
+
781
+ const authResult = verifyOrRejectWorkerRequest(
782
+ req,
783
+ res,
784
+ config,
785
+ RED?.log,
786
+ "Forbidden: Direct access to Editor disabled. Connect through NR Connect."
787
+ );
788
+ if (!authResult.allowed) {
789
+ return;
790
+ }
791
+
792
+ if (authResult.verified && authResult.verified.user?.role !== "admin") {
793
+ const role = authResult.verified.user?.role;
794
+ const blocked =
795
+ role === "webhook"
796
+ ? isAdminEditorPath(req, RED)
797
+ : !isNonAdminAllowedNodePath(req);
798
+ if (blocked) {
799
+ res.status(403).json({
800
+ error: "Forbidden: Admin privileges required for Editor.",
801
+ });
802
+ return;
803
+ }
804
+ }
805
+
806
+ next();
807
+ };
808
+
809
+ // In Node-RED, plugins receive runtime.httpAdmin, which is mounted inside api.httpAdmin
810
+ // *after* editorApp (GET /, vendor.js, red.min.js) and adminApiApp (/flows, /nodes, /settings).
811
+ // Prepending on httpAdmin.parent (api.httpAdmin) ensures the interceptor runs ahead of the
812
+ // entire Editor & Admin API stack without attaching to the shared outer server app.
813
+ const targetAdminApp =
814
+ httpAdmin.parent && httpAdmin.parent !== RED?.httpNode?.parent
815
+ ? httpAdmin.parent
816
+ : httpAdmin;
817
+
818
+ prependExpressLayer(targetAdminApp, "nrConnectAdminInterceptor", nrConnectAdminInterceptor);
819
+ }
820
+
821
+ /**
822
+ * Guard RED.server HTTP WebSocket upgrades (/comms and Dashboard 2.0 Socket.IO)
823
+ * when Require secure access is active.
824
+ *
825
+ * @param {object} RED
826
+ * @param {Function} getPluginConfig
827
+ */
828
+ function installUpgradeInterceptor(RED, getPluginConfig) {
829
+ const server = RED?.server;
830
+ if (!server || typeof server.on !== "function" || server.__nrConnectUpgradeInterceptorInstalled) {
831
+ return;
832
+ }
833
+
834
+ server.__nrConnectUpgradeInterceptorInstalled = true;
835
+ const onUpgrade = (req, socket) => {
836
+ const config = typeof getPluginConfig === "function" ? getPluginConfig() : null;
837
+ if (!config || !config.sharedSecret) {
838
+ return;
839
+ }
840
+
841
+ const verified = verifyWorkerHeaders(req, config.sharedSecret);
842
+ if (verified) {
843
+ const upgradePath = getFullRequestPathname(req);
844
+ const isCommsUpgrade =
845
+ upgradePath === "/comms" || upgradePath.endsWith("/comms");
846
+ if (isCommsUpgrade && verified.user?.role !== "admin") {
847
+ if (socket && typeof socket.write === "function") {
848
+ socket.write(
849
+ "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nForbidden: Admin privileges required for Editor.\r\n"
850
+ );
851
+ }
852
+ if (socket && typeof socket.destroy === "function") {
853
+ socket.destroy();
854
+ }
855
+ return;
856
+ }
857
+ req.nrConnectUser = verified.user;
858
+ req.nrConnectAllowedPages = verified.allowedPages;
859
+ } else if (
860
+ hasWorkerHeaders(req) ||
861
+ hasCloudflareProxyHeaders(req) ||
862
+ (config.requireSecureAccess && !isLocalEscapeHatchActive(req, config.userDir))
863
+ ) {
864
+ const reason = hasWorkerHeaders(req)
865
+ ? "Forbidden: Invalid or expired NR Connect signature."
866
+ : "Forbidden: Direct WebSocket access disabled.";
867
+ if (socket && typeof socket.write === "function") {
868
+ socket.write(
869
+ `HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${reason}\r\n`
870
+ );
871
+ }
872
+ if (socket && typeof socket.destroy === "function") {
873
+ socket.destroy();
874
+ }
875
+ }
876
+ };
877
+ if (typeof server.prependListener === "function") {
878
+ server.prependListener("upgrade", onUpgrade);
879
+ } else {
880
+ server.on("upgrade", onUpgrade);
881
+ }
882
+ }
883
+
884
+ /**
885
+ * Prepend the NR Connect middleware to the front of RED.httpNode's Express router stack
886
+ * so it runs ahead of FlowFuse Dashboard 2.0 routes without editing settings.js.
887
+ * Also guards RED.httpAdmin and RED.server WebSocket upgrades.
888
+ *
889
+ * @param {object} RED
890
+ * @param {Function} getPluginConfig
891
+ */
892
+ function installExpressInterceptor(RED, getPluginConfig) {
893
+ const httpNode = RED?.httpNode;
894
+ if (httpNode) {
895
+ const middleware = createNrConnectMiddleware(getPluginConfig, RED.log, { RED });
896
+ prependExpressLayer(httpNode, "nrConnectInterceptor", middleware);
897
+ }
898
+
899
+ installAdminInterceptor(RED, getPluginConfig);
900
+ installUpgradeInterceptor(RED, getPluginConfig);
901
+ }
902
+
903
+ module.exports = {
904
+ MAX_REPLAY_DRIFT_MS,
905
+ verifyWorkerHeaders,
906
+ hasWorkerHeaders,
907
+ isLocalEscapeHatchActive,
908
+ isBrowserNavigationRequest,
909
+ buildSecureRedirectUrl,
910
+ filterDashboardSetupPayload,
911
+ matchProfileRoute,
912
+ handleProfileEndpoint,
913
+ createNrConnectMiddleware,
914
+ installAdminInterceptor,
915
+ installUpgradeInterceptor,
916
+ installExpressInterceptor,
917
+ };