@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,1060 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { version: PACKAGE_VERSION = "1.0.0" } = require("../package.json");
6
+ const { decodeCompositeToken } = require("./tokenCodec");
7
+ const {
8
+ PINNED_CONNECTOR_MANIFEST,
9
+ compareVersions,
10
+ ensureCloudflaredBinary,
11
+ resolveConnectorBinaryInfo,
12
+ updateCloudflaredBinary,
13
+ } = require("./binaryManager");
14
+ const { spawnCloudflared } = require("./tunnelDaemon");
15
+ const {
16
+ discoverDashboardPages,
17
+ syncWithPortal,
18
+ } = require("./pageSyncAgent");
19
+ const { notifyActiveConfigChange } = require("./pushAgent");
20
+ const {
21
+ buildQrFilenameBase,
22
+ renderStyledQrSvg,
23
+ resolveInstanceQrUrl,
24
+ } = require("./qrCode");
25
+
26
+ const DEFAULT_SYNC_INTERVAL_MS = 900000;
27
+ const MIN_SYNC_INTERVAL_MS = 60000;
28
+ const MAX_SYNC_INTERVAL_MS = 3600000;
29
+ const DEFAULT_SYNC_JITTER_RATIO = 0.1;
30
+ const DEPLOY_DEBOUNCE_MS = 2000;
31
+ const HEARTBEAT_INTERVAL_MS = DEFAULT_SYNC_INTERVAL_MS;
32
+ const STATUS_TOPIC = "nr-connect/status";
33
+
34
+ const VALID_CONNECTOR_STATES = new Set([
35
+ "not_connected",
36
+ "preparing",
37
+ "connecting",
38
+ "connected",
39
+ "reconnecting",
40
+ "error",
41
+ "stopped",
42
+ ]);
43
+
44
+ const USER_ERRORS = {
45
+ MISSING_CODE: "Paste your connection code before connecting.",
46
+ INVALID_CODE: "That code isn't valid. Copy it again from NR Connect.",
47
+ ENV_MANAGED:
48
+ "This connection is managed by the server environment and cannot be changed here.",
49
+ NOT_CONNECTED: "Not connected to NR Connect yet.",
50
+ CONCURRENT_CHANGE: "Connection changed while verifying. Please try again.",
51
+ CONNECT_FAILED: "Unable to save connection settings.",
52
+ DISCONNECT_FAILED: "Unable to disconnect right now.",
53
+ CHECKIN_FAILED: "Check-in failed. Please try again.",
54
+ CONNECTOR_SYSTEM_MANAGED:
55
+ "This connector is managed by the host environment and cannot be updated here.",
56
+ CONNECTOR_UPDATE_FAILED: "Unable to update the connector right now. Please try again.",
57
+ };
58
+
59
+ function sanitizeStringOrNull(value) {
60
+ if (typeof value !== "string") return null;
61
+ const trimmed = value.trim();
62
+ return trimmed ? trimmed : null;
63
+ }
64
+
65
+ function sanitizeLogError(err) {
66
+ const raw = typeof err?.message === "string" ? err.message : String(err || "unknown error");
67
+ return raw
68
+ .replace(/https?:\/\/github\.com\/cloudflare\/[^\s)]+/gi, "[connector-release]")
69
+ .replace(/cloudflared(?:\.exe)?/gi, "connector")
70
+ .replace(/cloudflare/gi, "remote")
71
+ .replace(/\bcfTunnelToken\b|\bsharedSecret\b|\btunnelId\b/g, "[field]")
72
+ .replace(/\bnrc_[A-Za-z0-9+/_=-]+/g, "[code]")
73
+ .replace(/\btunnel\b/gi, "connection");
74
+ }
75
+
76
+ async function stopDaemonCleanly(daemon) {
77
+ if (!daemon) return;
78
+ if (typeof daemon.stopAndWait === "function") {
79
+ await daemon.stopAndWait();
80
+ return;
81
+ }
82
+ daemon.stop();
83
+ }
84
+
85
+ function buildUpdateSummary({
86
+ pluginVersion,
87
+ connectorVersion,
88
+ connectorSource,
89
+ advisories,
90
+ connectorUpdateState,
91
+ }) {
92
+ const pluginLatest = sanitizeStringOrNull(advisories?.plugin?.latest) || pluginVersion;
93
+ const pluginMinimum = sanitizeStringOrNull(advisories?.plugin?.minimum) || pluginVersion;
94
+ const pluginRequired = compareVersions(pluginVersion, pluginMinimum) === -1;
95
+ const pluginAvailable = pluginRequired || compareVersions(pluginVersion, pluginLatest) === -1;
96
+
97
+ const connectorLatest =
98
+ sanitizeStringOrNull(advisories?.connector?.latest) ||
99
+ PINNED_CONNECTOR_MANIFEST.version ||
100
+ null;
101
+ const connectorMinimum =
102
+ sanitizeStringOrNull(advisories?.connector?.minimum) ||
103
+ PINNED_CONNECTOR_MANIFEST.minVersion ||
104
+ null;
105
+
106
+ const connectorRequired = Boolean(
107
+ connectorVersion &&
108
+ connectorMinimum &&
109
+ compareVersions(connectorVersion, connectorMinimum) === -1
110
+ );
111
+ const connectorAvailable =
112
+ connectorRequired ||
113
+ Boolean(
114
+ connectorVersion &&
115
+ connectorLatest &&
116
+ compareVersions(connectorVersion, connectorLatest) === -1
117
+ );
118
+
119
+ return {
120
+ plugin: {
121
+ latest: pluginLatest,
122
+ minimum: pluginMinimum,
123
+ available: pluginAvailable,
124
+ required: pluginRequired,
125
+ },
126
+ connector: {
127
+ latest: connectorLatest,
128
+ minimum: connectorMinimum,
129
+ available: connectorAvailable,
130
+ required: connectorRequired,
131
+ canSelfUpdate: connectorSource === "managed",
132
+ updating: connectorUpdateState.state === "updating",
133
+ error: connectorUpdateState.error,
134
+ },
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Create the NR Connect runtime connection state machine.
140
+ *
141
+ * Manages persisted config (`.nr-connect.json`), env overrides, pre-save
142
+ * verification check-ins, connector lifecycle, verified connector binary
143
+ * updates, 60 s heartbeats, and retained `RED.comms` status broadcasts
144
+ * without exposing secrets in status snapshots.
145
+ */
146
+ function createConnectionManager(options = {}) {
147
+ const {
148
+ RED,
149
+ userDir = RED?.settings?.userDir || process.cwd(),
150
+ configFilePath = path.join(userDir, ".nr-connect.json"),
151
+ env = process.env,
152
+ fsImpl = fs,
153
+ fetchImpl = globalThis.fetch,
154
+ decodeToken = decodeCompositeToken,
155
+ ensureBinary = ensureCloudflaredBinary,
156
+ resolveBinaryInfo = resolveConnectorBinaryInfo,
157
+ updateBinary = updateCloudflaredBinary,
158
+ spawnDaemon = spawnCloudflared,
159
+ syncPortal = syncWithPortal,
160
+ discoverPages = discoverDashboardPages,
161
+ heartbeatIntervalMs = DEFAULT_SYNC_INTERVAL_MS,
162
+ syncIntervalMs = heartbeatIntervalMs,
163
+ syncJitterRatio = DEFAULT_SYNC_JITTER_RATIO,
164
+ deployDebounceMs = DEPLOY_DEBOUNCE_MS,
165
+ randomFn = Math.random,
166
+ pluginVersion = PACKAGE_VERSION,
167
+ } = options;
168
+
169
+ let activeDaemon = null;
170
+ let activeBinaryPath = null;
171
+ let heartbeatTimer = null;
172
+ let deployDebounceTimer = null;
173
+ let deployDebounceWaiters = [];
174
+ let currentSyncIntervalMs =
175
+ typeof syncIntervalMs === "number" && Number.isFinite(syncIntervalMs) && syncIntervalMs > 0
176
+ ? syncIntervalMs
177
+ : DEFAULT_SYNC_INTERVAL_MS;
178
+ let currentJitterRatio =
179
+ typeof syncJitterRatio === "number" && Number.isFinite(syncJitterRatio)
180
+ ? Math.max(0, Math.min(0.5, syncJitterRatio))
181
+ : DEFAULT_SYNC_JITTER_RATIO;
182
+ let pluginConfig = null;
183
+ let connectorState = "not_connected";
184
+ let checkIn = { state: "never", at: null };
185
+ let connectorVersion = null;
186
+ let connectorSource = null;
187
+ let updateAdvisories = null;
188
+ let connectorUpdate = { state: "idle", error: null };
189
+ let connectorUpdatePromise = null;
190
+ let lastAutoUpdateAttemptVersion = null;
191
+ let connectorGen = 0;
192
+ let mutationSeq = 0;
193
+
194
+ function isManagedByEnv() {
195
+ return Boolean(typeof env?.NR_CONNECT_TOKEN === "string" && env.NR_CONNECT_TOKEN.trim());
196
+ }
197
+
198
+ function getActiveConfig() {
199
+ if (!pluginConfig) return null;
200
+ return {
201
+ ...pluginConfig,
202
+ userDir,
203
+ };
204
+ }
205
+
206
+ function safeDiscoverPages() {
207
+ try {
208
+ const rawPages = discoverPages(RED);
209
+ return Array.isArray(rawPages)
210
+ ? rawPages.map((p) => ({
211
+ id: p.id,
212
+ name: p.name,
213
+ path: p.path,
214
+ }))
215
+ : [];
216
+ } catch {
217
+ // During early onadd() before Node-RED initializes activeFlowConfig,
218
+ // RED.nodes.eachNode throws until flows:started fires.
219
+ return [];
220
+ }
221
+ }
222
+
223
+ function getStatus() {
224
+ const connected = Boolean(pluginConfig);
225
+ const pages = connected ? safeDiscoverPages() : [];
226
+
227
+ return {
228
+ connected,
229
+ managedByEnv: isManagedByEnv(),
230
+ instanceId: connected ? pluginConfig.tunnelId : null,
231
+ portalUrl: connected ? pluginConfig.apiUrl : null,
232
+ name: connected ? sanitizeStringOrNull(pluginConfig.name) : null,
233
+ url: connected ? sanitizeStringOrNull(pluginConfig.url) : null,
234
+ requireSecureAccess: connected ? Boolean(pluginConfig.requireSecureAccess) : false,
235
+ connector: connected ? connectorState : "not_connected",
236
+ checkIn: {
237
+ state: connected ? checkIn.state : "never",
238
+ at: connected ? checkIn.at : null,
239
+ },
240
+ syncIntervalMs: currentSyncIntervalMs,
241
+ pages,
242
+ versions: {
243
+ plugin: pluginVersion,
244
+ connector: connected ? connectorVersion : null,
245
+ connectorSource: connected ? connectorSource : null,
246
+ },
247
+ updates: buildUpdateSummary({
248
+ pluginVersion,
249
+ connectorVersion: connected ? connectorVersion : null,
250
+ connectorSource: connected ? connectorSource : null,
251
+ advisories: connected ? updateAdvisories : null,
252
+ connectorUpdateState: connectorUpdate,
253
+ }),
254
+ };
255
+ }
256
+
257
+ function getDiagnostics() {
258
+ const status = getStatus();
259
+ const nodeRedVersion =
260
+ typeof RED?.version === "function" ? RED.version() : null;
261
+
262
+ return {
263
+ generatedAt: new Date().toISOString(),
264
+ pluginVersion: status.versions.plugin,
265
+ nodeVersion: process.version,
266
+ nodeRedVersion,
267
+ platform: process.platform,
268
+ arch: process.arch,
269
+ connected: status.connected,
270
+ managedByEnv: status.managedByEnv,
271
+ connectorState: status.connector,
272
+ connectorVersion: status.versions.connector,
273
+ connectorSource: status.versions.connectorSource,
274
+ requireSecureAccess: status.requireSecureAccess,
275
+ checkInState: status.checkIn.state,
276
+ checkInAt: status.checkIn.at,
277
+ syncIntervalMs: status.syncIntervalMs,
278
+ dashboardPageCount: Array.isArray(status.pages) ? status.pages.length : 0,
279
+ };
280
+ }
281
+
282
+ function publishStatus() {
283
+ const status = getStatus();
284
+ if (typeof RED?.comms?.publish === "function") {
285
+ RED.comms.publish(STATUS_TOPIC, status, true);
286
+ }
287
+ notifyActiveConfigChange();
288
+ return status;
289
+ }
290
+
291
+ function clearDeployDebounce() {
292
+ if (deployDebounceTimer) {
293
+ clearTimeout(deployDebounceTimer);
294
+ deployDebounceTimer = null;
295
+ }
296
+ if (deployDebounceWaiters.length > 0) {
297
+ const waiters = deployDebounceWaiters;
298
+ deployDebounceWaiters = [];
299
+ for (const resolve of waiters) {
300
+ resolve(null);
301
+ }
302
+ }
303
+ }
304
+
305
+ function stopDaemonAndHeartbeat() {
306
+ if (activeDaemon) {
307
+ const prev = activeDaemon;
308
+ activeDaemon = null;
309
+ prev.stop();
310
+ }
311
+ activeBinaryPath = null;
312
+ if (heartbeatTimer) {
313
+ clearTimeout(heartbeatTimer);
314
+ heartbeatTimer = null;
315
+ }
316
+ clearDeployDebounce();
317
+ }
318
+
319
+ function launchDaemon(binaryPath, myGen) {
320
+ activeBinaryPath = binaryPath;
321
+ return spawnDaemon({
322
+ binaryPath,
323
+ cfTunnelToken: pluginConfig.cfTunnelToken,
324
+ logger: RED?.log,
325
+ onStatusChange: (nextStatus) => {
326
+ if (myGen !== connectorGen) return;
327
+ const nextState = VALID_CONNECTOR_STATES.has(nextStatus?.state)
328
+ ? nextStatus.state
329
+ : "error";
330
+ if (nextState !== connectorState) {
331
+ connectorState = nextState;
332
+ publishStatus();
333
+ }
334
+ },
335
+ });
336
+ }
337
+
338
+ function loadPersistedConfig() {
339
+ if (isManagedByEnv()) {
340
+ try {
341
+ const decoded = decodeToken(env.NR_CONNECT_TOKEN.trim());
342
+ return {
343
+ ...decoded,
344
+ requireSecureAccess: String(env.NR_CONNECT_REQUIRE_SECURE_ACCESS) === "true",
345
+ name: null,
346
+ url: null,
347
+ };
348
+ } catch {
349
+ RED?.log?.warn?.("[NR Connect] Invalid NR_CONNECT_TOKEN environment value; ignoring.");
350
+ return null;
351
+ }
352
+ }
353
+
354
+ if (!fsImpl.existsSync(configFilePath)) {
355
+ return null;
356
+ }
357
+
358
+ try {
359
+ const saved = JSON.parse(fsImpl.readFileSync(configFilePath, "utf8"));
360
+ if (saved && saved.rawToken) {
361
+ const decoded = decodeToken(saved.rawToken);
362
+ return {
363
+ ...decoded,
364
+ requireSecureAccess: Boolean(saved.requireSecureAccess),
365
+ name: sanitizeStringOrNull(saved.name),
366
+ url: sanitizeStringOrNull(saved.url),
367
+ };
368
+ }
369
+ } catch (err) {
370
+ RED?.log?.warn?.(
371
+ `[NR Connect] Failed to load saved connection config: ${sanitizeLogError(err)}`
372
+ );
373
+ }
374
+
375
+ return null;
376
+ }
377
+
378
+ function savePersistedConfig(config) {
379
+ if (isManagedByEnv() || !config) return;
380
+ const payload = {
381
+ rawToken: config.rawToken,
382
+ requireSecureAccess: Boolean(config.requireSecureAccess),
383
+ name: sanitizeStringOrNull(config.name),
384
+ url: sanitizeStringOrNull(config.url),
385
+ updatedAt: new Date().toISOString(),
386
+ };
387
+ fsImpl.mkdirSync(path.dirname(configFilePath), { recursive: true });
388
+ fsImpl.writeFileSync(configFilePath, JSON.stringify(payload, null, 2), { mode: 0o600 });
389
+ }
390
+
391
+ function deletePersistedConfig() {
392
+ if (!fsImpl.existsSync(configFilePath)) return;
393
+ try {
394
+ fsImpl.unlinkSync(configFilePath);
395
+ } catch (err) {
396
+ if (err && err.code !== "ENOENT") throw err;
397
+ }
398
+ }
399
+
400
+ function applySyncResponseMetadata(config, response) {
401
+ if (!config || !response || typeof response !== "object") return false;
402
+ let changed = false;
403
+
404
+ if (
405
+ typeof response.requireSecureAccess === "boolean" &&
406
+ response.requireSecureAccess !== Boolean(config.requireSecureAccess)
407
+ ) {
408
+ config.requireSecureAccess = response.requireSecureAccess;
409
+ changed = true;
410
+ }
411
+
412
+ if ("name" in response) {
413
+ const nextName = sanitizeStringOrNull(response.name);
414
+ if (nextName !== config.name) {
415
+ config.name = nextName;
416
+ changed = true;
417
+ }
418
+ }
419
+
420
+ if ("url" in response) {
421
+ const nextUrl = sanitizeStringOrNull(response.url);
422
+ if (nextUrl !== config.url) {
423
+ config.url = nextUrl;
424
+ changed = true;
425
+ }
426
+ }
427
+
428
+ return changed;
429
+ }
430
+
431
+ function refreshBinaryMetadata(binaryPath) {
432
+ try {
433
+ const info = resolveBinaryInfo(userDir, { fsImpl });
434
+ if (info && info.source !== "missing") {
435
+ connectorSource = info.source;
436
+ connectorVersion = info.version || connectorVersion;
437
+ return;
438
+ }
439
+ } catch {
440
+ // Ignore inspection errors for mocked/unusual binary paths
441
+ }
442
+
443
+ if (!connectorSource && binaryPath) {
444
+ const managedDir = path.join(userDir, "bin");
445
+ if (binaryPath === "cloudflared") {
446
+ connectorSource = "system";
447
+ } else if (binaryPath.startsWith(managedDir)) {
448
+ connectorSource = "managed";
449
+ }
450
+ }
451
+ }
452
+
453
+ function buildManifestOverrideFromAdvisories() {
454
+ const conn = updateAdvisories?.connector;
455
+ if (conn && conn.asset && conn.latest) {
456
+ return {
457
+ version: conn.latest,
458
+ asset: conn.asset,
459
+ };
460
+ }
461
+ if (
462
+ conn &&
463
+ conn.latest &&
464
+ PINNED_CONNECTOR_MANIFEST.version === conn.latest
465
+ ) {
466
+ return PINNED_CONNECTOR_MANIFEST;
467
+ }
468
+ return null;
469
+ }
470
+
471
+ async function runConnectorUpdate(manifestOverride) {
472
+ if (connectorUpdatePromise) {
473
+ return connectorUpdatePromise;
474
+ }
475
+
476
+ const myGen = connectorGen;
477
+ const previousBinaryPath = activeBinaryPath;
478
+ let daemonStoppedForSwap = false;
479
+
480
+ connectorUpdate = { state: "updating", error: null };
481
+ publishStatus();
482
+
483
+ connectorUpdatePromise = (async () => {
484
+ try {
485
+ const result = await updateBinary(userDir, RED?.log, {
486
+ fetchImpl,
487
+ fsImpl,
488
+ manifest: manifestOverride || buildManifestOverrideFromAdvisories(),
489
+ stopDaemon: async () => {
490
+ if (activeDaemon) {
491
+ const prev = activeDaemon;
492
+ activeDaemon = null;
493
+ daemonStoppedForSwap = true;
494
+ await stopDaemonCleanly(prev);
495
+ }
496
+ },
497
+ });
498
+
499
+ if (myGen !== connectorGen || !pluginConfig) {
500
+ return { status: 409, error: USER_ERRORS.CONCURRENT_CHANGE };
501
+ }
502
+
503
+ if (!result || result.reason === "system_managed") {
504
+ connectorSource = "system";
505
+ connectorUpdate = { state: "idle", error: null };
506
+ publishStatus();
507
+ return { status: 409, error: USER_ERRORS.CONNECTOR_SYSTEM_MANAGED };
508
+ }
509
+
510
+ if (result.version) {
511
+ connectorVersion = result.version;
512
+ }
513
+ connectorSource = "managed";
514
+ connectorUpdate = { state: "idle", error: null };
515
+
516
+ if (result.binaryPath) {
517
+ activeDaemon = launchDaemon(result.binaryPath, myGen);
518
+ } else if (daemonStoppedForSwap && previousBinaryPath) {
519
+ activeDaemon = launchDaemon(previousBinaryPath, myGen);
520
+ }
521
+
522
+ await performSync("connector_update");
523
+ return { status: 200, body: getStatus() };
524
+ } catch (err) {
525
+ if (myGen === connectorGen && pluginConfig) {
526
+ if (daemonStoppedForSwap && !activeDaemon && previousBinaryPath) {
527
+ try {
528
+ activeDaemon = launchDaemon(previousBinaryPath, myGen);
529
+ } catch {
530
+ // Ignore recovery launch errors; state will reflect failure
531
+ }
532
+ }
533
+ connectorUpdate = {
534
+ state: "error",
535
+ error: USER_ERRORS.CONNECTOR_UPDATE_FAILED,
536
+ };
537
+ RED?.log?.error?.(`[NR Connect] Connector update failed: ${sanitizeLogError(err)}`);
538
+ publishStatus();
539
+ }
540
+ return { status: 500, error: USER_ERRORS.CONNECTOR_UPDATE_FAILED };
541
+ } finally {
542
+ connectorUpdatePromise = null;
543
+ }
544
+ })();
545
+
546
+ return connectorUpdatePromise;
547
+ }
548
+
549
+ function maybeTriggerAutoUpdate(summary) {
550
+ if (!pluginConfig || connectorSource !== "managed" || connectorUpdatePromise) return;
551
+ const latest = summary?.connector?.latest;
552
+ if (!latest || !summary.connector.available) return;
553
+
554
+ const autoEnabled =
555
+ summary.connector.required || String(env?.NR_CONNECT_AUTO_UPDATE_CONNECTOR) === "true";
556
+ if (!autoEnabled) return;
557
+ if (lastAutoUpdateAttemptVersion === latest) return;
558
+
559
+ const manifestOverride = buildManifestOverrideFromAdvisories();
560
+ if (!manifestOverride) return;
561
+
562
+ lastAutoUpdateAttemptVersion = latest;
563
+ void runConnectorUpdate(manifestOverride);
564
+ }
565
+
566
+ function applySyncSchedule(syncDirective) {
567
+ if (!syncDirective || typeof syncDirective !== "object") return false;
568
+ let changed = false;
569
+ if (
570
+ typeof syncDirective.intervalMs === "number" &&
571
+ Number.isFinite(syncDirective.intervalMs) &&
572
+ syncDirective.intervalMs > 0
573
+ ) {
574
+ const clamped = Math.min(
575
+ MAX_SYNC_INTERVAL_MS,
576
+ Math.max(MIN_SYNC_INTERVAL_MS, Math.round(syncDirective.intervalMs))
577
+ );
578
+ if (clamped !== currentSyncIntervalMs) {
579
+ currentSyncIntervalMs = clamped;
580
+ changed = true;
581
+ }
582
+ }
583
+ if (
584
+ typeof syncDirective.jitterRatio === "number" &&
585
+ Number.isFinite(syncDirective.jitterRatio)
586
+ ) {
587
+ const clampedJitter = Math.max(0, Math.min(0.5, syncDirective.jitterRatio));
588
+ if (clampedJitter !== currentJitterRatio) {
589
+ currentJitterRatio = clampedJitter;
590
+ changed = true;
591
+ }
592
+ }
593
+ return changed;
594
+ }
595
+
596
+ function computeNextSyncDelayMs() {
597
+ if (currentJitterRatio <= 0) {
598
+ return Math.max(10, Math.round(currentSyncIntervalMs));
599
+ }
600
+ const offset = (randomFn() * 2 - 1) * currentJitterRatio;
601
+ return Math.max(10, Math.round(currentSyncIntervalMs * (1 + offset)));
602
+ }
603
+
604
+ function scheduleHeartbeat(myGen) {
605
+ if (heartbeatTimer) {
606
+ clearTimeout(heartbeatTimer);
607
+ heartbeatTimer = null;
608
+ }
609
+ if (myGen !== connectorGen || !pluginConfig) return;
610
+
611
+ const delayMs = computeNextSyncDelayMs();
612
+ heartbeatTimer = setTimeout(async () => {
613
+ heartbeatTimer = null;
614
+ if (myGen !== connectorGen || !pluginConfig) return;
615
+ try {
616
+ await performSync("periodic");
617
+ } finally {
618
+ if (myGen === connectorGen && pluginConfig) {
619
+ scheduleHeartbeat(myGen);
620
+ }
621
+ }
622
+ }, delayMs);
623
+ if (typeof heartbeatTimer.unref === "function") {
624
+ heartbeatTimer.unref();
625
+ }
626
+ }
627
+
628
+ async function performSync(reason = "periodic") {
629
+ const configSnapshot = pluginConfig;
630
+ if (!configSnapshot) return null;
631
+ const myGen = connectorGen;
632
+
633
+ try {
634
+ const result = await syncPortal(
635
+ RED,
636
+ configSnapshot,
637
+ {
638
+ daemonState: connectorState,
639
+ pluginVersion,
640
+ reason,
641
+ ...(connectorVersion ? { connectorVersion } : {}),
642
+ ...(connectorSource ? { connectorSource } : {}),
643
+ },
644
+ fetchImpl
645
+ );
646
+ if (myGen !== connectorGen || pluginConfig !== configSnapshot) {
647
+ return null;
648
+ }
649
+
650
+ if (result && result.ok) {
651
+ checkIn = { state: "ok", at: new Date().toISOString() };
652
+ const changed = applySyncResponseMetadata(configSnapshot, result.response);
653
+ if (result.response && result.response.updates && typeof result.response.updates === "object") {
654
+ updateAdvisories = result.response.updates;
655
+ }
656
+ const scheduleChanged = applySyncSchedule(result.response?.sync);
657
+ if (scheduleChanged && heartbeatTimer) {
658
+ scheduleHeartbeat(myGen);
659
+ }
660
+ if (changed && !isManagedByEnv()) {
661
+ try {
662
+ savePersistedConfig(configSnapshot);
663
+ } catch (persistErr) {
664
+ RED?.log?.warn?.(
665
+ `[NR Connect] Failed to persist refreshed metadata: ${sanitizeLogError(persistErr)}`
666
+ );
667
+ }
668
+ }
669
+
670
+ const summary = buildUpdateSummary({
671
+ pluginVersion,
672
+ connectorVersion,
673
+ connectorSource,
674
+ advisories: updateAdvisories,
675
+ connectorUpdateState: connectorUpdate,
676
+ });
677
+ maybeTriggerAutoUpdate(summary);
678
+ }
679
+ } catch (err) {
680
+ if (myGen !== connectorGen || pluginConfig !== configSnapshot) {
681
+ return null;
682
+ }
683
+
684
+ const httpStatus = err && typeof err.status === "number" ? err.status : null;
685
+ if (httpStatus === 401 || httpStatus === 403 || httpStatus === 404) {
686
+ checkIn = { state: "invalid", at: checkIn.at };
687
+ } else {
688
+ checkIn = { state: "unreachable", at: checkIn.at };
689
+ }
690
+ RED?.log?.debug?.(`[NR Connect] Sync error: ${sanitizeLogError(err)}`);
691
+ }
692
+
693
+ publishStatus();
694
+ return getStatus();
695
+ }
696
+
697
+ async function startConnector(config, startOptions = {}) {
698
+ const { runInitialSync = true, syncReason = "startup" } = startOptions;
699
+ const myGen = ++connectorGen;
700
+ stopDaemonAndHeartbeat();
701
+
702
+ pluginConfig = config || null;
703
+ connectorVersion = null;
704
+ connectorSource = null;
705
+ updateAdvisories = null;
706
+ connectorUpdate = { state: "idle", error: null };
707
+ lastAutoUpdateAttemptVersion = null;
708
+
709
+ if (!pluginConfig) {
710
+ connectorState = "not_connected";
711
+ checkIn = { state: "never", at: null };
712
+ publishStatus();
713
+ return;
714
+ }
715
+
716
+ connectorState = "preparing";
717
+ publishStatus();
718
+
719
+ try {
720
+ const binaryPath = await ensureBinary(userDir, RED?.log, { fetchImpl });
721
+ if (myGen !== connectorGen) return;
722
+
723
+ refreshBinaryMetadata(binaryPath);
724
+ activeDaemon = launchDaemon(binaryPath, myGen);
725
+ } catch (err) {
726
+ if (myGen !== connectorGen) return;
727
+ connectorState = "error";
728
+ RED?.log?.error?.(`[NR Connect] Connector startup failed: ${sanitizeLogError(err)}`);
729
+ publishStatus();
730
+ }
731
+
732
+ if (myGen !== connectorGen) return;
733
+ if (runInitialSync) {
734
+ await performSync(syncReason);
735
+ }
736
+ if (myGen === connectorGen && pluginConfig) {
737
+ scheduleHeartbeat(myGen);
738
+ }
739
+ }
740
+
741
+ /**
742
+ * Initialize the connection manager on plugin load using env or disk config.
743
+ */
744
+ function init() {
745
+ const initialConfig = loadPersistedConfig();
746
+ if (initialConfig) {
747
+ checkIn = { state: "never", at: null };
748
+ return startConnector(initialConfig, { runInitialSync: true, syncReason: "startup" });
749
+ }
750
+ connectorState = "not_connected";
751
+ checkIn = { state: "never", at: null };
752
+ publishStatus();
753
+ return Promise.resolve();
754
+ }
755
+
756
+ /**
757
+ * Validate a pasted connection code with one verification sync before
758
+ * persisting `.nr-connect.json` or restarting the connector.
759
+ */
760
+ async function connect(rawCode) {
761
+ if (isManagedByEnv()) {
762
+ return { status: 409, error: USER_ERRORS.ENV_MANAGED };
763
+ }
764
+
765
+ const trimmed = typeof rawCode === "string" ? rawCode.trim() : "";
766
+ if (!trimmed) {
767
+ return { status: 400, error: USER_ERRORS.MISSING_CODE };
768
+ }
769
+
770
+ let decoded;
771
+ try {
772
+ decoded = decodeToken(trimmed);
773
+ } catch {
774
+ return { status: 400, error: USER_ERRORS.INVALID_CODE };
775
+ }
776
+
777
+ const candidateConfig = {
778
+ ...decoded,
779
+ requireSecureAccess: false,
780
+ name: null,
781
+ url: null,
782
+ };
783
+
784
+ const opSeq = ++mutationSeq;
785
+ let initialCheckIn;
786
+ let initialUpdates = null;
787
+
788
+ try {
789
+ const result = await syncPortal(
790
+ RED,
791
+ candidateConfig,
792
+ { daemonState: "connecting", pluginVersion, reason: "connect" },
793
+ fetchImpl
794
+ );
795
+ if (opSeq !== mutationSeq) {
796
+ return { status: 409, error: USER_ERRORS.CONCURRENT_CHANGE };
797
+ }
798
+ if (result && result.response) {
799
+ applySyncResponseMetadata(candidateConfig, result.response);
800
+ applySyncSchedule(result.response.sync);
801
+ if (result.response.updates && typeof result.response.updates === "object") {
802
+ initialUpdates = result.response.updates;
803
+ }
804
+ }
805
+ initialCheckIn = { state: "ok", at: new Date().toISOString() };
806
+ } catch (err) {
807
+ if (opSeq !== mutationSeq) {
808
+ return { status: 409, error: USER_ERRORS.CONCURRENT_CHANGE };
809
+ }
810
+ const httpStatus = err && typeof err.status === "number" ? err.status : null;
811
+ if (httpStatus === 401 || httpStatus === 403 || httpStatus === 404) {
812
+ return { status: 400, error: USER_ERRORS.INVALID_CODE };
813
+ }
814
+ // Network/5xx errors still save and start so the sidebar reports unreachable state cleanly.
815
+ initialCheckIn = { state: "unreachable", at: null };
816
+ RED?.log?.warn?.(`[NR Connect] Initial sync unreachable: ${sanitizeLogError(err)}`);
817
+ }
818
+
819
+ savePersistedConfig(candidateConfig);
820
+ checkIn = initialCheckIn;
821
+ await startConnector(candidateConfig, { runInitialSync: false });
822
+ if (initialUpdates) {
823
+ updateAdvisories = initialUpdates;
824
+ const summary = buildUpdateSummary({
825
+ pluginVersion,
826
+ connectorVersion,
827
+ connectorSource,
828
+ advisories: updateAdvisories,
829
+ connectorUpdateState: connectorUpdate,
830
+ });
831
+ maybeTriggerAutoUpdate(summary);
832
+ publishStatus();
833
+ }
834
+ return { status: 200, body: getStatus() };
835
+ }
836
+
837
+ /**
838
+ * Stop the connector and sync timer, delete `.nr-connect.json`, and clear
839
+ * active config so Require secure access disables immediately.
840
+ */
841
+ function disconnect() {
842
+ if (isManagedByEnv()) {
843
+ return { status: 409, error: USER_ERRORS.ENV_MANAGED };
844
+ }
845
+
846
+ mutationSeq += 1;
847
+ connectorGen += 1;
848
+ stopDaemonAndHeartbeat();
849
+ pluginConfig = null;
850
+ connectorState = "not_connected";
851
+ connectorVersion = null;
852
+ connectorSource = null;
853
+ updateAdvisories = null;
854
+ connectorUpdate = { state: "idle", error: null };
855
+ lastAutoUpdateAttemptVersion = null;
856
+ checkIn = { state: "never", at: null };
857
+ deletePersistedConfig();
858
+ const status = publishStatus();
859
+ return { status: 200, body: status };
860
+ }
861
+
862
+ /**
863
+ * Run an immediate portal sync for the active connection.
864
+ */
865
+ async function checkInNow() {
866
+ if (!pluginConfig) {
867
+ return { status: 400, error: USER_ERRORS.NOT_CONNECTED };
868
+ }
869
+ const status = await performSync("manual");
870
+ return { status: 200, body: status || getStatus() };
871
+ }
872
+
873
+ /**
874
+ * Manually trigger a verified update of the managed connector binary.
875
+ */
876
+ async function updateConnectorNow() {
877
+ if (!pluginConfig) {
878
+ return { status: 400, error: USER_ERRORS.NOT_CONNECTED };
879
+ }
880
+ if (connectorSource === "system") {
881
+ return { status: 409, error: USER_ERRORS.CONNECTOR_SYSTEM_MANAGED };
882
+ }
883
+ return runConnectorUpdate(buildManifestOverrideFromAdvisories());
884
+ }
885
+
886
+ /**
887
+ * Publish updated page list and trigger debounced sync when flows are deployed/started.
888
+ */
889
+ function handleFlowsStarted() {
890
+ publishStatus();
891
+ if (!pluginConfig) {
892
+ return Promise.resolve(null);
893
+ }
894
+ if (deployDebounceMs <= 0) {
895
+ return performSync("deploy");
896
+ }
897
+
898
+ const myGen = connectorGen;
899
+ if (deployDebounceTimer) {
900
+ clearTimeout(deployDebounceTimer);
901
+ deployDebounceTimer = null;
902
+ }
903
+
904
+ return new Promise((resolve) => {
905
+ deployDebounceWaiters.push(resolve);
906
+ deployDebounceTimer = setTimeout(async () => {
907
+ deployDebounceTimer = null;
908
+ const waiters = deployDebounceWaiters;
909
+ deployDebounceWaiters = [];
910
+ let result = null;
911
+ if (myGen === connectorGen && pluginConfig) {
912
+ result = await performSync("deploy");
913
+ }
914
+ for (const done of waiters) {
915
+ done(result);
916
+ }
917
+ }, deployDebounceMs);
918
+ });
919
+ }
920
+
921
+ /**
922
+ * Stop daemon and background timers cleanly on shutdown.
923
+ */
924
+ function stop() {
925
+ mutationSeq += 1;
926
+ connectorGen += 1;
927
+ stopDaemonAndHeartbeat();
928
+ }
929
+
930
+ return {
931
+ init,
932
+ stop,
933
+ getActiveConfig,
934
+ getStatus,
935
+ getDiagnostics,
936
+ connect,
937
+ disconnect,
938
+ checkInNow,
939
+ updateConnectorNow,
940
+ performSync,
941
+ handleFlowsStarted,
942
+ };
943
+ }
944
+
945
+ function getPermissionMiddleware(RED, permission) {
946
+ if (typeof RED?.auth?.needsPermission === "function") {
947
+ return RED.auth.needsPermission(permission);
948
+ }
949
+ return (_req, _res, next) => next();
950
+ }
951
+
952
+ /**
953
+ * Register the `/nr-connect/*` admin routes on `RED.httpAdmin`.
954
+ */
955
+ function registerAdminRoutes(RED, manager) {
956
+ const httpAdmin = RED?.httpAdmin;
957
+ if (!httpAdmin) return;
958
+
959
+ const readAuth = getPermissionMiddleware(RED, "flows.read");
960
+ const writeAuth = getPermissionMiddleware(RED, "flows.write");
961
+
962
+ httpAdmin.get("/nr-connect/status", readAuth, (_req, res) => {
963
+ return res.json(manager.getStatus());
964
+ });
965
+
966
+ httpAdmin.get("/nr-connect/diagnostics", readAuth, (_req, res) => {
967
+ return res.json(manager.getDiagnostics());
968
+ });
969
+
970
+ httpAdmin.get("/nr-connect/qr", readAuth, (req, res) => {
971
+ const status = manager.getStatus();
972
+ if (!status.connected || !status.url) {
973
+ return res.status(404).json({ error: USER_ERRORS.NOT_CONNECTED });
974
+ }
975
+ const rawPath = typeof req.query?.path === "string" ? req.query.path : "";
976
+ const targetUrl = resolveInstanceQrUrl(status.url, rawPath);
977
+ if (!targetUrl) {
978
+ return res.status(400).json({ error: "Invalid QR code target path." });
979
+ }
980
+ const instanceName = status.name || "NR Connect";
981
+ const title = `QR code for ${instanceName}`;
982
+ const svg = renderStyledQrSvg(targetUrl, {
983
+ quietZone: 4,
984
+ pixelSize: 512,
985
+ title,
986
+ });
987
+ return res.json({
988
+ url: targetUrl,
989
+ title,
990
+ filenameBase: buildQrFilenameBase(instanceName),
991
+ svg,
992
+ });
993
+ });
994
+
995
+ httpAdmin.post("/nr-connect/connect", writeAuth, async (req, res) => {
996
+ try {
997
+ const code = typeof req.body?.code === "string" ? req.body.code : "";
998
+ const outcome = await manager.connect(code);
999
+ if (outcome.status !== 200) {
1000
+ return res.status(outcome.status).json({ error: outcome.error });
1001
+ }
1002
+ return res.json(outcome.body);
1003
+ } catch (err) {
1004
+ RED?.log?.error?.(`[NR Connect] Connect route error: ${sanitizeLogError(err)}`);
1005
+ return res.status(500).json({ error: USER_ERRORS.CONNECT_FAILED });
1006
+ }
1007
+ });
1008
+
1009
+ httpAdmin.post("/nr-connect/disconnect", writeAuth, (_req, res) => {
1010
+ try {
1011
+ const outcome = manager.disconnect();
1012
+ if (outcome.status !== 200) {
1013
+ return res.status(outcome.status).json({ error: outcome.error });
1014
+ }
1015
+ return res.json(outcome.body);
1016
+ } catch (err) {
1017
+ RED?.log?.error?.(`[NR Connect] Disconnect route error: ${sanitizeLogError(err)}`);
1018
+ return res.status(500).json({ error: USER_ERRORS.DISCONNECT_FAILED });
1019
+ }
1020
+ });
1021
+
1022
+ httpAdmin.post("/nr-connect/check-in", writeAuth, async (_req, res) => {
1023
+ try {
1024
+ const outcome = await manager.checkInNow();
1025
+ if (outcome.status !== 200) {
1026
+ return res.status(outcome.status).json({ error: outcome.error });
1027
+ }
1028
+ return res.json(outcome.body);
1029
+ } catch (err) {
1030
+ RED?.log?.error?.(`[NR Connect] Check-in route error: ${sanitizeLogError(err)}`);
1031
+ return res.status(500).json({ error: USER_ERRORS.CHECKIN_FAILED });
1032
+ }
1033
+ });
1034
+
1035
+ httpAdmin.post("/nr-connect/update-connector", writeAuth, async (_req, res) => {
1036
+ try {
1037
+ const outcome = await manager.updateConnectorNow();
1038
+ if (outcome.status !== 200) {
1039
+ return res.status(outcome.status).json({ error: outcome.error });
1040
+ }
1041
+ return res.json(outcome.body);
1042
+ } catch (err) {
1043
+ RED?.log?.error?.(`[NR Connect] Connector update route error: ${sanitizeLogError(err)}`);
1044
+ return res.status(500).json({ error: USER_ERRORS.CONNECTOR_UPDATE_FAILED });
1045
+ }
1046
+ });
1047
+ }
1048
+
1049
+ module.exports = {
1050
+ DEFAULT_SYNC_INTERVAL_MS,
1051
+ MIN_SYNC_INTERVAL_MS,
1052
+ MAX_SYNC_INTERVAL_MS,
1053
+ DEFAULT_SYNC_JITTER_RATIO,
1054
+ DEPLOY_DEBOUNCE_MS,
1055
+ HEARTBEAT_INTERVAL_MS,
1056
+ STATUS_TOPIC,
1057
+ USER_ERRORS,
1058
+ createConnectionManager,
1059
+ registerAdminRoutes,
1060
+ };