asyx 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +103 -17
  2. package/SECURITY.md +5 -3
  3. package/package.json +15 -22
  4. package/src/commands/name.js +23 -0
  5. package/src/commands/reject-messages.js +54 -0
  6. package/src/commands/setup.js +98 -102
  7. package/src/commands/tunnel.js +304 -2316
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +24 -6
  10. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
  11. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
  12. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
  13. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
  14. package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
  15. package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
  16. package/vendor/tunnel-core/dist/errors.d.ts +49 -0
  17. package/vendor/tunnel-core/dist/errors.js +53 -0
  18. package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
  19. package/vendor/tunnel-core/dist/flows/http.js +585 -0
  20. package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
  21. package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
  22. package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
  23. package/vendor/tunnel-core/dist/flows/udp.js +376 -0
  24. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
  26. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
  27. package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
  28. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
  29. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
  30. package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
  31. package/vendor/tunnel-core/dist/lib/logger.js +58 -0
  32. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
  33. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
  34. package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
  35. package/vendor/tunnel-core/dist/lifecycle.js +29 -0
  36. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
  37. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
  38. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
  39. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
  40. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
  41. package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
  42. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
  43. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
  44. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
  46. package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
  47. package/vendor/tunnel-core/dist/state/assignment.js +322 -0
  48. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
  49. package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
  50. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
  51. package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
  52. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
  53. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
  54. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
  55. package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
  56. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
  57. package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
  58. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
  59. package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
  60. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
  61. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
  62. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
  63. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
  64. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
  65. package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
  66. package/vendor/tunnel-core/dist/types.d.ts +24 -0
  67. package/vendor/tunnel-core/dist/types.js +2 -0
  68. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
  69. package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
  70. package/vendor/tunnel-core/package.json +34 -0
  71. package/src/control-plane/MqttControlPlaneClient.js +0 -1196
  72. package/src/control-plane/MqttControlPlaneTransport.js +0 -150
  73. package/src/lib/fingerprint.js +0 -115
  74. package/src/lib/jwt-verifier.js +0 -260
  75. package/src/lib/logger.js +0 -62
  76. package/src/mqtt/awaiter-map.js +0 -247
  77. package/src/mqtt/events/handlers.js +0 -300
  78. package/src/mqtt/events/index.js +0 -222
  79. package/src/mqtt/events/schemas.js +0 -58
  80. package/src/mqtt/ingress.js +0 -182
  81. package/src/state/assignment.js +0 -333
  82. package/src/tcp-v1/framing.js +0 -203
  83. package/src/tunnel/http-tunnel.js +0 -1694
  84. package/src/tunnel/tcp-tunnel.js +0 -862
  85. package/src/tunnel/udp-tunnel.js +0 -708
  86. package/src/tunnel/ws-control.js +0 -135
  87. package/src/udp-v1/framing.js +0 -203
@@ -0,0 +1,1088 @@
1
+ /**
2
+ * MqttControlPlaneClient
3
+ *
4
+ * Encapsulates MQTT control-plane connection management, client ID rotation,
5
+ * reconnect logic, and JWT refresh buffering as described in docs/cli-mqtt-refresh_algo.md.
6
+ *
7
+ * This module provides a clean abstraction for CLI MQTT operations, making the
8
+ * logic testable in isolation via dependency injection.
9
+ *
10
+ * @see docs/cli-mqtt-refresh_algo.md
11
+ */
12
+ import mqtt from 'mqtt';
13
+ import { ulid } from 'ulid';
14
+ /**
15
+ * @typedef {'soft' | 'hard' | 'transient'} MqttFaultKind
16
+ */
17
+ /**
18
+ * @typedef {Object} MqttControlPlaneClientOptions
19
+ * @property {string} url - MQTT broker URL (e.g., 'wss://...')
20
+ * @property {string} baseClientId - Base client ID (e.g., 'cli_F285616B53CE')
21
+ * @property {Object} [mqttOptions] - Additional mqtt.js options (cert, key, ca, etc.)
22
+ * @property {(client: any) => void | Promise<void>} [onConnected] - Called after successful connect
23
+ * @property {(reason: string) => void} [onOffline] - Called when connection goes offline
24
+ * @property {(reason: string, err?: unknown) => void} [onFatalError] - Called when we give up due to JWT expiry or unrecoverable error
25
+ * @property {() => Promise<number>} onRefreshLease - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
26
+ * @property {number} [refreshEarlySeconds] - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
27
+ * @property {number} [maxReconnectDelayMs] - Max reconnect delay in ms (default 5000)
28
+ * @property {'unique' | 'legacy'} [mode] - Mode: 'unique' (default) or 'legacy'
29
+ * @property {Object} [logger] - Logger for structured logging
30
+ * @property {any} [mqttLib] - Optional mqtt library for dependency injection (defaults to real mqtt)
31
+ * @property {any} [ulidLib] - Optional ulid library for dependency injection (defaults to real ulid)
32
+ */
33
+ export class MqttControlPlaneClient {
34
+ /**
35
+ * @param {MqttControlPlaneClientOptions} opts
36
+ */
37
+ constructor(opts) {
38
+ this.url = opts.url;
39
+ this.baseClientId = opts.baseClientId;
40
+ this.mqttOptions = opts.mqttOptions ?? {};
41
+ this.onConnected = opts.onConnected;
42
+ this.onOffline = opts.onOffline;
43
+ this.onFatalError = opts.onFatalError;
44
+ this.onRefreshLease = opts.onRefreshLease;
45
+ this.refreshEarlySeconds = opts.refreshEarlySeconds ?? 675; // 0.75 * 900s (15 min TTL)
46
+ this.maxReconnectDelayMs = opts.maxReconnectDelayMs ?? 5000;
47
+ this.mode = opts.mode || (process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique');
48
+ this.logger = opts.logger;
49
+ // Dependency injection: allow tests to inject mock mqtt library
50
+ this.mqtt = opts.mqttLib || mqtt;
51
+ // Dependency injection: allow tests to inject mock ulid library
52
+ this.ulidLib = opts.ulidLib;
53
+ // Initialize client ID based on mode
54
+ this.currentClientId = this.makeClientId();
55
+ // State tracking
56
+ this.client = null;
57
+ this.forceClosing = null;
58
+ this.shuttingDown = false;
59
+ this.mqttOnline = false;
60
+ this.hardErrorCount = 0;
61
+ this.transientErrorCount = 0;
62
+ this.reconnectTimer = null;
63
+ this.connectStartTime = null;
64
+ this.reconnectAttempts = 0; // Track total reconnect attempts
65
+ this.maxReconnectAttempts = parseInt(process.env.ASYX_MQTT_MAX_RECONNECT_ATTEMPTS || '20', 10); // Default 20 attempts (was 100, but too many for policy issues)
66
+ // Refresh state
67
+ this.refreshTimer = null;
68
+ this.refreshPending = false;
69
+ this.refreshDeadlineMs = null;
70
+ this.currentLeaseId = null; // Current lease ID for correlation with jwt_expired_before_refresh
71
+ this.rearmTimeout = null; // QPA-CLI-08: Timeout for refresh re-arm after reconnect
72
+ this.flushPendingRefreshTimer = null; // Timer for flushing pending refresh after reconnect
73
+ // Watchdog state
74
+ this.watchdogTimer = null;
75
+ this.WATCHDOG_TIMEOUT_MS = 60000; // 60 seconds
76
+ // Pending message handler (for Transport interface)
77
+ this._pendingMessageHandler = null;
78
+ }
79
+ // Public API --------------------------------------------------------------
80
+ /**
81
+ * Connect to MQTT broker (initial connection).
82
+ * Returns a promise that resolves when connected or rejects on fatal error.
83
+ * @returns {Promise<void>}
84
+ */
85
+ async connect() {
86
+ this.shuttingDown = false;
87
+ return this.connectWithNewClient(/* initial */ true);
88
+ }
89
+ /**
90
+ * Disconnect and clean up all timers.
91
+ * @param {Object} [opts] - Options
92
+ * @param {boolean} [opts.preserveState] - If true, don't set shuttingDown (for forceReconnect)
93
+ * @returns {Promise<void>}
94
+ */
95
+ async disconnect(opts = {}) {
96
+ if (!opts.preserveState) {
97
+ this.shuttingDown = true;
98
+ }
99
+ this.clearReconnectTimer();
100
+ this.clearRefreshTimer();
101
+ this.clearWatchdog();
102
+ this.clearRearmTimeout(); // QPA-CLI-08: Clear rearm timeout on disconnect
103
+ this.clearFlushPendingRefreshTimer(); // Clear flush pending refresh timer
104
+ if (!opts.preserveState) {
105
+ this.refreshPending = false;
106
+ this.refreshDeadlineMs = null;
107
+ }
108
+ this.mqttOnline = false;
109
+ if (this.client) {
110
+ const c = this.client;
111
+ this.client = null;
112
+ return new Promise((resolve) => {
113
+ try {
114
+ c.end(true, {}, () => resolve());
115
+ }
116
+ catch {
117
+ resolve();
118
+ }
119
+ });
120
+ }
121
+ }
122
+ /**
123
+ * Force a manual reconnect (tear down and reconnect).
124
+ * Used when we need a fresh MQTT session (e.g., after ack timeout).
125
+ * @param {string} reason - Reason for reconnect
126
+ * @returns {Promise<void>}
127
+ */
128
+ async forceReconnect(reason = 'manual') {
129
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
130
+ this.logger?.debug('mqtt.control_plane.manual_reconnect', { reason });
131
+ await this.disconnect({ preserveState: true });
132
+ return this.connect();
133
+ }
134
+ /**
135
+ * Publish a message.
136
+ * @param {string} topic
137
+ * @param {string | Buffer} payload
138
+ * @param {Object} [opts]
139
+ * @returns {Promise<void>}
140
+ */
141
+ async publish(topic, payload, opts = {}) {
142
+ return new Promise((resolve, reject) => {
143
+ if (!this.client || !this.mqttOnline) {
144
+ return reject(new Error("MQTT offline"));
145
+ }
146
+ this.client.publish(topic, payload, opts, (err) => {
147
+ if (err)
148
+ reject(err);
149
+ else
150
+ resolve();
151
+ });
152
+ });
153
+ }
154
+ /**
155
+ * Subscribe to a topic.
156
+ * @param {string} topic
157
+ * @param {number} qos
158
+ * @returns {Promise<void>}
159
+ */
160
+ async subscribe(topic, qos = 0) {
161
+ return new Promise((resolve, reject) => {
162
+ if (!this.client || !this.mqttOnline) {
163
+ return reject(new Error("MQTT offline"));
164
+ }
165
+ this.client.subscribe(topic, { qos }, (err) => {
166
+ if (err)
167
+ reject(err);
168
+ else
169
+ resolve();
170
+ });
171
+ });
172
+ }
173
+ /**
174
+ * Schedule a JWT refresh based on an expiration timestamp (ms since epoch).
175
+ * @param {number} expMs - Expiration timestamp in milliseconds since epoch
176
+ * @param {string} [leaseId] - Optional lease ID for correlation
177
+ */
178
+ scheduleRefresh(expMs, leaseId = null) {
179
+ this.refreshDeadlineMs = expMs;
180
+ if (leaseId) {
181
+ this.currentLeaseId = leaseId;
182
+ }
183
+ this.clearRefreshTimer();
184
+ const now = Date.now();
185
+ const triggerAt = expMs - this.refreshEarlySeconds * 1000;
186
+ const delayMs = Math.max(0, triggerAt - now);
187
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
188
+ this.logger?.debug('mqtt.control_plane.refresh.scheduled', {
189
+ expEpochMs: expMs,
190
+ leaseId: this.currentLeaseId,
191
+ leadMs: this.refreshEarlySeconds * 1000,
192
+ refreshAtEpochMs: triggerAt,
193
+ skewMs: now - expMs,
194
+ delayMs
195
+ });
196
+ this.refreshTimer = setTimeout(() => {
197
+ this.refreshTimer = null;
198
+ this.logger?.debug('mqtt.control_plane.refresh.timer_fired', {
199
+ expEpochMs: expMs,
200
+ leaseId: this.currentLeaseId,
201
+ now: Date.now()
202
+ });
203
+ void this.refreshLeaseToken("scheduled");
204
+ }, delayMs);
205
+ // Don't keep process alive for refresh timer (can be very long delays)
206
+ // Always use unref() since we manage these timers explicitly
207
+ if (this.refreshTimer) {
208
+ this.refreshTimer.unref();
209
+ }
210
+ this.logger?.debug('mqtt.control_plane.refresh.timer_created', {
211
+ expEpochMs: expMs,
212
+ leaseId: this.currentLeaseId,
213
+ delayMs,
214
+ timerId: this.refreshTimer ? 'set' : 'null'
215
+ });
216
+ }
217
+ /**
218
+ * Check if MQTT is online.
219
+ * @returns {boolean}
220
+ */
221
+ isOnline() {
222
+ return this.mqttOnline && this.client !== null;
223
+ }
224
+ /**
225
+ * Get current client ID.
226
+ * @returns {string}
227
+ */
228
+ getClientId() {
229
+ return this.currentClientId;
230
+ }
231
+ /**
232
+ * Set message handler (for Transport interface).
233
+ * Converts mqtt.js format (topic, payload, packet) to MqttCore format {topic, payload: Uint8Array}
234
+ * @param {(message: {topic: string, payload: Uint8Array}) => void} handler
235
+ */
236
+ setMessageHandler(handler) {
237
+ // Wrap handler to convert mqtt.js format to MqttCore format
238
+ const wrappedHandler = (topic, payload, packet) => {
239
+ // Convert payload to Uint8Array as expected by MqttCore
240
+ const payloadBytes = payload instanceof Buffer
241
+ ? new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength)
242
+ : payload instanceof Uint8Array
243
+ ? payload
244
+ : typeof payload === 'string'
245
+ ? new TextEncoder().encode(payload)
246
+ : new Uint8Array(Buffer.from(payload));
247
+ handler({ topic, payload: payloadBytes });
248
+ };
249
+ if (this.client && this._pendingMessageHandler) {
250
+ this.client.removeListener('message', this._pendingMessageHandler);
251
+ }
252
+ this._pendingMessageHandler = wrappedHandler;
253
+ if (this.client && this.mqttOnline) {
254
+ this.client.on('message', wrappedHandler);
255
+ }
256
+ }
257
+ // Internal helpers --------------------------------------------------------
258
+ /**
259
+ * Generate client ID based on mode.
260
+ * @returns {string}
261
+ */
262
+ makeClientId() {
263
+ if (this.mode === 'legacy') {
264
+ return this.baseClientId;
265
+ }
266
+ // Unique mode: baseClientId + ULID
267
+ const ulidValue = this.ulidLib ? this.ulidLib() : ulid();
268
+ return `${this.baseClientId}_${ulidValue}`;
269
+ }
270
+ /**
271
+ * Connect with a new client (initial or after fault).
272
+ * @param {boolean} initial - true for first connect, false for reconnect
273
+ * @returns {Promise<void>}
274
+ */
275
+ connectWithNewClient(initial = false) {
276
+ if (this.shuttingDown)
277
+ return Promise.resolve();
278
+ // Avoid double-connect attempts
279
+ if (this.client) {
280
+ // already connected or connecting
281
+ return Promise.resolve();
282
+ }
283
+ // Rotate client ID on reconnect (hard faults)
284
+ if (!initial && this.mode === 'unique') {
285
+ this.currentClientId = this.makeClientId();
286
+ }
287
+ else if (initial) {
288
+ this.currentClientId = this.makeClientId();
289
+ }
290
+ // Build options: match AwsIotTransport exactly
291
+ // For mqtts:// URLs, protocol must be set in options; mqtt.js doesn't auto-detect it
292
+ const options = {
293
+ clientId: this.currentClientId,
294
+ protocolVersion: 4, // MQTT 3.1.1 (required for AWS IoT)
295
+ clean: true,
296
+ keepalive: this.mqttOptions.keepalive ?? 25,
297
+ reconnectPeriod: 0, // we manage reconnects
298
+ cert: this.mqttOptions.cert,
299
+ key: this.mqttOptions.key,
300
+ ca: this.mqttOptions.ca,
301
+ rejectUnauthorized: true,
302
+ connectTimeout: this.mqttOptions.connectTimeout ?? 8000,
303
+ resubscribe: false,
304
+ // Protocol and port for TLS (mqtts) - required for client certificate authentication
305
+ protocol: this.mqttOptions.protocol || 'mqtts',
306
+ port: this.mqttOptions.port || 443,
307
+ // ALPN for port 443 (AWS IoT)
308
+ ALPNProtocols: this.mqttOptions.ALPNProtocols || ['x-amzn-mqtt-ca'],
309
+ };
310
+ // Log connection attempt with TLS info (but not the actual cert/key data)
311
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
312
+ this.logger?.debug('mqtt.control_plane.dial', {
313
+ clientId: this.currentClientId,
314
+ mode: this.mode,
315
+ initial,
316
+ hasCert: !!options.cert,
317
+ hasKey: !!options.key,
318
+ hasCa: !!options.ca,
319
+ rejectUnauthorized: options.rejectUnauthorized,
320
+ alpnProtocols: options.ALPNProtocols
321
+ });
322
+ const client = this.mqtt.connect(this.url, options);
323
+ this.client = client;
324
+ this.mqttOnline = false;
325
+ this.connectStartTime = Date.now();
326
+ this.startWatchdog();
327
+ return new Promise((resolve, reject) => {
328
+ let resolvedOrRejected = false;
329
+ let hasConnected = false; // Track if connect event has fired
330
+ let lastError = null; // Track last error for better diagnostics
331
+ const onConnect = async () => {
332
+ hasConnected = true;
333
+ this.clearWatchdog();
334
+ this.mqttOnline = true;
335
+ this.hardErrorCount = 0;
336
+ this.transientErrorCount = 0;
337
+ this.reconnectAttempts = 0; // Reset on successful connect
338
+ this.connectStartTime = null;
339
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
340
+ this.logger?.debug('mqtt.control_plane.connected', {
341
+ clientId: this.currentClientId
342
+ });
343
+ // Wire up message handler if set
344
+ if (this._pendingMessageHandler) {
345
+ client.on('message', this._pendingMessageHandler);
346
+ }
347
+ try {
348
+ if (this.onConnected) {
349
+ await this.onConnected(client);
350
+ }
351
+ }
352
+ catch (e) {
353
+ this.handleFatal("onConnected_failed", e);
354
+ }
355
+ if (!resolvedOrRejected && initial) {
356
+ resolvedOrRejected = true;
357
+ resolve();
358
+ }
359
+ // If we had a pending refresh because we were offline, try now.
360
+ if (this.refreshPending) {
361
+ // Grace period: if we're within 30s of expiry, attempt one refresh before exiting
362
+ const now = Date.now();
363
+ const gracePeriodMs = 30000; // 30 seconds
364
+ const timeUntilExpiry = this.refreshDeadlineMs ? (this.refreshDeadlineMs - now) : Infinity;
365
+ if (timeUntilExpiry < gracePeriodMs && timeUntilExpiry > 0) {
366
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
367
+ this.logger?.debug('mqtt.control_plane.refresh.grace_period', {
368
+ timeUntilExpiry,
369
+ gracePeriodMs
370
+ });
371
+ }
372
+ this.clearFlushPendingRefreshTimer();
373
+ this.flushPendingRefreshTimer = setTimeout(() => {
374
+ this.flushPendingRefreshTimer = null;
375
+ void this.refreshLeaseToken("pending_after_reconnect");
376
+ }, 500);
377
+ this.flushPendingRefreshTimer?.unref(); // Don't keep process alive
378
+ }
379
+ // QPA-CLI-08: Schedule refresh re-arm check after reconnect
380
+ // Use a short delay to avoid racing with existing resend logic
381
+ this.clearRearmTimeout();
382
+ this.logger?.debug('jwt.refresh.rearm.scheduled', {
383
+ delayMs: 1000,
384
+ refreshDeadlineMs: this.refreshDeadlineMs,
385
+ leaseId: this.currentLeaseId,
386
+ refreshPending: this.refreshPending,
387
+ hasRefreshTimer: this.refreshTimer !== null
388
+ });
389
+ this.rearmTimeout = setTimeout(() => {
390
+ this.rearmTimeout = null;
391
+ this.ensureRefreshScheduled();
392
+ }, 1000);
393
+ this.rearmTimeout?.unref(); // Don't keep process alive for this timer
394
+ };
395
+ const onError = (err) => {
396
+ // A pre-TLS failure can be emitted twice. The first emit force-closes
397
+ // this client; ignore that client afterwards so the second emit cannot
398
+ // throw or schedule another reconnect.
399
+ if (this.forceClosing === client || this.client !== client)
400
+ return;
401
+ lastError = err; // Store error for diagnostics
402
+ // Try to extract more details from the client's internal state
403
+ let socketError = null;
404
+ let streamError = null;
405
+ try {
406
+ // mqtt.js client may have a stream or socket with error info
407
+ if (client.stream) {
408
+ streamError = client.stream._readableState?.error || client.stream._writableState?.error;
409
+ }
410
+ if (client.socket) {
411
+ socketError = client.socket.error || client.socket._socket?.error;
412
+ }
413
+ }
414
+ catch (e) {
415
+ // Ignore errors accessing internal state
416
+ }
417
+ const fault = this.classifyMqttFault("error", err, undefined, !hasConnected);
418
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
419
+ this.logger?.debug('mqtt.control_plane.error', {
420
+ fault,
421
+ error: err?.message || String(err),
422
+ code: err?.code,
423
+ name: err?.name,
424
+ errno: err?.errno,
425
+ syscall: err?.syscall,
426
+ beforeConnect: !hasConnected,
427
+ clientId: this.currentClientId,
428
+ baseClientId: this.baseClientId,
429
+ socketError: socketError ? { message: socketError.message, code: socketError.code } : undefined,
430
+ streamError: streamError ? { message: streamError.message, code: streamError.code } : undefined
431
+ });
432
+ this.handleFault(fault, err || socketError || streamError);
433
+ if (!resolvedOrRejected && !initial) {
434
+ resolvedOrRejected = true;
435
+ reject(err);
436
+ }
437
+ };
438
+ const onOffline = () => {
439
+ // offline event may fire before close, capture any available error info
440
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
441
+ this.logger?.debug('mqtt.control_plane.offline', {
442
+ beforeConnect: !hasConnected,
443
+ clientId: this.currentClientId,
444
+ baseClientId: this.baseClientId,
445
+ lastError: lastError ? {
446
+ code: lastError.code,
447
+ message: lastError.message,
448
+ name: lastError.name
449
+ } : undefined
450
+ });
451
+ // offline is usually a soft fault, but if it happens before connect, treat as hard
452
+ if (!hasConnected) {
453
+ const fault = this.classifyMqttFault("error", lastError || undefined, undefined, true);
454
+ this.handleFault(fault, lastError || new Error("MQTT went offline before connect"));
455
+ }
456
+ };
457
+ const onClose = (...args) => {
458
+ // mqtt.js close event may pass: () or (hadError) or (code, reason)
459
+ // Capture all arguments for diagnostics
460
+ const closeCode = args[0] !== undefined && typeof args[0] === 'number' ? args[0] : undefined;
461
+ const closeReason = args[1] !== undefined ? String(args[1]) : undefined;
462
+ const hadError = args[0] === true || (closeCode === undefined && args[0] === true);
463
+ // If close fires before connect, it's likely a hard fault (auth/policy issue)
464
+ const isBeforeConnect = !hasConnected;
465
+ // Try to extract more diagnostic info from client state
466
+ /** @type {Record<string, any>} */
467
+ let clientState = {};
468
+ try {
469
+ if (client) {
470
+ clientState = {
471
+ connected: client.connected,
472
+ disconnecting: client.disconnecting,
473
+ reconnecting: client.reconnecting,
474
+ options: {
475
+ clientId: client.options?.clientId,
476
+ protocol: client.options?.protocol,
477
+ protocolVersion: client.options?.protocolVersion
478
+ }
479
+ };
480
+ // Try to get socket state if available
481
+ if (client.stream) {
482
+ clientState.streamState = {
483
+ readable: client.stream.readable,
484
+ writable: client.stream.writable,
485
+ destroyed: client.stream.destroyed
486
+ };
487
+ }
488
+ }
489
+ }
490
+ catch (e) {
491
+ // Ignore errors accessing internal state
492
+ }
493
+ const fault = this.classifyMqttFault("close", lastError || undefined, closeCode, isBeforeConnect);
494
+ // Log close code/reason more accurately
495
+ const codeStr = closeCode !== undefined && closeCode !== null
496
+ ? String(closeCode)
497
+ : (lastError?.code ? String(lastError.code) : (hadError ? 'error' : 'unknown'));
498
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
499
+ this.logger?.debug('mqtt.control_plane.close', {
500
+ fault,
501
+ closeCode: codeStr,
502
+ closeReason: closeReason || undefined,
503
+ hadError: hadError || undefined,
504
+ beforeConnect: isBeforeConnect,
505
+ lastError: lastError ? {
506
+ code: lastError.code,
507
+ message: lastError.message,
508
+ name: lastError.name,
509
+ stack: lastError.stack
510
+ } : undefined,
511
+ clientId: this.currentClientId,
512
+ baseClientId: this.baseClientId,
513
+ clientState: Object.keys(clientState).length > 0 ? clientState : undefined,
514
+ // Diagnostic: if this keeps happening, it's likely a policy/auth issue
515
+ diagnostic: isBeforeConnect && !lastError ?
516
+ 'Connection closed before MQTT handshake. Likely causes: AWS IoT policy mismatch, certificate auth failure, or TLS handshake rejection. Check AWS IoT policy allows clientId pattern: ' + this.baseClientId + '*' : undefined
517
+ });
518
+ // Don't reject immediately - let reconnect loop handle retries
519
+ // The reconnect loop will retry with backoff, and only call handleFatal after max attempts
520
+ this.handleFault(fault, lastError || (hadError ? new Error('MQTT connection had error') : undefined));
521
+ // Don't reject the promise here - let the reconnect loop handle it
522
+ // If we've exhausted retries, handleFault will eventually call handleFatal
523
+ };
524
+ const onEnd = () => {
525
+ // If end fires before connect, it's likely a hard fault
526
+ const isBeforeConnect = !hasConnected;
527
+ const fault = this.classifyMqttFault("close", lastError || undefined, undefined, isBeforeConnect);
528
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
529
+ this.logger?.debug('mqtt.control_plane.end', {
530
+ fault,
531
+ beforeConnect: isBeforeConnect,
532
+ lastError: lastError ? {
533
+ code: lastError.code,
534
+ message: lastError.message,
535
+ name: lastError.name
536
+ } : undefined,
537
+ clientId: this.currentClientId,
538
+ baseClientId: this.baseClientId
539
+ });
540
+ // Don't reject immediately - let reconnect loop handle it
541
+ this.handleFault(fault, lastError);
542
+ };
543
+ client.on("connect", onConnect);
544
+ client.on("error", onError);
545
+ client.on("offline", onOffline);
546
+ client.on("close", onClose);
547
+ client.on("end", onEnd);
548
+ // Also try to capture errors from the underlying socket/stream if available
549
+ try {
550
+ if (client.stream) {
551
+ client.stream.on('error', (streamErr) => {
552
+ if (!lastError) {
553
+ lastError = streamErr;
554
+ }
555
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
556
+ this.logger?.debug('mqtt.control_plane.stream.error', {
557
+ error: streamErr?.message || String(streamErr),
558
+ code: streamErr?.code,
559
+ errno: streamErr?.errno,
560
+ syscall: streamErr?.syscall,
561
+ beforeConnect: !hasConnected,
562
+ clientId: this.currentClientId
563
+ });
564
+ });
565
+ // Also listen for secureConnect event to see if TLS handshake succeeds
566
+ if (client.stream.once) {
567
+ client.stream.once('secureConnect', () => {
568
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
569
+ this.logger?.debug('mqtt.control_plane.tls.secure_connect', {
570
+ clientId: this.currentClientId,
571
+ authorized: client.stream?.authorized,
572
+ authorizationError: client.stream?.authorizationError?.message
573
+ });
574
+ });
575
+ }
576
+ }
577
+ if (client.socket) {
578
+ client.socket.on('error', (socketErr) => {
579
+ if (!lastError) {
580
+ lastError = socketErr;
581
+ }
582
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
583
+ this.logger?.debug('mqtt.control_plane.socket.error', {
584
+ error: socketErr?.message || String(socketErr),
585
+ code: socketErr?.code,
586
+ errno: socketErr?.errno,
587
+ syscall: socketErr?.syscall,
588
+ beforeConnect: !hasConnected,
589
+ clientId: this.currentClientId
590
+ });
591
+ });
592
+ // For TLS sockets, check authorization
593
+ if (client.socket.authorized !== undefined) {
594
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
595
+ this.logger?.debug('mqtt.control_plane.tls.authorization', {
596
+ clientId: this.currentClientId,
597
+ authorized: client.socket.authorized,
598
+ authorizationError: client.socket.authorizationError?.message
599
+ });
600
+ }
601
+ }
602
+ }
603
+ catch (e) {
604
+ // Ignore errors accessing internal state
605
+ this.logger?.debug('mqtt.control_plane.internal_state_access_error', {
606
+ error: e?.message,
607
+ clientId: this.currentClientId
608
+ });
609
+ }
610
+ });
611
+ }
612
+ /**
613
+ * Classify MQTT fault as hard or soft.
614
+ * @param {string} event - Event type: 'error', 'close', 'end'
615
+ * @param {any} [err] - Error object
616
+ * @param {number} [closeCode] - MQTT close code
617
+ * @param {boolean} [beforeConnect] - true if fault occurred before connect event
618
+ * @returns {MqttFaultKind}
619
+ */
620
+ classifyMqttFault(event, err, closeCode, beforeConnect = false) {
621
+ // Fix code_NaN: log real codes, fall back to 'unknown'
622
+ const code = (err && (err.code)) || undefined;
623
+ const name = (err && (err.name)) || "";
624
+ const msg = (err && (err.message)) || "";
625
+ // Resolver failures recover, including before the MQTT handshake.
626
+ // The 20-attempt exit is for auth and policy failures that will not.
627
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
628
+ return "transient";
629
+ }
630
+ // If close/end fires before connect, it's likely a hard fault (auth/policy issue)
631
+ if (beforeConnect) {
632
+ return "hard";
633
+ }
634
+ // Clean shutdown (soft)
635
+ if (event === "close" && closeCode === 1000) {
636
+ return "soft";
637
+ }
638
+ // Hard network / broker faults
639
+ if (code === "ECONNRESET" ||
640
+ code === "ETIMEDOUT" ||
641
+ code === "EPIPE") {
642
+ return "hard";
643
+ }
644
+ // TLS / auth / protocol problems are also hard
645
+ if (name.includes("TLS") ||
646
+ msg.includes("certificate") ||
647
+ msg.includes("TLS") ||
648
+ String(code || "").includes("CERT") ||
649
+ msg.includes("authentication") ||
650
+ msg.includes("authorization") ||
651
+ msg.includes("policy")) {
652
+ return "hard";
653
+ }
654
+ // MQTT protocol errors (close codes 1-5) are hard faults
655
+ if (event === "close" && closeCode !== undefined && closeCode !== null) {
656
+ // MQTT 3.1.1 close codes: 1-5 are protocol errors (hard)
657
+ if (closeCode >= 1 && closeCode <= 5) {
658
+ return "hard";
659
+ }
660
+ // Close code 0 or undefined might be network-level (could be hard or soft)
661
+ // But if we have an error, prefer that classification
662
+ }
663
+ // Everything else: treat as soft by default
664
+ return "soft";
665
+ }
666
+ /**
667
+ * Handle a fault (soft or hard).
668
+ * Hard faults trigger clientId rotation and immediate reconnect.
669
+ * @param {MqttFaultKind} kind
670
+ * @param {any} [err]
671
+ */
672
+ handleFault(kind, err) {
673
+ if (this.shuttingDown)
674
+ return;
675
+ this.mqttOnline = false;
676
+ this.clearWatchdog();
677
+ const reason = err?.message || err?.code || kind;
678
+ this.onOffline?.(reason);
679
+ if (kind === "transient") {
680
+ this.transientErrorCount++;
681
+ this.logger?.debug('mqtt.control_plane.fault.transient', {
682
+ transientErrorCount: this.transientErrorCount,
683
+ reconnectAttempts: this.reconnectAttempts,
684
+ reason,
685
+ clientId: this.currentClientId,
686
+ baseClientId: this.baseClientId
687
+ });
688
+ this.forceCloseClient();
689
+ this.scheduleReconnect(/* immediate */ false, { transient: true });
690
+ return;
691
+ }
692
+ if (kind === "hard") {
693
+ this.hardErrorCount++;
694
+ this.reconnectAttempts++;
695
+ // Check if we've exhausted retries
696
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
697
+ const errorDetails = {
698
+ reason: 'max_reconnect_attempts_exceeded',
699
+ attempts: this.reconnectAttempts,
700
+ hardErrorCount: this.hardErrorCount,
701
+ lastError: err ? {
702
+ code: err.code,
703
+ message: err.message,
704
+ name: err.name
705
+ } : undefined,
706
+ clientId: this.currentClientId,
707
+ baseClientId: this.baseClientId,
708
+ policyInfo: `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`
709
+ };
710
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
711
+ this.handleFatal('max_reconnect_attempts', new Error(`MQTT connection failed after ${this.reconnectAttempts} attempts. ` +
712
+ `Last error: ${err?.message || err?.code || 'unknown'}. ` +
713
+ `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`));
714
+ return;
715
+ }
716
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
717
+ this.logger?.debug('mqtt.control_plane.fault.hard', {
718
+ hardErrorCount: this.hardErrorCount,
719
+ reconnectAttempts: this.reconnectAttempts,
720
+ maxAttempts: this.maxReconnectAttempts,
721
+ reason,
722
+ clientId: this.currentClientId,
723
+ baseClientId: this.baseClientId
724
+ });
725
+ this.forceCloseClient();
726
+ this.scheduleReconnect(/* immediate */ true);
727
+ }
728
+ else {
729
+ this.reconnectAttempts++;
730
+ // Check if we've exhausted retries
731
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
732
+ const errorDetails = {
733
+ reason: 'max_reconnect_attempts_exceeded',
734
+ attempts: this.reconnectAttempts,
735
+ lastError: err ? {
736
+ code: err.code,
737
+ message: err.message,
738
+ name: err.name
739
+ } : undefined,
740
+ clientId: this.currentClientId,
741
+ baseClientId: this.baseClientId
742
+ };
743
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
744
+ this.handleFatal('max_reconnect_attempts', new Error(`MQTT connection failed after ${this.reconnectAttempts} attempts. ` +
745
+ `Last error: ${err?.message || err?.code || 'unknown'}`));
746
+ return;
747
+ }
748
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
749
+ this.logger?.debug('mqtt.control_plane.fault.soft', {
750
+ reconnectAttempts: this.reconnectAttempts,
751
+ maxAttempts: this.maxReconnectAttempts,
752
+ reason,
753
+ clientId: this.currentClientId
754
+ });
755
+ this.forceCloseClient();
756
+ this.scheduleReconnect(/* immediate */ false);
757
+ }
758
+ }
759
+ /**
760
+ * Force close the current client.
761
+ */
762
+ forceCloseClient() {
763
+ if (!this.client)
764
+ return;
765
+ const client = this.client;
766
+ this.forceClosing = client;
767
+ try {
768
+ client.removeAllListeners();
769
+ client.on('error', () => { });
770
+ client.end(true);
771
+ }
772
+ catch {
773
+ // ignore
774
+ }
775
+ this.client = null;
776
+ this.forceClosing = null;
777
+ }
778
+ /**
779
+ * Schedule reconnect with jittered backoff.
780
+ * @param {boolean} immediate - true for hard faults (ECONNRESET, etc.), false for soft
781
+ * @param {{ transient?: boolean }} [options] - transient resolver failures use a growing delay
782
+ */
783
+ scheduleReconnect(immediate, options = {}) {
784
+ if (this.shuttingDown)
785
+ return;
786
+ if (this.reconnectTimer)
787
+ return; // already scheduled
788
+ const transient = options.transient === true;
789
+ let delay;
790
+ if (transient) {
791
+ const expFactor = Math.min(Math.max(this.transientErrorCount - 1, 0), 4);
792
+ const delayNoJitter = 1000 * Math.pow(2, expFactor);
793
+ const jitter = Math.random() * 200; // 0-200ms jitter
794
+ delay = Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
795
+ }
796
+ else {
797
+ const base = immediate ? 0 : 200;
798
+ const expFactor = Math.min(this.hardErrorCount, 5);
799
+ const delayNoJitter = this.hardErrorCount === 0 ? base : base * Math.pow(2, expFactor);
800
+ const jitter = Math.random() * 200; // 0-200ms jitter
801
+ delay =
802
+ this.hardErrorCount === 0
803
+ ? base
804
+ : Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
805
+ }
806
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
807
+ this.logger?.debug('mqtt.control_plane.reconnect.scheduled', {
808
+ immediate: transient ? false : immediate,
809
+ delay,
810
+ hardErrorCount: this.hardErrorCount,
811
+ transientErrorCount: this.transientErrorCount,
812
+ attempt: this.hardErrorCount + 1
813
+ });
814
+ this.reconnectTimer = setTimeout(() => {
815
+ this.reconnectTimer = null;
816
+ // Swallow reconnect promise rejections (non-initial reconnects are fire-and-forget)
817
+ void this.connectWithNewClient().catch((err) => {
818
+ this.logger?.debug('mqtt.control_plane.reconnect.attempt_failed', {
819
+ error: err?.message || String(err),
820
+ code: err?.code
821
+ });
822
+ });
823
+ }, delay);
824
+ // Don't keep process alive for reconnect timer
825
+ if (this.reconnectTimer) {
826
+ this.reconnectTimer.unref();
827
+ }
828
+ }
829
+ /**
830
+ * Start watchdog timer to detect stuck connections.
831
+ */
832
+ startWatchdog() {
833
+ this.clearWatchdog();
834
+ this.watchdogTimer = setTimeout(() => {
835
+ if (this.connectStartTime && Date.now() - this.connectStartTime > this.WATCHDOG_TIMEOUT_MS) {
836
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
837
+ this.logger?.debug('mqtt.control_plane.watchdog', {
838
+ elapsed: Date.now() - this.connectStartTime,
839
+ clientId: this.currentClientId
840
+ });
841
+ this.handleFault("hard", new Error("Watchdog timeout: connection stuck in CONNECTING"));
842
+ }
843
+ }, this.WATCHDOG_TIMEOUT_MS);
844
+ // Don't keep process alive for watchdog timer (long timeout)
845
+ if (this.watchdogTimer) {
846
+ this.watchdogTimer.unref();
847
+ }
848
+ }
849
+ /**
850
+ * Clear watchdog timer.
851
+ */
852
+ clearWatchdog() {
853
+ if (this.watchdogTimer) {
854
+ clearTimeout(this.watchdogTimer);
855
+ this.watchdogTimer = null;
856
+ }
857
+ }
858
+ /**
859
+ * Clear reconnect timer.
860
+ */
861
+ clearReconnectTimer() {
862
+ if (this.reconnectTimer) {
863
+ clearTimeout(this.reconnectTimer);
864
+ this.reconnectTimer = null;
865
+ }
866
+ }
867
+ /**
868
+ * Clear refresh timer.
869
+ */
870
+ clearRefreshTimer() {
871
+ if (this.refreshTimer) {
872
+ this.logger?.debug('mqtt.control_plane.refresh.timer_cleared', {
873
+ refreshDeadlineMs: this.refreshDeadlineMs,
874
+ leaseId: this.currentLeaseId
875
+ });
876
+ clearTimeout(this.refreshTimer);
877
+ this.refreshTimer = null;
878
+ }
879
+ }
880
+ /**
881
+ * Clear rearm timeout (QPA-CLI-08).
882
+ */
883
+ clearRearmTimeout() {
884
+ if (this.rearmTimeout) {
885
+ clearTimeout(this.rearmTimeout);
886
+ this.rearmTimeout = null;
887
+ }
888
+ }
889
+ /**
890
+ * Clear flush pending refresh timer.
891
+ */
892
+ clearFlushPendingRefreshTimer() {
893
+ if (this.flushPendingRefreshTimer) {
894
+ clearTimeout(this.flushPendingRefreshTimer);
895
+ this.flushPendingRefreshTimer = null;
896
+ }
897
+ }
898
+ /**
899
+ * Attempt to refresh the lease token.
900
+ * @param {string} reason - Reason for refresh (e.g., 'scheduled', 'pending_after_reconnect')
901
+ */
902
+ async refreshLeaseToken(reason) {
903
+ if (this.shuttingDown)
904
+ return;
905
+ // If we already missed the deadline, exit.
906
+ if (this.refreshDeadlineMs && Date.now() > this.refreshDeadlineMs) {
907
+ this.handleFatal("jwt_expired_before_refresh");
908
+ return;
909
+ }
910
+ if (!this.client || !this.mqttOnline) {
911
+ // offline, mark pending
912
+ this.refreshPending = true;
913
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
914
+ this.logger?.debug('mqtt.control_plane.refresh.pending', {
915
+ reason,
916
+ pending: true,
917
+ refreshDeadlineMs: this.refreshDeadlineMs,
918
+ leaseId: this.currentLeaseId
919
+ });
920
+ return;
921
+ }
922
+ try {
923
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
924
+ this.logger?.debug('mqtt.control_plane.refresh.attempting', {
925
+ reason,
926
+ refreshDeadlineMs: this.refreshDeadlineMs,
927
+ leaseId: this.currentLeaseId
928
+ });
929
+ const newExp = await this.onRefreshLease();
930
+ this.refreshPending = false;
931
+ if (newExp) {
932
+ this.scheduleRefresh(newExp);
933
+ }
934
+ }
935
+ catch (err) {
936
+ // If it's an offline-ish error, buffer and try after reconnect
937
+ if (this.isOfflineError(err)) {
938
+ this.refreshPending = true;
939
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
940
+ this.logger?.debug('mqtt.control_plane.refresh.buffered', {
941
+ reason: 'connection_closed_during_refresh',
942
+ error: err?.message || String(err),
943
+ code: err?.code,
944
+ refreshDeadlineMs: this.refreshDeadlineMs,
945
+ leaseId: this.currentLeaseId
946
+ });
947
+ return;
948
+ }
949
+ // Check if deadline exceeded before treating as fatal
950
+ if (this.refreshDeadlineMs && Date.now() > this.refreshDeadlineMs) {
951
+ this.handleFatal("jwt_expired_before_refresh", err);
952
+ return;
953
+ }
954
+ // Real failure (non-recoverable, non-offline error)
955
+ this.handleFatal("jwt_refresh_failed", err);
956
+ }
957
+ }
958
+ /**
959
+ * Check if error is an offline/connection error (should buffer refresh).
960
+ * @param {any} err
961
+ * @returns {boolean}
962
+ */
963
+ isOfflineError(err) {
964
+ const msg = (err && err.message) || "";
965
+ const code = (err && err.code) || "";
966
+ return (msg.includes("offline") ||
967
+ msg.includes("not connected") ||
968
+ msg.includes("Connection closed") ||
969
+ code === "ECONNRESET" ||
970
+ code === "ETIMEDOUT");
971
+ }
972
+ /**
973
+ * QPA-CLI-08: Ensure a refresh is scheduled after reconnect.
974
+ * Checks if refresh is pending or if we need to re-arm a refresh.
975
+ */
976
+ ensureRefreshScheduled() {
977
+ // Safety buffer: 5 minutes before lease expiry
978
+ const SAFETY_BUFFER_MS = 5 * 60 * 1000;
979
+ this.logger?.debug('jwt.refresh.rearm.checking', {
980
+ refreshDeadlineMs: this.refreshDeadlineMs,
981
+ leaseId: this.currentLeaseId,
982
+ refreshPending: this.refreshPending,
983
+ hasRefreshTimer: this.refreshTimer !== null,
984
+ mqttOnline: this.mqttOnline
985
+ });
986
+ // If no lease expiration tracked, nothing to do (still waiting for lease)
987
+ if (!this.refreshDeadlineMs) {
988
+ this.logger?.debug('jwt.refresh.rearm.skip', {
989
+ reason: 'no_lease',
990
+ refreshDeadlineMs: null,
991
+ leaseId: this.currentLeaseId
992
+ });
993
+ return;
994
+ }
995
+ const now = Date.now();
996
+ const expEpochMs = this.refreshDeadlineMs;
997
+ const timeUntilExpiry = expEpochMs - now;
998
+ // If lease already expired, let existing fatal path handle it
999
+ if (timeUntilExpiry <= 0) {
1000
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1001
+ reason: 'lease_expired',
1002
+ expEpochMs,
1003
+ leaseId: this.currentLeaseId,
1004
+ timeUntilExpiry
1005
+ });
1006
+ return;
1007
+ }
1008
+ // If refresh is already pending, existing retry/resend logic will handle it
1009
+ if (this.refreshPending) {
1010
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1011
+ reason: 'pending',
1012
+ refreshPending: true,
1013
+ expEpochMs,
1014
+ leaseId: this.currentLeaseId
1015
+ });
1016
+ return;
1017
+ }
1018
+ // Calculate when the next refresh would be scheduled (based on refreshEarlySeconds)
1019
+ // This is when the refresh timer would fire if it exists
1020
+ const nextRefreshMs = expEpochMs - (this.refreshEarlySeconds * 1000);
1021
+ const timeUntilNextRefresh = nextRefreshMs - now;
1022
+ const safetyBufferPointMs = expEpochMs - SAFETY_BUFFER_MS;
1023
+ // Check if refresh timer is missing or if next refresh is too close to expiry
1024
+ // If nextRefreshMs > safetyBufferPointMs, the refresh is scheduled too late
1025
+ const hasRefreshTimer = this.refreshTimer !== null;
1026
+ const needsRearm = !hasRefreshTimer || nextRefreshMs > safetyBufferPointMs;
1027
+ this.logger?.debug('jwt.refresh.rearm.calculated', {
1028
+ expEpochMs,
1029
+ leaseId: this.currentLeaseId,
1030
+ nextRefreshMs,
1031
+ timeUntilNextRefresh,
1032
+ safetyBufferPointMs,
1033
+ hasRefreshTimer,
1034
+ needsRearm,
1035
+ now
1036
+ });
1037
+ if (needsRearm) {
1038
+ // Determine reason for rearm
1039
+ const reason = !hasRefreshTimer ? 'no_timer' : 'approaching_expiration';
1040
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1041
+ this.logger?.debug('jwt.refresh.rearm', {
1042
+ reason,
1043
+ expEpochMs,
1044
+ leaseId: this.currentLeaseId,
1045
+ nextRefreshMs: hasRefreshTimer ? nextRefreshMs : null,
1046
+ timeUntilExpiry,
1047
+ safetyBufferMs: SAFETY_BUFFER_MS,
1048
+ hasRefreshTimer
1049
+ });
1050
+ // Trigger a new refresh publish immediately
1051
+ // This will set refreshPending = true and update refreshDeadlineMs via scheduleRefresh
1052
+ void this.refreshLeaseToken('rearm');
1053
+ }
1054
+ else {
1055
+ // Safe deadline exists, skip rearm
1056
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1057
+ reason: 'safe_deadline',
1058
+ nextRefreshMs,
1059
+ expEpochMs,
1060
+ leaseId: this.currentLeaseId,
1061
+ timeUntilNextRefresh,
1062
+ timeUntilExpiry,
1063
+ safetyBufferPointMs
1064
+ });
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Handle fatal error (JWT expired, max retries, etc.).
1069
+ * @param {string} reason
1070
+ * @param {any} [err]
1071
+ */
1072
+ handleFatal(reason, err) {
1073
+ const errorDetails = {
1074
+ reason,
1075
+ error: err?.message || String(err),
1076
+ errorCode: err?.code,
1077
+ errorName: err?.name,
1078
+ clientId: this.currentClientId,
1079
+ baseClientId: this.baseClientId,
1080
+ reconnectAttempts: this.reconnectAttempts,
1081
+ hardErrorCount: this.hardErrorCount,
1082
+ policyInfo: `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`
1083
+ };
1084
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
1085
+ this.onFatalError?.(reason, err);
1086
+ void this.disconnect();
1087
+ }
1088
+ }