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