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
package/src/commands/tunnel.js
CHANGED
|
@@ -12,6 +12,71 @@ import { MessageIngress } from "../mqtt/ingress.js";
|
|
|
12
12
|
|
|
13
13
|
const DEVICE_JSON_PATH = join(process.env.HOME ?? '', '.asyx', 'device.json');
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* QPA-CLI-09: Publish refresh request with ECONNRESET error handling.
|
|
17
|
+
* Catches connection reset errors during publish and returns a sentinel value
|
|
18
|
+
* instead of throwing, so the CLI doesn't exit with "Unexpected error".
|
|
19
|
+
*
|
|
20
|
+
* @param {Object} coordinatorCore - MQTT core client with publish method
|
|
21
|
+
* @param {string} topic - MQTT topic to publish to
|
|
22
|
+
* @param {Object} payload - Refresh payload object (will be JSON stringified)
|
|
23
|
+
* @param {string} refreshRequestId - Request ID for logging
|
|
24
|
+
* @param {Object} logger - Logger instance
|
|
25
|
+
* @returns {Promise<boolean>} Returns true on success, false on ECONNRESET (buffered), throws on other errors
|
|
26
|
+
*/
|
|
27
|
+
export async function publishRefreshRequestWithErrorHandling(
|
|
28
|
+
coordinatorCore,
|
|
29
|
+
topic,
|
|
30
|
+
payload,
|
|
31
|
+
refreshRequestId,
|
|
32
|
+
logger
|
|
33
|
+
) {
|
|
34
|
+
try {
|
|
35
|
+
await coordinatorCore.publish({
|
|
36
|
+
topic,
|
|
37
|
+
payload: JSON.stringify(payload),
|
|
38
|
+
qos: 1,
|
|
39
|
+
retain: false
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
43
|
+
logger.debug('jwt.refresh.request.sent', { refreshRequestId });
|
|
44
|
+
return true;
|
|
45
|
+
} catch (publishError) {
|
|
46
|
+
// Check if this is a connection reset error (transient condition)
|
|
47
|
+
const isConnectionError =
|
|
48
|
+
publishError?.code === 'ECONNRESET' ||
|
|
49
|
+
publishError?.errno === -54 || // macOS/Linux ECONNRESET errno
|
|
50
|
+
publishError?.message?.includes('ECONNRESET') ||
|
|
51
|
+
publishError?.message?.includes('Connection closed') ||
|
|
52
|
+
publishError?.message?.includes('connection closed');
|
|
53
|
+
|
|
54
|
+
if (isConnectionError) {
|
|
55
|
+
// QPA-CLI-09: Return false instead of throwing - refresh is buffered, CLI stays alive
|
|
56
|
+
// The MqttControlPlaneClient will detect the disconnect and set refreshPending=true
|
|
57
|
+
// The re-arm logic will retry after reconnect
|
|
58
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
59
|
+
logger.debug('jwt.refresh.publish.econnreset', {
|
|
60
|
+
refreshRequestId,
|
|
61
|
+
error: publishError?.message || String(publishError),
|
|
62
|
+
code: publishError?.code,
|
|
63
|
+
action: 'buffered_for_retry'
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// Return false to indicate buffered (don't throw - prevents "Unexpected error" log)
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// For non-connection errors (e.g., JSON parse, invalid payload), rethrow
|
|
71
|
+
logger.error('jwt.refresh.publish.error', {
|
|
72
|
+
refreshRequestId,
|
|
73
|
+
error: publishError?.message || String(publishError),
|
|
74
|
+
code: publishError?.code
|
|
75
|
+
});
|
|
76
|
+
throw publishError;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
15
80
|
export default async function tunnel(args = []) {
|
|
16
81
|
// Device credential guard
|
|
17
82
|
await access(DEVICE_JSON_PATH, fsConstants.F_OK).catch(() => {
|
|
@@ -27,6 +92,8 @@ export default async function tunnel(args = []) {
|
|
|
27
92
|
process.stdout.write(`Tunnel commands:\n`);
|
|
28
93
|
process.stdout.write(` asyx tunnel connect Connect to control plane (TLS 8883)\n`);
|
|
29
94
|
process.stdout.write(` asyx tunnel --http --port <n> Create HTTP tunnel on local port <n>\n`);
|
|
95
|
+
process.stdout.write(` asyx tunnel --http --port <n> --secgroup <slug> Create HTTP tunnel with QuickPass security group\n`);
|
|
96
|
+
process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
|
|
30
97
|
process.stdout.write(` asyx tunnel --help Show this help\n`);
|
|
31
98
|
return;
|
|
32
99
|
}
|
|
@@ -36,7 +103,11 @@ export default async function tunnel(args = []) {
|
|
|
36
103
|
|
|
37
104
|
// Handle new --http --port flags
|
|
38
105
|
if (parsed.http && parsed.port) {
|
|
39
|
-
|
|
106
|
+
// QPA-CLI-11: Track QuickPass request for vault UX messaging
|
|
107
|
+
if (parsed.secGroupSlug) {
|
|
108
|
+
logger.info("qp.requested", { group: parsed.secGroupSlug });
|
|
109
|
+
}
|
|
110
|
+
return httpTunnel(parsed.port, parsed.secGroupSlug);
|
|
40
111
|
}
|
|
41
112
|
|
|
42
113
|
// Fail fast on unsupported combinations
|
|
@@ -77,6 +148,16 @@ function parseArgs(args) {
|
|
|
77
148
|
process.stderr.write("Error: --port requires a port number\n");
|
|
78
149
|
process.exit(2);
|
|
79
150
|
}
|
|
151
|
+
} else if (arg === '--secgroup') {
|
|
152
|
+
// QPA-04: Parse --secgroup flag
|
|
153
|
+
if (i + 1 < args.length) {
|
|
154
|
+
parsed.secGroupSlug = args[i + 1];
|
|
155
|
+
i++; // Skip next argument as it's the slug value
|
|
156
|
+
} else {
|
|
157
|
+
logger.error("cli.args.secgroup_missing", {});
|
|
158
|
+
process.stderr.write("Error: --secgroup requires a slug\n");
|
|
159
|
+
process.exit(2);
|
|
160
|
+
}
|
|
80
161
|
} else if (arg === '--help' || arg === '-h') {
|
|
81
162
|
parsed.help = true;
|
|
82
163
|
}
|
|
@@ -183,7 +264,8 @@ async function connect() {
|
|
|
183
264
|
// CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers)
|
|
184
265
|
const ingress = new MessageIngress({
|
|
185
266
|
maxAwaiters: 100,
|
|
186
|
-
observability: process.env.ASYX_DEBUG === '1'
|
|
267
|
+
observability: process.env.ASYX_DEBUG === '1',
|
|
268
|
+
logger // QPA-CLI-10: Pass logger for quiet mode
|
|
187
269
|
});
|
|
188
270
|
|
|
189
271
|
// Set up the CP-3F dispatcher
|
|
@@ -242,14 +324,18 @@ async function connect() {
|
|
|
242
324
|
await new Promise(() => {}); // eslint-disable-line no-new
|
|
243
325
|
}
|
|
244
326
|
|
|
245
|
-
async function httpTunnel(localPort) {
|
|
246
|
-
logger.info('cli.http.start', { localPort });
|
|
247
|
-
|
|
327
|
+
async function httpTunnel(localPort, secGroupSlug) {
|
|
328
|
+
logger.info('cli.http.start', { localPort, secGroupSlug });
|
|
329
|
+
// QPA-CLI-11: Vault UX messaging - Initializing tunnel
|
|
330
|
+
process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
|
|
248
331
|
|
|
249
332
|
// 0) Imports (kept local to this command to avoid global side-effects)
|
|
250
|
-
const { loadAwsIotConfig
|
|
333
|
+
const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
|
|
251
334
|
const { MqttCore } = await import("@asyx/mqtt-core");
|
|
252
335
|
const { waitForAssignment } = await import("../state/assignment.js");
|
|
336
|
+
const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
|
|
337
|
+
const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
|
|
338
|
+
const { readFileSync } = await import("node:fs");
|
|
253
339
|
|
|
254
340
|
// 1) Load IoT config (throws with clear messages if misconfigured)
|
|
255
341
|
let cfg;
|
|
@@ -262,82 +348,445 @@ async function httpTunnel(localPort) {
|
|
|
262
348
|
}
|
|
263
349
|
|
|
264
350
|
logger.info("cli.http.control_plane.establish", {});
|
|
265
|
-
|
|
351
|
+
// QPA-CLI-11: Vault UX messaging - Negotiating control-plane security
|
|
352
|
+
process.stdout.write(`🔐 Negotiating control-plane security…\n`);
|
|
266
353
|
|
|
267
354
|
// CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
|
|
268
355
|
const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
|
|
269
356
|
|
|
270
|
-
//
|
|
271
|
-
|
|
272
|
-
const
|
|
357
|
+
// Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
|
|
358
|
+
// WebSocket endpoints ignore client certificates, so we must use TLS
|
|
359
|
+
const port = 443;
|
|
360
|
+
const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
|
|
361
|
+
|
|
362
|
+
// Load certificates for MQTT TLS options
|
|
363
|
+
const ca = readFileSync(cfg.caPath);
|
|
364
|
+
const cert = readFileSync(cfg.certPath);
|
|
365
|
+
const key = readFileSync(cfg.keyPath);
|
|
366
|
+
|
|
367
|
+
// CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
|
|
368
|
+
const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
|
|
369
|
+
|
|
370
|
+
// CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
|
|
371
|
+
const baseClientId = cfg.clientId;
|
|
372
|
+
|
|
373
|
+
// QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
|
|
374
|
+
const tunnelInstanceRef = { tunnel: null };
|
|
375
|
+
|
|
376
|
+
// QPA-CLI-05: Store coordinator references for onRefreshLease callback
|
|
377
|
+
// These will be set after core and ingress are created
|
|
378
|
+
let coordinatorCoreRef = null;
|
|
379
|
+
let coordinatorIngressRef = null;
|
|
380
|
+
let deviceIdRef = cfg.clientId;
|
|
381
|
+
let localPortRef = localPort;
|
|
382
|
+
let secGroupSlugRef = secGroupSlug;
|
|
383
|
+
// Track subscription state to ensure refresh requests wait for subscription to be active
|
|
384
|
+
let subscriptionReadyRef = { ready: false };
|
|
385
|
+
|
|
386
|
+
// 2) Build MqttControlPlaneClient for connection management
|
|
387
|
+
// Use mqtts (TLS) protocol with client certificates for AWS IoT authentication
|
|
388
|
+
const mqttClient = new MqttControlPlaneClient({
|
|
389
|
+
url: mqttUrl,
|
|
390
|
+
baseClientId,
|
|
391
|
+
mqttOptions: {
|
|
392
|
+
protocol: 'mqtts',
|
|
393
|
+
port: 443,
|
|
394
|
+
cert,
|
|
395
|
+
key,
|
|
396
|
+
ca,
|
|
397
|
+
rejectUnauthorized: true,
|
|
398
|
+
keepalive,
|
|
399
|
+
connectTimeout: 8000,
|
|
400
|
+
// ALPN for port 443 (AWS IoT)
|
|
401
|
+
ALPNProtocols: ['x-amzn-mqtt-ca'],
|
|
402
|
+
},
|
|
403
|
+
mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
|
|
404
|
+
logger,
|
|
405
|
+
onConnected: async (mqttClientInstance) => {
|
|
406
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
407
|
+
logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
|
|
408
|
+
// QPA-CLI-11: Vault UX messaging - Control-plane sealed
|
|
409
|
+
process.stdout.write("✅ Control-plane sealed\n");
|
|
410
|
+
|
|
411
|
+
// Resubscribe to topics on reconnect (MqttControlPlaneClient manages subscriptions)
|
|
412
|
+
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
413
|
+
subscriptionReadyRef.ready = false;
|
|
414
|
+
try {
|
|
415
|
+
await mqttClient.subscribe(evtWildcard, 0);
|
|
416
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
417
|
+
logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
|
|
418
|
+
// Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
|
|
419
|
+
// This prevents race conditions where refresh requests are published before subscription is active
|
|
420
|
+
subscriptionReadyRef.ready = true;
|
|
421
|
+
} catch (e) {
|
|
422
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
423
|
+
logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
|
|
424
|
+
// Mark ready even on failure to avoid blocking forever
|
|
425
|
+
subscriptionReadyRef.ready = true;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// QPA-CLI-05: Auto-resume is now handled by MqttControlPlaneClient's refresh buffering
|
|
429
|
+
// The onRefreshLease callback will be called automatically when MQTT reconnects if refreshPending is true
|
|
430
|
+
},
|
|
431
|
+
onOffline: (reason) => {
|
|
432
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
433
|
+
logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
|
|
434
|
+
process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
|
|
435
|
+
// Clear subscription ready flag on disconnect so we wait for resubscription on reconnect
|
|
436
|
+
subscriptionReadyRef.ready = false;
|
|
437
|
+
},
|
|
438
|
+
onFatalError: (reason, err) => {
|
|
439
|
+
logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
|
|
440
|
+
process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
|
|
441
|
+
process.exit(1);
|
|
442
|
+
},
|
|
443
|
+
// QPA-CLI-05: Wire onRefreshLease to handle JWT refresh via coordinator
|
|
444
|
+
onRefreshLease: async () => {
|
|
445
|
+
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
446
|
+
throw new Error("Coordinator not available for refresh");
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const { getAssignment } = await import('../state/assignment.js');
|
|
450
|
+
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
451
|
+
|
|
452
|
+
// Get current assignment to reuse lease
|
|
453
|
+
const currentAssignment = getAssignment();
|
|
454
|
+
if (!currentAssignment) {
|
|
455
|
+
throw new Error("No current assignment for refresh");
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const leaseId = currentAssignment.leaseId;
|
|
459
|
+
if (!leaseId) {
|
|
460
|
+
throw new Error("No leaseId in current assignment");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Build refresh payload
|
|
464
|
+
const refreshRequestId = `refresh-${Date.now()}`;
|
|
465
|
+
const fingerprint = await getFpHash(deviceIdRef);
|
|
466
|
+
|
|
467
|
+
const refreshPayload = {
|
|
468
|
+
requestId: refreshRequestId,
|
|
469
|
+
refreshOf: leaseId,
|
|
470
|
+
proto: 'http',
|
|
471
|
+
localPort: localPortRef,
|
|
472
|
+
clientId: deviceIdRef,
|
|
473
|
+
...fingerprint
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
477
|
+
if (secGroupSlugRef) {
|
|
478
|
+
refreshPayload.secGroupSlug = secGroupSlugRef;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// Cancel any existing awaiters for this leaseId before starting a new refresh
|
|
482
|
+
// This prevents duplicate awaiters from accumulating when multiple refresh attempts happen
|
|
483
|
+
const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
|
|
484
|
+
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
485
|
+
// Test if this awaiter matches open_ack messages (likely a stale refresh awaiter)
|
|
486
|
+
try {
|
|
487
|
+
const testMessage = {
|
|
488
|
+
topic: ackTopic,
|
|
489
|
+
payload: { type: 'open_ack', requestId: 'test' }
|
|
490
|
+
};
|
|
491
|
+
// If the criteria matches open_ack messages, it's likely a refresh awaiter
|
|
492
|
+
const matches = awaiter.criteria(testMessage);
|
|
493
|
+
// Only cancel if it matches open_ack (we don't want to cancel other awaiters)
|
|
494
|
+
return matches;
|
|
495
|
+
} catch {
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
if (cancelled > 0) {
|
|
501
|
+
logger.debug('jwt.refresh.awaiter.cancelled_stale', {
|
|
502
|
+
refreshRequestId,
|
|
503
|
+
cancelledCount: cancelled,
|
|
504
|
+
reason: 'new_refresh_starting'
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// Wait for subscription to be ready before publishing (prevents race where ack is published before subscription is active)
|
|
509
|
+
// Only wait if subscription is not ready (e.g., after reconnect before resubscription completes)
|
|
510
|
+
if (!subscriptionReadyRef.ready) {
|
|
511
|
+
logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
|
|
512
|
+
// Wait up to 2 seconds for subscription to be ready (should be immediate after subscribe() resolves)
|
|
513
|
+
const maxWait = 2000;
|
|
514
|
+
const startWait = Date.now();
|
|
515
|
+
while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
|
|
516
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
517
|
+
}
|
|
518
|
+
if (!subscriptionReadyRef.ready) {
|
|
519
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
520
|
+
logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
521
|
+
} else {
|
|
522
|
+
logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Set up topic and wait for ack
|
|
527
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
|
|
528
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
529
|
+
|
|
530
|
+
// Log awaiter registration for debugging
|
|
531
|
+
logger.debug('jwt.refresh.awaiter.registered', {
|
|
532
|
+
refreshRequestId,
|
|
533
|
+
timeoutMs: ACK_TIMEOUT_MS,
|
|
534
|
+
expectedType: 'open_ack'
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
538
|
+
try {
|
|
539
|
+
const parsed = message.payload;
|
|
540
|
+
const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
541
|
+
|
|
542
|
+
// Log matching attempts for debugging
|
|
543
|
+
if (parsed?.type === 'open_ack') {
|
|
544
|
+
logger.debug('jwt.refresh.awaiter.checking', {
|
|
545
|
+
refreshRequestId,
|
|
546
|
+
receivedRequestId: parsed.requestId,
|
|
547
|
+
receivedType: parsed.type,
|
|
548
|
+
isMatch,
|
|
549
|
+
topic: message.topic
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
return isMatch;
|
|
554
|
+
} catch (e) {
|
|
555
|
+
logger.debug('jwt.refresh.awaiter.criteria_error', {
|
|
556
|
+
refreshRequestId,
|
|
557
|
+
error: e.message
|
|
558
|
+
});
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
}, ACK_TIMEOUT_MS);
|
|
562
|
+
|
|
563
|
+
// Publish refresh request
|
|
564
|
+
// QPA-CLI-09: Catch ECONNRESET during publish to prevent fatal exit
|
|
565
|
+
const publishSuccess = await publishRefreshRequestWithErrorHandling(
|
|
566
|
+
coordinatorCoreRef,
|
|
567
|
+
cmdOpenTopic,
|
|
568
|
+
refreshPayload,
|
|
569
|
+
refreshRequestId,
|
|
570
|
+
logger
|
|
571
|
+
);
|
|
572
|
+
|
|
573
|
+
// If publish returned false, ECONNRESET was caught and buffered
|
|
574
|
+
// Throw an error that MqttControlPlaneClient recognizes as offline error
|
|
575
|
+
// This ensures refreshPending stays true and re-arm logic knows refresh is needed
|
|
576
|
+
// The error will be caught by MqttControlPlaneClient and buffered (not bubbled up)
|
|
577
|
+
if (publishSuccess === false) {
|
|
578
|
+
const bufferedError = new Error('Connection closed during refresh publish');
|
|
579
|
+
bufferedError.code = 'ECONNRESET';
|
|
580
|
+
throw bufferedError;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Wait for ack with reconnect retry on timeout
|
|
584
|
+
let ackResult;
|
|
585
|
+
try {
|
|
586
|
+
ackResult = await ackPromise;
|
|
587
|
+
} catch (timeoutError) {
|
|
588
|
+
// QPA-CLI-07: On timeout, reconnect control-plane and retry once
|
|
589
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
590
|
+
logger.debug('jwt.refresh.timeout', {
|
|
591
|
+
error: timeoutError.message,
|
|
592
|
+
action: 'reconnect_and_retry',
|
|
593
|
+
requestId: refreshRequestId
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
// Cancel any existing awaiters for this requestId before retrying
|
|
597
|
+
// This prevents duplicate awaiters from accumulating when retrying
|
|
598
|
+
const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
|
|
599
|
+
// Test if this awaiter matches the same requestId
|
|
600
|
+
try {
|
|
601
|
+
// Create a test message to see if the awaiter's criteria would match
|
|
602
|
+
// We can't directly inspect the criteria, so we test it with a mock message
|
|
603
|
+
const testMessage = {
|
|
604
|
+
topic: `asyx/tunnel/clients/${deviceIdRef}/evt/ack`,
|
|
605
|
+
payload: { type: 'open_ack', requestId: refreshRequestId }
|
|
606
|
+
};
|
|
607
|
+
return awaiter.criteria(testMessage);
|
|
608
|
+
} catch {
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
if (cancelled > 0) {
|
|
614
|
+
logger.debug('jwt.refresh.awaiter.cancelled_duplicates', {
|
|
615
|
+
refreshRequestId,
|
|
616
|
+
cancelledCount: cancelled
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// Force reconnect to get fresh MQTT session
|
|
621
|
+
await mqttClient.forceReconnect('ack_timeout');
|
|
622
|
+
|
|
623
|
+
// Re-register awaiter with same timeout after reconnect; ack might already be queued
|
|
624
|
+
logger.debug('jwt.refresh.awaiter.retry_registered', {
|
|
625
|
+
refreshRequestId,
|
|
626
|
+
timeoutMs: ACK_TIMEOUT_MS
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
630
|
+
try {
|
|
631
|
+
const parsed = message.payload;
|
|
632
|
+
const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
633
|
+
|
|
634
|
+
// Log matching attempts for debugging
|
|
635
|
+
if (parsed?.type === 'open_ack') {
|
|
636
|
+
logger.debug('jwt.refresh.awaiter.retry_checking', {
|
|
637
|
+
refreshRequestId,
|
|
638
|
+
receivedRequestId: parsed.requestId,
|
|
639
|
+
receivedType: parsed.type,
|
|
640
|
+
isMatch,
|
|
641
|
+
topic: message.topic
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
return isMatch;
|
|
646
|
+
} catch (e) {
|
|
647
|
+
logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
|
|
648
|
+
refreshRequestId,
|
|
649
|
+
error: e.message
|
|
650
|
+
});
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}, ACK_TIMEOUT_MS);
|
|
654
|
+
|
|
655
|
+
try {
|
|
656
|
+
ackResult = await retryAckPromise;
|
|
657
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
658
|
+
logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
|
|
659
|
+
} catch (retryError) {
|
|
660
|
+
logger.error('jwt.refresh.timeout', {
|
|
661
|
+
error: retryError.message,
|
|
662
|
+
action: 'give_up',
|
|
663
|
+
requestId: refreshRequestId
|
|
664
|
+
});
|
|
665
|
+
throw new Error(`Refresh timeout after reconnect: ${retryError.message}`);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// Get new assignment
|
|
670
|
+
const newAssignment = getAssignment();
|
|
671
|
+
if (!newAssignment) {
|
|
672
|
+
throw new Error("No new assignment after refresh");
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// Extract expiration from new JWT
|
|
676
|
+
const newJwt = newAssignment.jwt;
|
|
677
|
+
const parts = newJwt.split('.');
|
|
678
|
+
if (parts.length !== 3) {
|
|
679
|
+
throw new Error("Invalid JWT format in new assignment");
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
683
|
+
const expMs = payload.exp ? payload.exp * 1000 : null;
|
|
684
|
+
|
|
685
|
+
if (!expMs) {
|
|
686
|
+
throw new Error("No expiration in new JWT");
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// QPA-CLI-05: Notify HttpTunnel that new JWT is available
|
|
690
|
+
// HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
|
|
691
|
+
if (tunnelInstanceRef.tunnel) {
|
|
692
|
+
// Update HttpTunnel with new JWT and assignment
|
|
693
|
+
tunnelInstanceRef.tunnel.jwt = newJwt;
|
|
694
|
+
tunnelInstanceRef.tunnel.requestId = newAssignment.requestId;
|
|
695
|
+
tunnelInstanceRef.tunnel.relayUrl = newAssignment.relayUrl;
|
|
696
|
+
tunnelInstanceRef.tunnel.headers = {
|
|
697
|
+
'Authorization': `Bearer ${newJwt}`,
|
|
698
|
+
'X-Asyx-DeviceId': deviceIdRef,
|
|
699
|
+
'X-Asyx-RequestId': newAssignment.requestId
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
// Update jwtMeta for HttpTunnel
|
|
703
|
+
tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
|
|
704
|
+
|
|
705
|
+
// Record refresh timestamp and delta metrics
|
|
706
|
+
const { recordRefresh } = await import('../state/assignment.js');
|
|
707
|
+
const deltaMs = recordRefresh(Date.now());
|
|
708
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
709
|
+
logger.debug('jwt.refresh.delta', { deltaMs });
|
|
710
|
+
|
|
711
|
+
// Try in-band reauth if WebSocket is open
|
|
712
|
+
if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
|
|
713
|
+
const prevJti = tunnelInstanceRef.tunnel.jwtMeta?.token
|
|
714
|
+
? tunnelInstanceRef.tunnel._extractJti(tunnelInstanceRef.tunnel.jwtMeta.token)
|
|
715
|
+
: null;
|
|
716
|
+
try {
|
|
717
|
+
const reauthSuccess = await tunnelInstanceRef.tunnel.reauthInBand(newJwt, prevJti, 'timer');
|
|
718
|
+
if (reauthSuccess) {
|
|
719
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
720
|
+
logger.debug('jwt.refresh.success', { method: 'in_band', leaseId: newAssignment.leaseId });
|
|
721
|
+
return expMs;
|
|
722
|
+
}
|
|
723
|
+
} catch (reauthError) {
|
|
724
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
725
|
+
logger.debug('jwt.reauth.exception', { error: reauthError.message });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Fallback to reconnect
|
|
730
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
731
|
+
logger.debug('jwt.refresh.reconnect', { leaseId: newAssignment.leaseId });
|
|
732
|
+
await tunnelInstanceRef.tunnel._attemptConnect();
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
736
|
+
logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
|
|
737
|
+
return expMs;
|
|
738
|
+
},
|
|
739
|
+
});
|
|
740
|
+
|
|
741
|
+
// Create Transport adapter and MqttCore
|
|
742
|
+
const transport = new MqttControlPlaneTransport(mqttClient);
|
|
743
|
+
const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
|
|
273
744
|
|
|
274
|
-
// CLI-IMG-ControlPlane-Watchdog: Expose helpers
|
|
745
|
+
// CLI-IMG-ControlPlane-Watchdog: Expose helpers for HttpTunnel compatibility
|
|
275
746
|
const isControlPlaneConnected = () => {
|
|
276
|
-
|
|
277
|
-
if (t && typeof t.isControlPlaneConnected === 'function') return t.isControlPlaneConnected();
|
|
278
|
-
const underlying = (core && (core.transport || core._transport));
|
|
279
|
-
if (underlying && typeof underlying.isControlPlaneConnected === 'function') return underlying.isControlPlaneConnected();
|
|
280
|
-
return false;
|
|
281
|
-
} catch {
|
|
282
|
-
return false;
|
|
283
|
-
}
|
|
747
|
+
return mqttClient.isOnline();
|
|
284
748
|
};
|
|
749
|
+
|
|
285
750
|
const waitForControlPlane = () => {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const underlying = (core && (core.transport || core._transport));
|
|
289
|
-
if (underlying && typeof underlying.waitForConnect === 'function') return underlying.waitForConnect(CONTROL_PLANE_TIMEOUT_MS);
|
|
290
|
-
// Fallback: poll isControlPlaneConnected until timeout
|
|
291
|
-
logger.warn('mqtt.control_plane.helper_missing', { fn: 'waitForConnect' });
|
|
292
|
-
const start = Date.now();
|
|
293
|
-
return new Promise((resolve, reject) => {
|
|
294
|
-
const interval = setInterval(() => {
|
|
295
|
-
if (isControlPlaneConnected()) {
|
|
296
|
-
clearInterval(interval);
|
|
297
|
-
resolve();
|
|
298
|
-
} else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
|
|
299
|
-
clearInterval(interval);
|
|
300
|
-
reject(new Error('control_plane_timeout'));
|
|
301
|
-
}
|
|
302
|
-
}, 250);
|
|
303
|
-
});
|
|
304
|
-
} catch (e) {
|
|
305
|
-
return Promise.reject(e);
|
|
751
|
+
if (mqttClient.isOnline()) {
|
|
752
|
+
return Promise.resolve();
|
|
306
753
|
}
|
|
754
|
+
// Poll until connected or timeout
|
|
755
|
+
const start = Date.now();
|
|
756
|
+
return new Promise((resolve, reject) => {
|
|
757
|
+
const interval = setInterval(() => {
|
|
758
|
+
if (mqttClient.isOnline()) {
|
|
759
|
+
clearInterval(interval);
|
|
760
|
+
resolve();
|
|
761
|
+
} else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
|
|
762
|
+
clearInterval(interval);
|
|
763
|
+
reject(new Error('control_plane_timeout'));
|
|
764
|
+
}
|
|
765
|
+
}, 250);
|
|
766
|
+
});
|
|
307
767
|
};
|
|
308
|
-
|
|
309
|
-
// CLI-IMG-MQTT-Parity: Track first connect for persistent sessions
|
|
310
|
-
let isFirstConnect = true;
|
|
311
|
-
|
|
312
|
-
// CLI-IMG-ControlPlane-Watchdog: Register MQTT callbacks before connect
|
|
313
|
-
t.onConnect(() => {
|
|
314
|
-
logger.info("mqtt.control_plane.connected", {});
|
|
315
|
-
process.stdout.write("✅ Control-plane connection established\n");
|
|
316
|
-
});
|
|
317
768
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
769
|
+
// QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
|
|
770
|
+
// Note: MqttControlPlaneClient doesn't expose this yet - can be added if needed
|
|
771
|
+
const getLastMqttError = () => {
|
|
772
|
+
// TODO: Add getLastMqttError to MqttControlPlaneClient if needed
|
|
773
|
+
return null;
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
// QPA-CLI-03: Expose helper to force reconnect
|
|
777
|
+
const getForceReconnect = () => {
|
|
778
|
+
// MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
|
|
779
|
+
return async () => {
|
|
780
|
+
if (!mqttClient.isOnline()) {
|
|
781
|
+
await mqttClient.disconnect();
|
|
782
|
+
await mqttClient.connect();
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
};
|
|
329
786
|
|
|
330
787
|
// 3) Connect to control plane
|
|
331
788
|
try {
|
|
332
|
-
await
|
|
333
|
-
protocol: "tls",
|
|
334
|
-
port: 443,
|
|
335
|
-
keepalive,
|
|
336
|
-
clean: cleanSession,
|
|
337
|
-
reconnectMinMs: reconnectMin,
|
|
338
|
-
reconnectMaxMs: reconnectMax
|
|
339
|
-
});
|
|
340
|
-
// transport will resolve waiters on connect; nothing else required here
|
|
789
|
+
await mqttClient.connect();
|
|
341
790
|
} catch (e) {
|
|
342
791
|
logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
|
|
343
792
|
process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
|
|
@@ -345,24 +794,30 @@ async function httpTunnel(localPort) {
|
|
|
345
794
|
}
|
|
346
795
|
|
|
347
796
|
// 4) Set up topics and message handling
|
|
348
|
-
|
|
349
|
-
const
|
|
350
|
-
const
|
|
797
|
+
// CLI-MQTT-UniqueID-CleanSession: Use baseClientId for topics (not session client ID) to maintain topic stability
|
|
798
|
+
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
799
|
+
const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
|
|
800
|
+
const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
|
|
351
801
|
|
|
352
|
-
//
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
802
|
+
// Subscribe to topics after initial connect
|
|
803
|
+
// Note: MqttControlPlaneClient.onConnected callback will handle resubscription on reconnect
|
|
804
|
+
await core.subscribe(evtWildcard, 0);
|
|
805
|
+
// Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
|
|
806
|
+
subscriptionReadyRef.ready = true;
|
|
357
807
|
|
|
358
808
|
// 5) Set up message ingress and dispatcher
|
|
359
809
|
const ingress = new MessageIngress({
|
|
360
810
|
maxAwaiters: 100,
|
|
361
|
-
observability: process.env.ASYX_DEBUG === '1'
|
|
811
|
+
observability: process.env.ASYX_DEBUG === '1',
|
|
812
|
+
logger // QPA-CLI-10: Pass logger for quiet mode
|
|
362
813
|
});
|
|
363
814
|
|
|
364
815
|
ingress.setDispatcher(dispatchEvt);
|
|
365
816
|
|
|
817
|
+
// QPA-CLI-05: Store coordinator references for onRefreshLease callback
|
|
818
|
+
coordinatorCoreRef = core;
|
|
819
|
+
coordinatorIngressRef = ingress;
|
|
820
|
+
|
|
366
821
|
core.onMessage(async (m) => {
|
|
367
822
|
try {
|
|
368
823
|
await ingress.handleMessage(m);
|
|
@@ -395,6 +850,11 @@ async function httpTunnel(localPort) {
|
|
|
395
850
|
clientId: cfg.clientId,
|
|
396
851
|
...fingerprint
|
|
397
852
|
};
|
|
853
|
+
|
|
854
|
+
// QPA-04: Include secGroupSlug in cmd/open payload if provided
|
|
855
|
+
if (secGroupSlug) {
|
|
856
|
+
openPayload.secGroupSlug = secGroupSlug;
|
|
857
|
+
}
|
|
398
858
|
|
|
399
859
|
// Publish the open request
|
|
400
860
|
await core.publish({
|
|
@@ -407,7 +867,7 @@ async function httpTunnel(localPort) {
|
|
|
407
867
|
logger.info("cli.cmd.open.sent", { requestId });
|
|
408
868
|
|
|
409
869
|
// 7) Wait for ack and then connect to relay
|
|
410
|
-
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "
|
|
870
|
+
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
411
871
|
|
|
412
872
|
try {
|
|
413
873
|
const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
|
|
@@ -422,13 +882,17 @@ async function httpTunnel(localPort) {
|
|
|
422
882
|
} catch {}
|
|
423
883
|
|
|
424
884
|
// 8) Connect to relay using thin client behavior
|
|
885
|
+
// QPA-CLI-05: Pass mqttClient for refresh scheduling
|
|
425
886
|
await connectToRelay(
|
|
426
887
|
assignment,
|
|
427
888
|
cfg.clientId,
|
|
428
889
|
localPort,
|
|
429
890
|
core,
|
|
430
891
|
ingress,
|
|
431
|
-
{ isControlPlaneConnected, waitForControlPlane, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS }
|
|
892
|
+
{ isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
|
|
893
|
+
secGroupSlug,
|
|
894
|
+
tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here before infinite promise
|
|
895
|
+
mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
|
|
432
896
|
);
|
|
433
897
|
|
|
434
898
|
} catch (error) {
|
|
@@ -444,7 +908,10 @@ async function connectToRelay(
|
|
|
444
908
|
localPort,
|
|
445
909
|
coordinatorCore,
|
|
446
910
|
coordinatorIngress,
|
|
447
|
-
controlPlaneHelpers
|
|
911
|
+
controlPlaneHelpers,
|
|
912
|
+
secGroupSlug,
|
|
913
|
+
tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
|
|
914
|
+
mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
|
|
448
915
|
) {
|
|
449
916
|
// Import WebSocket bridge logic (ported from client-mvp)
|
|
450
917
|
const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
|
|
@@ -460,7 +927,11 @@ async function connectToRelay(
|
|
|
460
927
|
// CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
|
|
461
928
|
isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
|
|
462
929
|
waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
|
|
930
|
+
getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
|
|
931
|
+
getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
|
|
463
932
|
controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
|
|
933
|
+
// QPA-04: Pass secGroupSlug to HttpTunnel
|
|
934
|
+
secGroupSlug,
|
|
464
935
|
log: {
|
|
465
936
|
info: (msgOrFields, maybeFields) => {
|
|
466
937
|
if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
|
|
@@ -481,19 +952,57 @@ async function connectToRelay(
|
|
|
481
952
|
}
|
|
482
953
|
});
|
|
483
954
|
|
|
955
|
+
// QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
|
|
956
|
+
if (tunnelInstanceRef) {
|
|
957
|
+
tunnelInstanceRef.tunnel = tunnel;
|
|
958
|
+
}
|
|
959
|
+
|
|
484
960
|
try {
|
|
485
961
|
await tunnel.open();
|
|
486
962
|
|
|
487
|
-
// CLI-
|
|
488
|
-
|
|
963
|
+
// QPA-CLI-05: Schedule initial proactive refresh via MqttControlPlaneClient
|
|
964
|
+
// Decode JWT to get expiration
|
|
965
|
+
const jwtParts = assignment.jwt.split('.');
|
|
966
|
+
if (jwtParts.length === 3) {
|
|
967
|
+
try {
|
|
968
|
+
const payload = JSON.parse(Buffer.from(jwtParts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
969
|
+
const expMs = payload.exp ? payload.exp * 1000 : null;
|
|
970
|
+
if (expMs) {
|
|
971
|
+
// Use assignment.leaseId if available, otherwise pass null (will be set on next refresh)
|
|
972
|
+
const leaseId = assignment.leaseId || null;
|
|
973
|
+
mqttClient.scheduleRefresh(expMs, leaseId);
|
|
974
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
975
|
+
logger.debug("jwt.refresh.schedule", { expEpochMs: expMs, context: 'open_ack', leaseId });
|
|
976
|
+
}
|
|
977
|
+
} catch (e) {
|
|
978
|
+
logger.warn('jwt.refresh.schedule.invalid_token', { context: 'open_ack', error: e.message });
|
|
979
|
+
}
|
|
980
|
+
}
|
|
489
981
|
|
|
982
|
+
// QPA-CLI-11: Vault UX messaging - Final tunnel live message
|
|
983
|
+
const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
|
|
490
984
|
logger.info("tunnel.active", { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
985
|
+
|
|
986
|
+
// Show QuickPass secured message if QuickPass was requested and enabled
|
|
987
|
+
if (secGroupSlug && assignment.quickpassSlug) {
|
|
988
|
+
process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// Tunnel live message
|
|
992
|
+
process.stdout.write(`🌐 Tunnel live at http://localhost:${localPort}\n`);
|
|
993
|
+
|
|
994
|
+
// QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
|
|
995
|
+
// Most users don't need to know the lease term; they just care the tunnel stays alive
|
|
996
|
+
const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
|
|
997
|
+
if (logLevel === 'info' || logLevel === 'debug') {
|
|
998
|
+
process.stdout.write(` Relay: ${assignment.relayId}\n`);
|
|
999
|
+
process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
|
|
1000
|
+
}
|
|
1001
|
+
|
|
494
1002
|
process.stdout.write(` Press Ctrl+C to stop\n`);
|
|
495
1003
|
|
|
496
1004
|
// CLI-IMG-WSReconnect: Set up graceful shutdown
|
|
1005
|
+
// QPA-CLI-05: Also disconnect MqttControlPlaneClient on shutdown
|
|
497
1006
|
let shuttingDown = false;
|
|
498
1007
|
const onSig = async (sig) => {
|
|
499
1008
|
if (shuttingDown) return;
|
|
@@ -511,6 +1020,13 @@ async function connectToRelay(
|
|
|
511
1020
|
logger.error('tunnel.close.error', { error: e.message });
|
|
512
1021
|
process.stderr.write(`Error closing tunnel: ${e.message}\n`);
|
|
513
1022
|
}
|
|
1023
|
+
// QPA-CLI-05: Disconnect MqttControlPlaneClient to clear timers
|
|
1024
|
+
try {
|
|
1025
|
+
await mqttClient.disconnect();
|
|
1026
|
+
} catch (e) {
|
|
1027
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
1028
|
+
logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
|
|
1029
|
+
}
|
|
514
1030
|
clearTimeout(killer);
|
|
515
1031
|
process.exit(0);
|
|
516
1032
|
};
|
|
@@ -520,7 +1036,8 @@ async function connectToRelay(
|
|
|
520
1036
|
// CLI-REFRESH-SIGNAL: External trigger to force JWT refresh (avoids SIGUSR1 inspector conflict)
|
|
521
1037
|
try {
|
|
522
1038
|
process.once('SIGUSR2', () => {
|
|
523
|
-
|
|
1039
|
+
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
1040
|
+
logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
|
|
524
1041
|
try { tunnel.attemptJwtRefresh(); } catch (e) {
|
|
525
1042
|
logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
|
|
526
1043
|
}
|