@xkwdstore/agent 2.1.5 → 2.1.7

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.
@@ -1,319 +1,319 @@
1
- 'use strict';
2
-
3
- /**
4
- * BrokerConnectionSupervisor — ONE reconnect lifecycle shared by the foreground
5
- * `start` agent and the machine `service` broker (2.1.0 reconnect fix).
6
- *
7
- * WHY THIS EXISTS
8
- * The production machine broker must be long-lived. A transient loss of network,
9
- * DNS, TLS reachability, backend availability, the WebSocket, or a heartbeat must
10
- * NOT require a manual service restart, a user login, a re-pair, or a new device
11
- * identity. The broker must transparently reconnect with the SAME enrolled
12
- * identity.
13
- *
14
- * The foreground `start` path had an ad-hoc reconnect; the `service` path had
15
- * NONE, so a dropped production WebSocket left the broker idle forever. This
16
- * module is the single supervisor used by BOTH paths.
17
- *
18
- * GUARANTEES
19
- * - at most ONE reconnect timer and ONE in-flight connect attempt (Phase 7);
20
- * - at most ONE active WebSocket; a stale socket's close is ignored;
21
- * - bounded exponential backoff with jitter, reset after a stable connect;
22
- * - `stop()` cancels the timer and prevents any later reconnect;
23
- * - a pong watchdog terminates a half-open socket so the close path runs;
24
- * - transport recovery only: it never touches the device id/key/pairing.
25
- *
26
- * Dependencies (timers, random, now, connect) are injectable for deterministic
27
- * tests. No secrets are ever logged.
28
- */
29
-
30
- const DEFAULT_BACKOFF = Object.freeze({ baseMs: 1000, maxMs: 60000, jitterMs: 1000, factor: 2 });
31
- // Authentication is a PERMANENT failure class: after this many consecutive
32
- // rejections the supervisor stops retrying entirely. Retrying a revoked/replaced
33
- // device forever is useless and produced >43k log lines in the field.
34
- const DEFAULT_AUTH_MAX_ATTEMPTS = 3;
35
- // The agent heartbeat is every 10s (see sessionHandler). A half-open socket is
36
- // terminated only after several missed pongs — deliberately NOT aggressive.
37
- const DEFAULT_PONG_TIMEOUT_MS = 60000;
38
-
39
- function _safeMsg(e) { return String((e && e.message) || e || 'unknown').slice(0, 200); }
40
-
41
- /** Auth/credential failures must not busy-loop AND must not regenerate identity. */
42
- function isAuthErrorMessage(msg) {
43
- return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol|device is not enrolled|not enrolled|replaced_by_new_device|replaced by (a )?new device/i.test(String(msg || ''));
44
- }
45
-
46
- function createBrokerConnectionSupervisor(opts = {}) {
47
- const connect = opts.connect;
48
- if (typeof connect !== 'function') throw new Error('createBrokerConnectionSupervisor: connect is required');
49
-
50
- const onConnected = opts.onConnected || (() => {});
51
- const onDisconnected = opts.onDisconnected || (() => {});
52
- const onAuthRejected = opts.onAuthRejected || null;
53
- const onAuthBlocked = opts.onAuthBlocked || null;
54
- const onStateChange = opts.onStateChange || null;
55
- const log = opts.log || (() => {});
56
- const timer = opts.timers || {};
57
- const setTimeoutFn = timer.setTimeout || setTimeout;
58
- const clearTimeoutFn = timer.clearTimeout || clearTimeout;
59
- const setIntervalFn = timer.setInterval || setInterval;
60
- const clearIntervalFn = timer.clearInterval || clearInterval;
61
- const now = opts.now || (() => Date.now());
62
- const random = opts.random || Math.random;
63
- const backoff = { ...DEFAULT_BACKOFF, ...(opts.backoff || {}) };
64
- // 0 = retry forever (machine service). >0 = bounded (foreground start).
65
- const maxAttempts = Number.isInteger(opts.maxAttempts) ? opts.maxAttempts : 0;
66
- const maxAuthAttempts = Number.isInteger(opts.maxAuthAttempts) && opts.maxAuthAttempts > 0
67
- ? opts.maxAuthAttempts
68
- : DEFAULT_AUTH_MAX_ATTEMPTS;
69
- const pongTimeoutMs = Number.isInteger(opts.pongTimeoutMs) ? opts.pongTimeoutMs : DEFAULT_PONG_TIMEOUT_MS;
70
-
71
- let state = 'idle'; // idle|connecting|connected|disconnected|reconnecting|auth_blocked|stopping
72
- let ws = null;
73
- let retryTimer = null;
74
- let stopped = false;
75
- let attempt = 0;
76
- let authFailures = 0;
77
- let authNotified = false;
78
- let connectInFlight = false;
79
- let heartbeatTimer = null;
80
- let lastPongAt = 0;
81
-
82
- const diag = {
83
- lastConnectedAt: null,
84
- lastDisconnectedAt: null,
85
- lastDisconnectCode: null,
86
- lastDisconnectReason: null,
87
- reconnectAttempt: 0,
88
- nextRetryMs: null,
89
- authBlocked: false,
90
- authFailures: 0,
91
- reauthorizationRequired: false,
92
- lastAuthFailureAt: null,
93
- };
94
-
95
- function getState() {
96
- return {
97
- state,
98
- deviceIdentityPreserved: true,
99
- ...diag,
100
- };
101
- }
102
-
103
- function setState(s) {
104
- state = s;
105
- try { if (onStateChange) onStateChange(s, getState()); } catch { /* never break the lifecycle */ }
106
- }
107
-
108
- function _clearRetry() {
109
- if (retryTimer) { try { clearTimeoutFn(retryTimer); } catch {} retryTimer = null; }
110
- }
111
-
112
- function _stopHeartbeatWatch() {
113
- if (heartbeatTimer) { try { clearIntervalFn(heartbeatTimer); } catch {} heartbeatTimer = null; }
114
- }
115
-
116
- function _startHeartbeatWatch(sock) {
117
- _stopHeartbeatWatch();
118
- lastPongAt = now();
119
- try {
120
- sock.on('pong', () => { lastPongAt = now(); });
121
- } catch { /* fake sockets in tests may not support on */ }
122
- heartbeatTimer = setIntervalFn(() => {
123
- if (stopped || ws !== sock) { _stopHeartbeatWatch(); return; }
124
- const silentFor = now() - lastPongAt;
125
- if (silentFor > pongTimeoutMs) {
126
- // Half-open socket: the TCP peer is gone but no close event arrived.
127
- // Terminating drives the normal close path -> reconnect.
128
- log(`[broker] heartbeat timeout (silent ${Math.round(silentFor)}ms); terminating socket`);
129
- try { sock.terminate(); } catch {}
130
- }
131
- }, Math.max(1000, Math.floor(pongTimeoutMs / 3)));
132
- if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
133
- }
134
-
135
- function _scheduleReconnect(info = {}) {
136
- if (stopped) return;
137
- if (retryTimer) return; // SINGLE reconnect timer invariant
138
-
139
- // ── Permanent authentication failures ──────────────────────────────────
140
- // A revoked/replaced device cannot recover by retrying. Count consecutive
141
- // auth rejections, notify once, and stop after a small bound so a dead
142
- // credential can never produce a retry/log storm. Manual recovery (after
143
- // owner re-authorization) calls start()/adopt() and resets this state.
144
- if (info.auth) {
145
- authFailures += 1;
146
- diag.authFailures = authFailures;
147
- diag.authBlocked = true;
148
- diag.lastAuthFailureAt = now();
149
- if (info.code !== undefined && info.code !== null) diag.lastDisconnectCode = info.code;
150
- if (info.reason) diag.lastDisconnectReason = String(info.reason).slice(0, 200);
151
- if (!authNotified) {
152
- authNotified = true;
153
- if (onAuthRejected) { try { onAuthRejected({ error: info.error || null, code: info.code ?? null, reason: info.reason || null }); } catch {} }
154
- }
155
- if (authFailures >= maxAuthAttempts) {
156
- diag.reauthorizationRequired = true;
157
- diag.nextRetryMs = null;
158
- _clearRetry();
159
- setState('auth_blocked');
160
- log(`[broker] authentication failed ${authFailures} times; retries stopped — reauthorization required (device identity preserved)`);
161
- if (onAuthBlocked) {
162
- try { onAuthBlocked({ authFailures, code: diag.lastDisconnectCode, reason: diag.lastDisconnectReason }); } catch {}
163
- }
164
- return;
165
- }
166
- }
167
-
168
- attempt += 1;
169
- diag.reconnectAttempt = attempt;
170
- diag.authBlocked = info.auth === true;
171
-
172
- if (maxAttempts > 0 && attempt > maxAttempts) {
173
- setState('disconnected');
174
- log(`[broker] reconnect exhausted after ${maxAttempts} attempts; giving up (identity preserved)`);
175
- if (opts.onExhausted) { try { opts.onExhausted(getState()); } catch {} }
176
- return;
177
- }
178
-
179
- const exp = Math.min(backoff.baseMs * Math.pow(backoff.factor, attempt - 1), backoff.maxMs);
180
- const jitter = Math.floor(random() * backoff.jitterMs);
181
- const delay = exp + jitter;
182
- diag.nextRetryMs = delay;
183
- setState(info.auth ? 'auth_blocked' : 'reconnecting');
184
- log(`[broker] reconnect scheduled attempt=${attempt} retry=${Math.round(delay)}ms${info.auth ? ' auth=blocked' : ''}`);
185
- retryTimer = setTimeoutFn(() => { retryTimer = null; _attemptConnect(); }, delay);
186
- }
187
-
188
- async function _attemptConnect() {
189
- if (stopped) return;
190
- if (connectInFlight) return; // SINGLE in-flight attempt invariant
191
- if (ws) return; // already connected
192
- connectInFlight = true;
193
- setState(attempt > 0 ? 'reconnecting' : 'connecting');
194
- log(`[broker] ${attempt > 0 ? 'reconnecting' : 'connecting'} attempt=${attempt}`);
195
-
196
- let sock;
197
- try {
198
- sock = await connect();
199
- } catch (err) {
200
- connectInFlight = false;
201
- if (stopped) return;
202
- const auth = isAuthErrorMessage(_safeMsg(err));
203
- if (!auth || authFailures === 0) log(`[broker] connect failed: ${_safeMsg(err)}`);
204
- _scheduleReconnect({ auth, code: err && err.code ? err.code : null, reason: _safeMsg(err), error: err });
205
- return;
206
- }
207
- connectInFlight = false;
208
- if (stopped) { try { sock.close(1000, 'stopping'); } catch {} return; }
209
-
210
- ws = sock;
211
- attempt = 0;
212
- authFailures = 0;
213
- authNotified = false;
214
- diag.lastConnectedAt = now();
215
- diag.nextRetryMs = null;
216
- diag.reconnectAttempt = 0;
217
- diag.authBlocked = false;
218
- diag.authFailures = 0;
219
- diag.reauthorizationRequired = false;
220
- setState('connected');
221
- log('[broker] connected');
222
-
223
- try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
224
- // An 'error' event immediately preceded by nothing else must not crash the
225
- // process; the close path handles reconnection.
226
- try { sock.on('error', () => {}); } catch {}
227
- _startHeartbeatWatch(sock);
228
-
229
- try { await onConnected(sock); } catch (e) { log(`[broker] onConnected error: ${_safeMsg(e)}`); }
230
- }
231
-
232
- function _handleClose(closedSock, code, reason) {
233
- if (stopped) return;
234
- if (ws !== closedSock) return; // stale socket (already replaced) — ignore
235
- ws = null;
236
- _stopHeartbeatWatch();
237
- const reasonStr = reason ? reason.toString() : '';
238
- diag.lastDisconnectedAt = now();
239
- diag.lastDisconnectCode = code;
240
- diag.lastDisconnectReason = reasonStr;
241
-
242
- if (code === 4003) {
243
- diag.authBlocked = true;
244
- if (!authNotified) log('[broker] disconnected code=4003 (authentication/identity)');
245
- // Permanent class: bounded by maxAuthAttempts, then retries stop. Identity
246
- // is NEVER regenerated or deleted here.
247
- _scheduleReconnect({ auth: true, code, reason: reasonStr });
248
- return;
249
- }
250
-
251
- log(`[broker] disconnected code=${code}${reasonStr ? ' reason=' + reasonStr : ''}`);
252
- try { const r = onDisconnected({ code, reason: reasonStr }); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
253
- _scheduleReconnect({});
254
- }
255
-
256
- function start() {
257
- stopped = false;
258
- attempt = 0;
259
- authFailures = 0;
260
- authNotified = false;
261
- diag.authBlocked = false;
262
- diag.authFailures = 0;
263
- diag.reauthorizationRequired = false;
264
- diag.nextRetryMs = null;
265
- return _attemptConnect();
266
- }
267
-
268
- /**
269
- * Adopt an ALREADY-authenticated socket (the foreground `start` path connects
270
- * first, including its one-time enrollment flow, then hands the live socket to
271
- * the supervisor for its reconnect lifecycle). Binding happens through
272
- * `onConnected` exactly once, so the handler is never double-installed.
273
- */
274
- function adopt(sock) {
275
- if (!sock) return;
276
- stopped = false;
277
- connectInFlight = false;
278
- attempt = 0;
279
- authFailures = 0;
280
- authNotified = false;
281
- ws = sock;
282
- diag.lastConnectedAt = now();
283
- diag.nextRetryMs = null;
284
- diag.reconnectAttempt = 0;
285
- diag.authBlocked = false;
286
- diag.authFailures = 0;
287
- diag.reauthorizationRequired = false;
288
- setState('connected');
289
- log('[broker] connected');
290
- try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
291
- try { sock.on('error', () => {}); } catch {}
292
- _startHeartbeatWatch(sock);
293
- try { const r = onConnected(sock); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
294
- }
295
-
296
- function stop() {
297
- if (stopped) return;
298
- stopped = true;
299
- _clearRetry();
300
- _stopHeartbeatWatch();
301
- setState('stopping');
302
- const sock = ws;
303
- ws = null;
304
- if (sock) { try { sock.close(1000, 'shutdown'); } catch {} }
305
- }
306
-
307
- return {
308
- start,
309
- adopt,
310
- stop,
311
- getState,
312
- // Exported for white-box deterministic tests.
313
- _handleClose,
314
- _attemptConnect,
315
- _isAuthError: (e) => isAuthErrorMessage(_safeMsg(e)),
316
- };
317
- }
318
-
319
- module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_AUTH_MAX_ATTEMPTS, DEFAULT_PONG_TIMEOUT_MS };
1
+ 'use strict';
2
+
3
+ /**
4
+ * BrokerConnectionSupervisor — ONE reconnect lifecycle shared by the foreground
5
+ * `start` agent and the machine `service` broker (2.1.0 reconnect fix).
6
+ *
7
+ * WHY THIS EXISTS
8
+ * The production machine broker must be long-lived. A transient loss of network,
9
+ * DNS, TLS reachability, backend availability, the WebSocket, or a heartbeat must
10
+ * NOT require a manual service restart, a user login, a re-pair, or a new device
11
+ * identity. The broker must transparently reconnect with the SAME enrolled
12
+ * identity.
13
+ *
14
+ * The foreground `start` path had an ad-hoc reconnect; the `service` path had
15
+ * NONE, so a dropped production WebSocket left the broker idle forever. This
16
+ * module is the single supervisor used by BOTH paths.
17
+ *
18
+ * GUARANTEES
19
+ * - at most ONE reconnect timer and ONE in-flight connect attempt (Phase 7);
20
+ * - at most ONE active WebSocket; a stale socket's close is ignored;
21
+ * - bounded exponential backoff with jitter, reset after a stable connect;
22
+ * - `stop()` cancels the timer and prevents any later reconnect;
23
+ * - a pong watchdog terminates a half-open socket so the close path runs;
24
+ * - transport recovery only: it never touches the device id/key/pairing.
25
+ *
26
+ * Dependencies (timers, random, now, connect) are injectable for deterministic
27
+ * tests. No secrets are ever logged.
28
+ */
29
+
30
+ const DEFAULT_BACKOFF = Object.freeze({ baseMs: 1000, maxMs: 60000, jitterMs: 1000, factor: 2 });
31
+ // Authentication is a PERMANENT failure class: after this many consecutive
32
+ // rejections the supervisor stops retrying entirely. Retrying a revoked/replaced
33
+ // device forever is useless and produced >43k log lines in the field.
34
+ const DEFAULT_AUTH_MAX_ATTEMPTS = 3;
35
+ // The agent heartbeat is every 10s (see sessionHandler). A half-open socket is
36
+ // terminated only after several missed pongs — deliberately NOT aggressive.
37
+ const DEFAULT_PONG_TIMEOUT_MS = 60000;
38
+
39
+ function _safeMsg(e) { return String((e && e.message) || e || 'unknown').slice(0, 200); }
40
+
41
+ /** Auth/credential failures must not busy-loop AND must not regenerate identity. */
42
+ function isAuthErrorMessage(msg) {
43
+ return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol|device is not enrolled|not enrolled|replaced_by_new_device|replaced by (a )?new device/i.test(String(msg || ''));
44
+ }
45
+
46
+ function createBrokerConnectionSupervisor(opts = {}) {
47
+ const connect = opts.connect;
48
+ if (typeof connect !== 'function') throw new Error('createBrokerConnectionSupervisor: connect is required');
49
+
50
+ const onConnected = opts.onConnected || (() => {});
51
+ const onDisconnected = opts.onDisconnected || (() => {});
52
+ const onAuthRejected = opts.onAuthRejected || null;
53
+ const onAuthBlocked = opts.onAuthBlocked || null;
54
+ const onStateChange = opts.onStateChange || null;
55
+ const log = opts.log || (() => {});
56
+ const timer = opts.timers || {};
57
+ const setTimeoutFn = timer.setTimeout || setTimeout;
58
+ const clearTimeoutFn = timer.clearTimeout || clearTimeout;
59
+ const setIntervalFn = timer.setInterval || setInterval;
60
+ const clearIntervalFn = timer.clearInterval || clearInterval;
61
+ const now = opts.now || (() => Date.now());
62
+ const random = opts.random || Math.random;
63
+ const backoff = { ...DEFAULT_BACKOFF, ...(opts.backoff || {}) };
64
+ // 0 = retry forever (machine service). >0 = bounded (foreground start).
65
+ const maxAttempts = Number.isInteger(opts.maxAttempts) ? opts.maxAttempts : 0;
66
+ const maxAuthAttempts = Number.isInteger(opts.maxAuthAttempts) && opts.maxAuthAttempts > 0
67
+ ? opts.maxAuthAttempts
68
+ : DEFAULT_AUTH_MAX_ATTEMPTS;
69
+ const pongTimeoutMs = Number.isInteger(opts.pongTimeoutMs) ? opts.pongTimeoutMs : DEFAULT_PONG_TIMEOUT_MS;
70
+
71
+ let state = 'idle'; // idle|connecting|connected|disconnected|reconnecting|auth_blocked|stopping
72
+ let ws = null;
73
+ let retryTimer = null;
74
+ let stopped = false;
75
+ let attempt = 0;
76
+ let authFailures = 0;
77
+ let authNotified = false;
78
+ let connectInFlight = false;
79
+ let heartbeatTimer = null;
80
+ let lastPongAt = 0;
81
+
82
+ const diag = {
83
+ lastConnectedAt: null,
84
+ lastDisconnectedAt: null,
85
+ lastDisconnectCode: null,
86
+ lastDisconnectReason: null,
87
+ reconnectAttempt: 0,
88
+ nextRetryMs: null,
89
+ authBlocked: false,
90
+ authFailures: 0,
91
+ reauthorizationRequired: false,
92
+ lastAuthFailureAt: null,
93
+ };
94
+
95
+ function getState() {
96
+ return {
97
+ state,
98
+ deviceIdentityPreserved: true,
99
+ ...diag,
100
+ };
101
+ }
102
+
103
+ function setState(s) {
104
+ state = s;
105
+ try { if (onStateChange) onStateChange(s, getState()); } catch { /* never break the lifecycle */ }
106
+ }
107
+
108
+ function _clearRetry() {
109
+ if (retryTimer) { try { clearTimeoutFn(retryTimer); } catch {} retryTimer = null; }
110
+ }
111
+
112
+ function _stopHeartbeatWatch() {
113
+ if (heartbeatTimer) { try { clearIntervalFn(heartbeatTimer); } catch {} heartbeatTimer = null; }
114
+ }
115
+
116
+ function _startHeartbeatWatch(sock) {
117
+ _stopHeartbeatWatch();
118
+ lastPongAt = now();
119
+ try {
120
+ sock.on('pong', () => { lastPongAt = now(); });
121
+ } catch { /* fake sockets in tests may not support on */ }
122
+ heartbeatTimer = setIntervalFn(() => {
123
+ if (stopped || ws !== sock) { _stopHeartbeatWatch(); return; }
124
+ const silentFor = now() - lastPongAt;
125
+ if (silentFor > pongTimeoutMs) {
126
+ // Half-open socket: the TCP peer is gone but no close event arrived.
127
+ // Terminating drives the normal close path -> reconnect.
128
+ log(`[broker] heartbeat timeout (silent ${Math.round(silentFor)}ms); terminating socket`);
129
+ try { sock.terminate(); } catch {}
130
+ }
131
+ }, Math.max(1000, Math.floor(pongTimeoutMs / 3)));
132
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
133
+ }
134
+
135
+ function _scheduleReconnect(info = {}) {
136
+ if (stopped) return;
137
+ if (retryTimer) return; // SINGLE reconnect timer invariant
138
+
139
+ // ── Permanent authentication failures ──────────────────────────────────
140
+ // A revoked/replaced device cannot recover by retrying. Count consecutive
141
+ // auth rejections, notify once, and stop after a small bound so a dead
142
+ // credential can never produce a retry/log storm. Manual recovery (after
143
+ // owner re-authorization) calls start()/adopt() and resets this state.
144
+ if (info.auth) {
145
+ authFailures += 1;
146
+ diag.authFailures = authFailures;
147
+ diag.authBlocked = true;
148
+ diag.lastAuthFailureAt = now();
149
+ if (info.code !== undefined && info.code !== null) diag.lastDisconnectCode = info.code;
150
+ if (info.reason) diag.lastDisconnectReason = String(info.reason).slice(0, 200);
151
+ if (!authNotified) {
152
+ authNotified = true;
153
+ if (onAuthRejected) { try { onAuthRejected({ error: info.error || null, code: info.code ?? null, reason: info.reason || null }); } catch {} }
154
+ }
155
+ if (authFailures >= maxAuthAttempts) {
156
+ diag.reauthorizationRequired = true;
157
+ diag.nextRetryMs = null;
158
+ _clearRetry();
159
+ setState('auth_blocked');
160
+ log(`[broker] authentication failed ${authFailures} times; retries stopped — reauthorization required (device identity preserved)`);
161
+ if (onAuthBlocked) {
162
+ try { onAuthBlocked({ authFailures, code: diag.lastDisconnectCode, reason: diag.lastDisconnectReason }); } catch {}
163
+ }
164
+ return;
165
+ }
166
+ }
167
+
168
+ attempt += 1;
169
+ diag.reconnectAttempt = attempt;
170
+ diag.authBlocked = info.auth === true;
171
+
172
+ if (maxAttempts > 0 && attempt > maxAttempts) {
173
+ setState('disconnected');
174
+ log(`[broker] reconnect exhausted after ${maxAttempts} attempts; giving up (identity preserved)`);
175
+ if (opts.onExhausted) { try { opts.onExhausted(getState()); } catch {} }
176
+ return;
177
+ }
178
+
179
+ const exp = Math.min(backoff.baseMs * Math.pow(backoff.factor, attempt - 1), backoff.maxMs);
180
+ const jitter = Math.floor(random() * backoff.jitterMs);
181
+ const delay = exp + jitter;
182
+ diag.nextRetryMs = delay;
183
+ setState(info.auth ? 'auth_blocked' : 'reconnecting');
184
+ log(`[broker] reconnect scheduled attempt=${attempt} retry=${Math.round(delay)}ms${info.auth ? ' auth=blocked' : ''}`);
185
+ retryTimer = setTimeoutFn(() => { retryTimer = null; _attemptConnect(); }, delay);
186
+ }
187
+
188
+ async function _attemptConnect() {
189
+ if (stopped) return;
190
+ if (connectInFlight) return; // SINGLE in-flight attempt invariant
191
+ if (ws) return; // already connected
192
+ connectInFlight = true;
193
+ setState(attempt > 0 ? 'reconnecting' : 'connecting');
194
+ log(`[broker] ${attempt > 0 ? 'reconnecting' : 'connecting'} attempt=${attempt}`);
195
+
196
+ let sock;
197
+ try {
198
+ sock = await connect();
199
+ } catch (err) {
200
+ connectInFlight = false;
201
+ if (stopped) return;
202
+ const auth = isAuthErrorMessage(_safeMsg(err));
203
+ if (!auth || authFailures === 0) log(`[broker] connect failed: ${_safeMsg(err)}`);
204
+ _scheduleReconnect({ auth, code: err && err.code ? err.code : null, reason: _safeMsg(err), error: err });
205
+ return;
206
+ }
207
+ connectInFlight = false;
208
+ if (stopped) { try { sock.close(1000, 'stopping'); } catch {} return; }
209
+
210
+ ws = sock;
211
+ attempt = 0;
212
+ authFailures = 0;
213
+ authNotified = false;
214
+ diag.lastConnectedAt = now();
215
+ diag.nextRetryMs = null;
216
+ diag.reconnectAttempt = 0;
217
+ diag.authBlocked = false;
218
+ diag.authFailures = 0;
219
+ diag.reauthorizationRequired = false;
220
+ setState('connected');
221
+ log('[broker] connected');
222
+
223
+ try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
224
+ // An 'error' event immediately preceded by nothing else must not crash the
225
+ // process; the close path handles reconnection.
226
+ try { sock.on('error', () => {}); } catch {}
227
+ _startHeartbeatWatch(sock);
228
+
229
+ try { await onConnected(sock); } catch (e) { log(`[broker] onConnected error: ${_safeMsg(e)}`); }
230
+ }
231
+
232
+ function _handleClose(closedSock, code, reason) {
233
+ if (stopped) return;
234
+ if (ws !== closedSock) return; // stale socket (already replaced) — ignore
235
+ ws = null;
236
+ _stopHeartbeatWatch();
237
+ const reasonStr = reason ? reason.toString() : '';
238
+ diag.lastDisconnectedAt = now();
239
+ diag.lastDisconnectCode = code;
240
+ diag.lastDisconnectReason = reasonStr;
241
+
242
+ if (code === 4003) {
243
+ diag.authBlocked = true;
244
+ if (!authNotified) log('[broker] disconnected code=4003 (authentication/identity)');
245
+ // Permanent class: bounded by maxAuthAttempts, then retries stop. Identity
246
+ // is NEVER regenerated or deleted here.
247
+ _scheduleReconnect({ auth: true, code, reason: reasonStr });
248
+ return;
249
+ }
250
+
251
+ log(`[broker] disconnected code=${code}${reasonStr ? ' reason=' + reasonStr : ''}`);
252
+ try { const r = onDisconnected({ code, reason: reasonStr }); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
253
+ _scheduleReconnect({});
254
+ }
255
+
256
+ function start() {
257
+ stopped = false;
258
+ attempt = 0;
259
+ authFailures = 0;
260
+ authNotified = false;
261
+ diag.authBlocked = false;
262
+ diag.authFailures = 0;
263
+ diag.reauthorizationRequired = false;
264
+ diag.nextRetryMs = null;
265
+ return _attemptConnect();
266
+ }
267
+
268
+ /**
269
+ * Adopt an ALREADY-authenticated socket (the foreground `start` path connects
270
+ * first, including its one-time enrollment flow, then hands the live socket to
271
+ * the supervisor for its reconnect lifecycle). Binding happens through
272
+ * `onConnected` exactly once, so the handler is never double-installed.
273
+ */
274
+ function adopt(sock) {
275
+ if (!sock) return;
276
+ stopped = false;
277
+ connectInFlight = false;
278
+ attempt = 0;
279
+ authFailures = 0;
280
+ authNotified = false;
281
+ ws = sock;
282
+ diag.lastConnectedAt = now();
283
+ diag.nextRetryMs = null;
284
+ diag.reconnectAttempt = 0;
285
+ diag.authBlocked = false;
286
+ diag.authFailures = 0;
287
+ diag.reauthorizationRequired = false;
288
+ setState('connected');
289
+ log('[broker] connected');
290
+ try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
291
+ try { sock.on('error', () => {}); } catch {}
292
+ _startHeartbeatWatch(sock);
293
+ try { const r = onConnected(sock); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
294
+ }
295
+
296
+ function stop() {
297
+ if (stopped) return;
298
+ stopped = true;
299
+ _clearRetry();
300
+ _stopHeartbeatWatch();
301
+ setState('stopping');
302
+ const sock = ws;
303
+ ws = null;
304
+ if (sock) { try { sock.close(1000, 'shutdown'); } catch {} }
305
+ }
306
+
307
+ return {
308
+ start,
309
+ adopt,
310
+ stop,
311
+ getState,
312
+ // Exported for white-box deterministic tests.
313
+ _handleClose,
314
+ _attemptConnect,
315
+ _isAuthError: (e) => isAuthErrorMessage(_safeMsg(e)),
316
+ };
317
+ }
318
+
319
+ module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_AUTH_MAX_ATTEMPTS, DEFAULT_PONG_TIMEOUT_MS };