asyx 0.1.1 → 0.1.3
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.
- package/README.md +50 -0
- package/package.json +6 -1
- package/src/commands/tunnel.js +603 -86
- package/src/control-plane/MqttControlPlaneClient.js +1145 -0
- package/src/control-plane/MqttControlPlaneTransport.js +150 -0
- package/src/lib/csr.js +32 -12
- package/src/lib/logger.js +8 -4
- package/src/mqtt/awaiter-map.js +92 -2
- package/src/mqtt/events/handlers.js +50 -9
- package/src/mqtt/ingress.js +11 -1
- package/src/state/assignment.js +1 -0
- package/src/tunnel/http-tunnel.js +219 -20
|
@@ -19,7 +19,11 @@ export class HttpTunnel {
|
|
|
19
19
|
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
20
20
|
isControlPlaneConnected = () => true,
|
|
21
21
|
waitForControlPlane = () => Promise.resolve(),
|
|
22
|
-
|
|
22
|
+
getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
|
|
23
|
+
getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
|
|
24
|
+
controlPlaneTimeoutMs = 60000,
|
|
25
|
+
// QPA-04: QuickPass security group slug
|
|
26
|
+
secGroupSlug = null
|
|
23
27
|
}) {
|
|
24
28
|
this.relayUrl = relayUrl;
|
|
25
29
|
this.jwt = jwt; // Accept JWT as-is (no validation)
|
|
@@ -28,6 +32,8 @@ export class HttpTunnel {
|
|
|
28
32
|
this.localPort = localPort;
|
|
29
33
|
this.log = log;
|
|
30
34
|
this.ws = null;
|
|
35
|
+
// QPA-04: Store secGroupSlug for use in refresh payloads
|
|
36
|
+
this.secGroupSlug = secGroupSlug;
|
|
31
37
|
|
|
32
38
|
// CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
|
|
33
39
|
this.coordinatorCore = coordinatorCore;
|
|
@@ -36,6 +42,8 @@ export class HttpTunnel {
|
|
|
36
42
|
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
37
43
|
this.isControlPlaneConnected = isControlPlaneConnected;
|
|
38
44
|
this.waitForControlPlane = waitForControlPlane;
|
|
45
|
+
this.getLastMqttError = getLastMqttError; // QPA-CLI-02: Store helper to get last MQTT error
|
|
46
|
+
this.getForceReconnect = getForceReconnect; // QPA-CLI-03: Store helper to force reconnect
|
|
39
47
|
this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
|
|
40
48
|
|
|
41
49
|
// CRT-Relay-E: Heartbeat properties
|
|
@@ -51,9 +59,15 @@ export class HttpTunnel {
|
|
|
51
59
|
this.headers = null; // Store headers for reuse during reconnects
|
|
52
60
|
|
|
53
61
|
// CLI-JWT-REFRESH: Refresh state machine
|
|
54
|
-
|
|
62
|
+
// QPA-CLI-01: Extended states for resilience
|
|
63
|
+
this.refreshState = 'idle'; // idle | pending | waiting_control_plane | retry_scheduled | fallback | failed
|
|
55
64
|
this.refreshAttempts = 0;
|
|
56
65
|
this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
|
|
66
|
+
// QPA-CLI-01: Refresh supervisor state
|
|
67
|
+
this.refreshRetryTimer = null;
|
|
68
|
+
this.refreshDeadline = null; // JWT expiry deadline (expMs - safetyMargin)
|
|
69
|
+
this.refreshRetryCount = 0;
|
|
70
|
+
this.refreshRetryMaxDelay = 30000; // Max 30s between retries
|
|
57
71
|
|
|
58
72
|
// CLI-RES-DPJWT-LEAD: Proactive refresh scheduling
|
|
59
73
|
this.refreshTimer = null;
|
|
@@ -328,27 +342,117 @@ export class HttpTunnel {
|
|
|
328
342
|
async _ensureControlPlane(reason, forceWait = false) {
|
|
329
343
|
if (!forceWait && this.isControlPlaneConnected()) return true;
|
|
330
344
|
|
|
331
|
-
|
|
345
|
+
// QPA-CLI-01: Log actual MQTT reason when control-plane is offline
|
|
346
|
+
const mqttReason = this.isControlPlaneConnected() ? 'connected' : 'offline';
|
|
347
|
+
this.log.warn({ reason, mqttReason }, "Control-plane offline, waiting for reconnect");
|
|
332
348
|
|
|
333
349
|
try {
|
|
334
350
|
// Use waitForControlPlane which internally calls transport.waitForConnect()
|
|
335
351
|
await this.waitForControlPlane();
|
|
336
|
-
|
|
352
|
+
// CLI-MQTT-UniqueID-CleanSession: Get session client ID from transport for logging
|
|
353
|
+
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
354
|
+
const sessionClientId = lastMqttError?.clientId || 'unknown';
|
|
355
|
+
this.log.info({ reason, sessionClientId }, "Control-plane reconnected");
|
|
337
356
|
return true;
|
|
338
357
|
} catch (err) {
|
|
339
|
-
//
|
|
358
|
+
// QPA-CLI-02: Get last MQTT error for diagnostic information
|
|
359
|
+
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
360
|
+
const mqttReasonCode = lastMqttError?.code;
|
|
361
|
+
const mqttReason = lastMqttError?.reason || this._extractMqttReasonFromError(lastMqttError);
|
|
362
|
+
|
|
363
|
+
// QPA-CLI-01: Extract and log actual MQTT reason from WaitForConnectError
|
|
364
|
+
let mqttErrorReason = 'unknown';
|
|
340
365
|
if (err.name === 'WaitForConnectError') {
|
|
341
|
-
|
|
366
|
+
// WaitForConnectError has a 'reason' property: 'timeout' | 'terminated'
|
|
367
|
+
mqttErrorReason = err.reason || 'timeout';
|
|
368
|
+
|
|
369
|
+
// QPA-CLI-03: Force reconnect on timeout
|
|
370
|
+
if (mqttErrorReason === 'timeout' && this.getForceReconnect) {
|
|
371
|
+
const forceReconnect = this.getForceReconnect();
|
|
372
|
+
if (forceReconnect) {
|
|
373
|
+
this.log.info('mqtt.transport.force_reconnect.attempt', { reason, attempt: 1 });
|
|
374
|
+
try {
|
|
375
|
+
await forceReconnect();
|
|
376
|
+
// Retry waitForControlPlane up to 3 times with 5s delay
|
|
377
|
+
const maxRetries = 3;
|
|
378
|
+
const retryDelayMs = 5000;
|
|
379
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
380
|
+
try {
|
|
381
|
+
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
|
|
382
|
+
await this.waitForControlPlane();
|
|
383
|
+
this.log.info('mqtt.transport.force_reconnect.success', { reason, attempt });
|
|
384
|
+
this.log.info({ reason }, "Control-plane reconnected after force reconnect");
|
|
385
|
+
return true;
|
|
386
|
+
} catch (retryErr) {
|
|
387
|
+
if (attempt < maxRetries) {
|
|
388
|
+
this.log.warn('mqtt.transport.force_reconnect.retry', { reason, attempt: attempt + 1, error: retryErr.message });
|
|
389
|
+
} else {
|
|
390
|
+
this.log.warn('mqtt.transport.force_reconnect.exhausted', { reason, attempts: maxRetries });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
} catch (forceErr) {
|
|
395
|
+
this.log.warn('mqtt.transport.force_reconnect.failed', { reason, error: forceErr.message });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// QPA-CLI-02: Include MQTT error details in log
|
|
401
|
+
this.log.warn('mqtt.transport.wait_for_connect.failed', {
|
|
402
|
+
reason,
|
|
403
|
+
mqttReason: mqttErrorReason,
|
|
404
|
+
mqttErrorCode: mqttReasonCode,
|
|
405
|
+
mqttErrorReason: mqttReason,
|
|
406
|
+
mqttEvent: lastMqttError?.event,
|
|
407
|
+
error: err.message
|
|
408
|
+
});
|
|
409
|
+
// QPA-CLI-02: User-facing message includes MQTT reason if available
|
|
410
|
+
let userMessage = `⚠️ Control-plane offline (${mqttErrorReason})`;
|
|
411
|
+
if (mqttReason && mqttReason !== 'unknown') {
|
|
412
|
+
userMessage += `. MQTT reason: ${mqttReason}`;
|
|
413
|
+
}
|
|
414
|
+
userMessage += `. Waiting for reconnect…\n`;
|
|
415
|
+
process.stdout.write(userMessage);
|
|
342
416
|
return false;
|
|
343
417
|
}
|
|
344
418
|
if (err.message === "control_plane_timeout") {
|
|
345
|
-
|
|
419
|
+
// QPA-CLI-02: Include MQTT error details in timeout log
|
|
420
|
+
this.log.warn('mqtt.transport.wait_for_connect.timeout', {
|
|
421
|
+
reason,
|
|
422
|
+
mqttErrorCode: mqttReasonCode,
|
|
423
|
+
mqttErrorReason: mqttReason,
|
|
424
|
+
mqttEvent: lastMqttError?.event
|
|
425
|
+
});
|
|
426
|
+
let userMessage = `⚠️ Control-plane offline (timeout)`;
|
|
427
|
+
if (mqttReason && mqttReason !== 'unknown') {
|
|
428
|
+
userMessage += `. MQTT reason: ${mqttReason}`;
|
|
429
|
+
}
|
|
430
|
+
userMessage += `. Waiting for reconnect…\n`;
|
|
431
|
+
process.stdout.write(userMessage);
|
|
346
432
|
return false;
|
|
347
433
|
}
|
|
348
434
|
throw err;
|
|
349
435
|
}
|
|
350
436
|
}
|
|
351
437
|
|
|
438
|
+
// QPA-CLI-02: Extract human-readable MQTT reason from error object
|
|
439
|
+
_extractMqttReasonFromError(mqttError) {
|
|
440
|
+
if (!mqttError) return 'unknown';
|
|
441
|
+
if (mqttError.reason) return mqttError.reason;
|
|
442
|
+
if (mqttError.code) {
|
|
443
|
+
const codeNum = typeof mqttError.code === 'string' ? parseInt(mqttError.code, 10) : mqttError.code;
|
|
444
|
+
const reasonMap = {
|
|
445
|
+
4: 'bad_username_password',
|
|
446
|
+
5: 'identifier_in_use',
|
|
447
|
+
6: 'server_unavailable',
|
|
448
|
+
7: 'bad_username_password',
|
|
449
|
+
8: 'not_authorized'
|
|
450
|
+
};
|
|
451
|
+
return reasonMap[codeNum] || `code_${codeNum}`;
|
|
452
|
+
}
|
|
453
|
+
return 'unknown';
|
|
454
|
+
}
|
|
455
|
+
|
|
352
456
|
async open() {
|
|
353
457
|
// CLI-IMG-WSReconnect: Start the connection process
|
|
354
458
|
return this._attemptConnect();
|
|
@@ -533,26 +637,106 @@ export class HttpTunnel {
|
|
|
533
637
|
}
|
|
534
638
|
}
|
|
535
639
|
|
|
640
|
+
// QPA-CLI-01: Schedule retry with exponential backoff
|
|
641
|
+
_scheduleRefreshRetry(reason) {
|
|
642
|
+
// Clear any existing retry timer
|
|
643
|
+
if (this.refreshRetryTimer) {
|
|
644
|
+
clearTimeout(this.refreshRetryTimer);
|
|
645
|
+
this.refreshRetryTimer = null;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// QPA-CLI-03: Check if we've exceeded the deadline AND MQTT is still offline
|
|
649
|
+
if (this.refreshDeadline && Date.now() >= this.refreshDeadline) {
|
|
650
|
+
// Only mark expired if control plane is still offline
|
|
651
|
+
if (!this.isControlPlaneConnected()) {
|
|
652
|
+
this.log.error('jwt.refresh.expired', {
|
|
653
|
+
retryCount: this.refreshRetryCount,
|
|
654
|
+
deadline: this.refreshDeadline,
|
|
655
|
+
elapsed: Date.now() - (this.refreshDeadline - this.LEAD_MS)
|
|
656
|
+
});
|
|
657
|
+
this.refreshState = 'failed';
|
|
658
|
+
process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
|
|
659
|
+
process.exit(1);
|
|
660
|
+
} else {
|
|
661
|
+
// Control plane came back, reset deadline and continue
|
|
662
|
+
this.log.info('jwt.refresh.deadline_extended', {
|
|
663
|
+
retryCount: this.refreshRetryCount,
|
|
664
|
+
oldDeadline: this.refreshDeadline
|
|
665
|
+
});
|
|
666
|
+
// Extend deadline by another 90 seconds
|
|
667
|
+
this.refreshDeadline = Date.now() + 90000;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Calculate exponential backoff delay
|
|
672
|
+
this.refreshRetryCount += 1;
|
|
673
|
+
const baseDelay = 5000; // 5 seconds
|
|
674
|
+
const delayMs = Math.min(baseDelay * Math.pow(2, this.refreshRetryCount - 1), this.refreshRetryMaxDelay);
|
|
675
|
+
|
|
676
|
+
this.log.info('jwt.refresh.delay', {
|
|
677
|
+
reason: 'control_plane_offline',
|
|
678
|
+
retryCount: this.refreshRetryCount,
|
|
679
|
+
nextDelayMs: delayMs,
|
|
680
|
+
deadline: this.refreshDeadline ? new Date(this.refreshDeadline).toISOString() : null
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
// QPA-CLI-01: Operator feedback
|
|
684
|
+
process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${this.refreshRetryCount})\n`);
|
|
685
|
+
|
|
686
|
+
this.refreshState = 'retry_scheduled';
|
|
687
|
+
this.refreshRetryTimer = setTimeout(() => {
|
|
688
|
+
this.refreshRetryTimer = null;
|
|
689
|
+
// Retry the refresh
|
|
690
|
+
this.attemptJwtRefresh().catch(err => {
|
|
691
|
+
this.log.error('jwt.refresh.retry.failed', { error: err.message, retryCount: this.refreshRetryCount });
|
|
692
|
+
});
|
|
693
|
+
}, delayMs);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// QPA-CLI-01: Cancel scheduled retry (called when MQTT reconnects)
|
|
697
|
+
_cancelRefreshRetry() {
|
|
698
|
+
if (this.refreshRetryTimer) {
|
|
699
|
+
clearTimeout(this.refreshRetryTimer);
|
|
700
|
+
this.refreshRetryTimer = null;
|
|
701
|
+
}
|
|
702
|
+
if (this.refreshState === 'retry_scheduled' || this.refreshState === 'waiting_control_plane') {
|
|
703
|
+
this.log.info('jwt.refresh.resumed', { retryCount: this.refreshRetryCount });
|
|
704
|
+
this.refreshState = 'pending';
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
536
708
|
// CLI-IMG-WSReconnect: JWT refresh logic
|
|
537
709
|
async attemptJwtRefresh() {
|
|
538
710
|
try {
|
|
539
|
-
if (
|
|
711
|
+
// QPA-CLI-01: Check if we've exceeded max attempts (only for actual refresh attempts, not retries)
|
|
712
|
+
if (this.refreshAttempts >= this.refreshMaxAttempts && this.refreshState !== 'retry_scheduled' && this.refreshState !== 'waiting_control_plane') {
|
|
540
713
|
this.log.error('jwt.refresh.exhausted', { retryCount: this.refreshAttempts });
|
|
541
714
|
this.refreshState = 'failed';
|
|
542
715
|
process.exit(1);
|
|
543
716
|
}
|
|
544
717
|
|
|
718
|
+
// QPA-CLI-01: Set refresh deadline on first attempt
|
|
719
|
+
if (this.refreshState === 'idle' && this.jwtMeta?.expMs) {
|
|
720
|
+
const safetyMargin = 90000; // QPA-CLI-03: Extended to 90 seconds safety margin
|
|
721
|
+
this.refreshDeadline = this.jwtMeta.expMs - safetyMargin;
|
|
722
|
+
this.refreshRetryCount = 0; // Reset retry count for new refresh cycle
|
|
723
|
+
}
|
|
724
|
+
|
|
545
725
|
this.refreshAttempts += 1;
|
|
546
726
|
this.refreshState = 'pending';
|
|
547
727
|
this.log.info('jwt.refresh.start', { retryCount: this.refreshAttempts });
|
|
548
728
|
|
|
549
|
-
// CLI-
|
|
729
|
+
// QPA-CLI-01: Ensure control-plane connectivity with retry logic
|
|
550
730
|
const ready = await this._ensureControlPlane("jwt_refresh");
|
|
551
731
|
if (!ready) {
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
732
|
+
// QPA-CLI-01: Instead of immediately falling back, schedule a retry
|
|
733
|
+
this.refreshState = 'waiting_control_plane';
|
|
734
|
+
this._scheduleRefreshRetry('control_plane_offline');
|
|
735
|
+
return; // Keep tunnel running, retry will happen via timer
|
|
555
736
|
}
|
|
737
|
+
|
|
738
|
+
// QPA-CLI-01: Control-plane is ready, cancel any pending retry
|
|
739
|
+
this._cancelRefreshRetry();
|
|
556
740
|
|
|
557
741
|
// Check if we have coordinator connection
|
|
558
742
|
if (!this.coordinatorCore || !this.coordinatorIngress) {
|
|
@@ -596,6 +780,11 @@ export class HttpTunnel {
|
|
|
596
780
|
...fingerprint
|
|
597
781
|
};
|
|
598
782
|
|
|
783
|
+
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
784
|
+
if (this.secGroupSlug) {
|
|
785
|
+
refreshPayload.secGroupSlug = this.secGroupSlug;
|
|
786
|
+
}
|
|
787
|
+
|
|
599
788
|
// Set up topic for refresh request
|
|
600
789
|
const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
|
|
601
790
|
|
|
@@ -671,8 +860,12 @@ export class HttpTunnel {
|
|
|
671
860
|
const deltaMs = recordRefresh(Date.now());
|
|
672
861
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
673
862
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
|
|
863
|
+
// QPA-CLI-01: Reset retry state on success
|
|
674
864
|
this.refreshState = 'idle';
|
|
675
865
|
this.refreshAttempts = 0;
|
|
866
|
+
this.refreshRetryCount = 0;
|
|
867
|
+
this.refreshDeadline = null;
|
|
868
|
+
this._cancelRefreshRetry();
|
|
676
869
|
return; // Socket stayed open, no reconnect needed
|
|
677
870
|
}
|
|
678
871
|
|
|
@@ -701,8 +894,12 @@ export class HttpTunnel {
|
|
|
701
894
|
const deltaMs = recordRefresh(Date.now());
|
|
702
895
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
703
896
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
|
|
897
|
+
// QPA-CLI-01: Reset retry state on success
|
|
704
898
|
this.refreshState = 'idle';
|
|
705
899
|
this.refreshAttempts = 0;
|
|
900
|
+
this.refreshRetryCount = 0;
|
|
901
|
+
this.refreshDeadline = null;
|
|
902
|
+
this._cancelRefreshRetry();
|
|
706
903
|
|
|
707
904
|
// CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
|
|
708
905
|
this.scheduleRefresh(this.jwt, 'refresh_success');
|
|
@@ -755,18 +952,15 @@ export class HttpTunnel {
|
|
|
755
952
|
await this.waitForControlPlane();
|
|
756
953
|
this.log.info('jwt.refresh.fallback.control_plane_recovered', { leaseId });
|
|
757
954
|
} catch (waitError) {
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
this.log.error('jwt.refresh.fallback.failure', {
|
|
955
|
+
// QPA-CLI-01: Instead of exiting, schedule a retry
|
|
956
|
+
this.log.warn('jwt.refresh.fallback.control_plane_wait_failed', {
|
|
761
957
|
error: waitError.message,
|
|
762
|
-
reason: 'control_plane_timeout_exhausted',
|
|
763
958
|
retryCount,
|
|
764
959
|
leaseId
|
|
765
960
|
});
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
continue; // Retry fallback after brief delay
|
|
961
|
+
// Schedule retry with backoff
|
|
962
|
+
this._scheduleRefreshRetry('fallback_control_plane_offline');
|
|
963
|
+
return; // Keep tunnel running, retry will happen via timer
|
|
770
964
|
}
|
|
771
965
|
}
|
|
772
966
|
|
|
@@ -1070,6 +1264,11 @@ export class HttpTunnel {
|
|
|
1070
1264
|
clearTimeout(this.refreshTimer);
|
|
1071
1265
|
this.refreshTimer = null;
|
|
1072
1266
|
}
|
|
1267
|
+
// QPA-CLI-01: Clean up retry timer
|
|
1268
|
+
if (this.refreshRetryTimer) {
|
|
1269
|
+
clearTimeout(this.refreshRetryTimer);
|
|
1270
|
+
this.refreshRetryTimer = null;
|
|
1271
|
+
}
|
|
1073
1272
|
|
|
1074
1273
|
// CLI-REAUTH: Cleanup control frame waiters
|
|
1075
1274
|
clearAllWaiters();
|