asyx 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,10 @@ 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(` asyx tunnel --tcp --port <n> Create TCP tunnel on local port <n> (localhost only)\n`);
97
+ process.stdout.write(` asyx tunnel --minecraft [--port 25565] [--name <svc>] Create Minecraft TCP tunnel (expands to --tcp --port 25565 --kind minecraft)\n`);
98
+ process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
30
99
  process.stdout.write(` asyx tunnel --help Show this help\n`);
31
100
  return;
32
101
  }
@@ -34,22 +103,63 @@ export default async function tunnel(args = []) {
34
103
  // Handle legacy connect command
35
104
  if (args[0] === "connect") return connect();
36
105
 
37
- // Handle new --http --port flags
38
- if (parsed.http && parsed.port) {
39
- return httpTunnel(parsed.port);
106
+ // E3-S8: Handle --minecraft flag (expands to --tcp --port 25565 --kind minecraft)
107
+ if (parsed.minecraft) {
108
+ parsed.tcp = true;
109
+ if (!parsed.port) {
110
+ parsed.port = 25565; // Default Minecraft port
111
+ }
112
+ parsed.kind = 'minecraft';
40
113
  }
41
114
 
42
- // Fail fast on unsupported combinations
115
+ // Validation: Mutual exclusion check MUST happen before dispatch to handlers
116
+ if (parsed.tcp && parsed.http) {
117
+ logger.error("cli.args.invalid", { reason: "--tcp and --http are mutually exclusive" });
118
+ process.stderr.write("Error: --tcp and --http are mutually exclusive\n");
119
+ process.exit(2);
120
+ }
121
+
122
+ // Validation: Fail fast on unsupported combinations
43
123
  if (parsed.http && !parsed.port) {
44
124
  logger.error("cli.args.invalid", { reason: "--http requires --port" });
45
125
  process.exit(2);
46
126
  }
47
127
 
48
- if (parsed.port && !parsed.http) {
49
- logger.error("cli.args.invalid", { reason: "--port requires --http" });
128
+ if (parsed.tcp && !parsed.port) {
129
+ logger.error("cli.args.invalid", { reason: "--tcp requires --port" });
130
+ process.stderr.write("Error: --tcp requires --port\n");
131
+ process.exit(2);
132
+ }
133
+
134
+ if (parsed.port && !parsed.http && !parsed.tcp) {
135
+ logger.error("cli.args.invalid", { reason: "--port requires --http or --tcp" });
136
+ process.stderr.write("Error: --port requires --http or --tcp\n");
50
137
  process.exit(2);
51
138
  }
52
139
 
140
+ // Handle new --http --port flags
141
+ if (parsed.http && parsed.port) {
142
+ // QPA-CLI-11: Track QuickPass request for vault UX messaging
143
+ if (parsed.secGroupSlug) {
144
+ logger.info("qp.requested", { group: parsed.secGroupSlug });
145
+ }
146
+ return httpTunnel(parsed.port, parsed.secGroupSlug);
147
+ }
148
+
149
+ // Handle new --tcp --port flags
150
+ if (parsed.tcp && parsed.port) {
151
+ // Validate target is localhost-only (defaults to 127.0.0.1)
152
+ const target = buildTcpTarget(parsed.port);
153
+ if (!isLocalhostTarget(target)) {
154
+ logger.error("cli.args.invalid", {
155
+ reason: `TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost). Got: ${target}`
156
+ });
157
+ process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
158
+ process.exit(2);
159
+ }
160
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind);
161
+ }
162
+
53
163
  logger.error("cli.args.unknown", { args: args.join(' ') });
54
164
  process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
55
165
  process.exit(2);
@@ -62,6 +172,12 @@ function parseArgs(args) {
62
172
  const arg = args[i];
63
173
  if (arg === '--http') {
64
174
  parsed.http = true;
175
+ } else if (arg === '--tcp') {
176
+ parsed.tcp = true;
177
+ } else if (arg === '--minecraft') {
178
+ parsed.minecraft = true;
179
+ } else if (arg === '--minecraft') {
180
+ parsed.minecraft = true;
65
181
  } else if (arg === '--port') {
66
182
  if (i + 1 < args.length) {
67
183
  const port = parseInt(args[i + 1], 10);
@@ -77,6 +193,26 @@ function parseArgs(args) {
77
193
  process.stderr.write("Error: --port requires a port number\n");
78
194
  process.exit(2);
79
195
  }
196
+ } else if (arg === '--name') {
197
+ // Optional service name for TCP mode
198
+ if (i + 1 < args.length) {
199
+ parsed.serviceName = args[i + 1];
200
+ i++; // Skip next argument as it's the service name value
201
+ } else {
202
+ logger.error("cli.args.name_missing", {});
203
+ process.stderr.write("Error: --name requires a service name\n");
204
+ process.exit(2);
205
+ }
206
+ } else if (arg === '--secgroup') {
207
+ // QPA-04: Parse --secgroup flag
208
+ if (i + 1 < args.length) {
209
+ parsed.secGroupSlug = args[i + 1];
210
+ i++; // Skip next argument as it's the slug value
211
+ } else {
212
+ logger.error("cli.args.secgroup_missing", {});
213
+ process.stderr.write("Error: --secgroup requires a slug\n");
214
+ process.exit(2);
215
+ }
80
216
  } else if (arg === '--help' || arg === '-h') {
81
217
  parsed.help = true;
82
218
  }
@@ -183,7 +319,8 @@ async function connect() {
183
319
  // CP-3G: Single ingress with awaiters + dispatcher (fix multiple onMessage handlers)
184
320
  const ingress = new MessageIngress({
185
321
  maxAwaiters: 100,
186
- observability: process.env.ASYX_DEBUG === '1'
322
+ observability: process.env.ASYX_DEBUG === '1',
323
+ logger // QPA-CLI-10: Pass logger for quiet mode
187
324
  });
188
325
 
189
326
  // Set up the CP-3F dispatcher
@@ -242,14 +379,18 @@ async function connect() {
242
379
  await new Promise(() => {}); // eslint-disable-line no-new
243
380
  }
244
381
 
245
- async function httpTunnel(localPort) {
246
- logger.info('cli.http.start', { localPort });
247
- process.stdout.write(`🚀 Starting HTTP tunnel on port ${localPort}...\n`);
382
+ async function httpTunnel(localPort, secGroupSlug) {
383
+ logger.info('cli.http.start', { localPort, secGroupSlug });
384
+ // QPA-CLI-11: Vault UX messaging - Initializing tunnel
385
+ process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
248
386
 
249
387
  // 0) Imports (kept local to this command to avoid global side-effects)
250
- const { loadAwsIotConfig, AwsIotTransport } = await import("@asyx/mqtt-broker-aws");
388
+ const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
251
389
  const { MqttCore } = await import("@asyx/mqtt-core");
252
390
  const { waitForAssignment } = await import("../state/assignment.js");
391
+ const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
392
+ const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
393
+ const { readFileSync } = await import("node:fs");
253
394
 
254
395
  // 1) Load IoT config (throws with clear messages if misconfigured)
255
396
  let cfg;
@@ -262,82 +403,445 @@ async function httpTunnel(localPort) {
262
403
  }
263
404
 
264
405
  logger.info("cli.http.control_plane.establish", {});
265
- process.stdout.write(`⏳ Establishing control-plane connection…\n`);
406
+ // QPA-CLI-11: Vault UX messaging - Negotiating control-plane security
407
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
266
408
 
267
409
  // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
268
410
  const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
269
411
 
270
- // 2) Build transport + core
271
- const t = new AwsIotTransport(logger);
272
- const core = new MqttCore(t, { canPublish: () => true, canSubscribe: () => true });
412
+ // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
413
+ // WebSocket endpoints ignore client certificates, so we must use TLS
414
+ const port = 443;
415
+ const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
416
+
417
+ // Load certificates for MQTT TLS options
418
+ const ca = readFileSync(cfg.caPath);
419
+ const cert = readFileSync(cfg.certPath);
420
+ const key = readFileSync(cfg.keyPath);
421
+
422
+ // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
423
+ const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
424
+
425
+ // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
426
+ const baseClientId = cfg.clientId;
427
+
428
+ // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
429
+ const tunnelInstanceRef = { tunnel: null };
430
+
431
+ // QPA-CLI-05: Store coordinator references for onRefreshLease callback
432
+ // These will be set after core and ingress are created
433
+ let coordinatorCoreRef = null;
434
+ let coordinatorIngressRef = null;
435
+ let deviceIdRef = cfg.clientId;
436
+ let localPortRef = localPort;
437
+ let secGroupSlugRef = secGroupSlug;
438
+ // Track subscription state to ensure refresh requests wait for subscription to be active
439
+ let subscriptionReadyRef = { ready: false };
440
+
441
+ // 2) Build MqttControlPlaneClient for connection management
442
+ // Use mqtts (TLS) protocol with client certificates for AWS IoT authentication
443
+ const mqttClient = new MqttControlPlaneClient({
444
+ url: mqttUrl,
445
+ baseClientId,
446
+ mqttOptions: {
447
+ protocol: 'mqtts',
448
+ port: 443,
449
+ cert,
450
+ key,
451
+ ca,
452
+ rejectUnauthorized: true,
453
+ keepalive,
454
+ connectTimeout: 8000,
455
+ // ALPN for port 443 (AWS IoT)
456
+ ALPNProtocols: ['x-amzn-mqtt-ca'],
457
+ },
458
+ mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
459
+ logger,
460
+ onConnected: async (mqttClientInstance) => {
461
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
462
+ logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
463
+ // QPA-CLI-11: Vault UX messaging - Control-plane sealed
464
+ process.stdout.write("✅ Control-plane sealed\n");
465
+
466
+ // Resubscribe to topics on reconnect (MqttControlPlaneClient manages subscriptions)
467
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
468
+ subscriptionReadyRef.ready = false;
469
+ try {
470
+ await mqttClient.subscribe(evtWildcard, 0);
471
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
472
+ logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
473
+ // Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
474
+ // This prevents race conditions where refresh requests are published before subscription is active
475
+ subscriptionReadyRef.ready = true;
476
+ } catch (e) {
477
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
478
+ logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
479
+ // Mark ready even on failure to avoid blocking forever
480
+ subscriptionReadyRef.ready = true;
481
+ }
482
+
483
+ // QPA-CLI-05: Auto-resume is now handled by MqttControlPlaneClient's refresh buffering
484
+ // The onRefreshLease callback will be called automatically when MQTT reconnects if refreshPending is true
485
+ },
486
+ onOffline: (reason) => {
487
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
488
+ logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
489
+ process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
490
+ // Clear subscription ready flag on disconnect so we wait for resubscription on reconnect
491
+ subscriptionReadyRef.ready = false;
492
+ },
493
+ onFatalError: (reason, err) => {
494
+ logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
495
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
496
+ process.exit(1);
497
+ },
498
+ // QPA-CLI-05: Wire onRefreshLease to handle JWT refresh via coordinator
499
+ onRefreshLease: async () => {
500
+ if (!coordinatorCoreRef || !coordinatorIngressRef) {
501
+ throw new Error("Coordinator not available for refresh");
502
+ }
503
+
504
+ const { getAssignment } = await import('../state/assignment.js');
505
+ const { getFpHash } = await import('../lib/fingerprint.js');
506
+
507
+ // Get current assignment to reuse lease
508
+ const currentAssignment = getAssignment();
509
+ if (!currentAssignment) {
510
+ throw new Error("No current assignment for refresh");
511
+ }
512
+
513
+ const leaseId = currentAssignment.leaseId;
514
+ if (!leaseId) {
515
+ throw new Error("No leaseId in current assignment");
516
+ }
517
+
518
+ // Build refresh payload
519
+ const refreshRequestId = `refresh-${Date.now()}`;
520
+ const fingerprint = await getFpHash(deviceIdRef);
521
+
522
+ const refreshPayload = {
523
+ requestId: refreshRequestId,
524
+ refreshOf: leaseId,
525
+ proto: 'http',
526
+ localPort: localPortRef,
527
+ clientId: deviceIdRef,
528
+ ...fingerprint
529
+ };
530
+
531
+ // QPA-04: Include secGroupSlug in refresh payload if provided
532
+ if (secGroupSlugRef) {
533
+ refreshPayload.secGroupSlug = secGroupSlugRef;
534
+ }
535
+
536
+ // Cancel any existing awaiters for this leaseId before starting a new refresh
537
+ // This prevents duplicate awaiters from accumulating when multiple refresh attempts happen
538
+ const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
539
+ const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
540
+ // Test if this awaiter matches open_ack messages (likely a stale refresh awaiter)
541
+ try {
542
+ const testMessage = {
543
+ topic: ackTopic,
544
+ payload: { type: 'open_ack', requestId: 'test' }
545
+ };
546
+ // If the criteria matches open_ack messages, it's likely a refresh awaiter
547
+ const matches = awaiter.criteria(testMessage);
548
+ // Only cancel if it matches open_ack (we don't want to cancel other awaiters)
549
+ return matches;
550
+ } catch {
551
+ return false;
552
+ }
553
+ });
554
+
555
+ if (cancelled > 0) {
556
+ logger.debug('jwt.refresh.awaiter.cancelled_stale', {
557
+ refreshRequestId,
558
+ cancelledCount: cancelled,
559
+ reason: 'new_refresh_starting'
560
+ });
561
+ }
562
+
563
+ // Wait for subscription to be ready before publishing (prevents race where ack is published before subscription is active)
564
+ // Only wait if subscription is not ready (e.g., after reconnect before resubscription completes)
565
+ if (!subscriptionReadyRef.ready) {
566
+ logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
567
+ // Wait up to 2 seconds for subscription to be ready (should be immediate after subscribe() resolves)
568
+ const maxWait = 2000;
569
+ const startWait = Date.now();
570
+ while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
571
+ await new Promise(resolve => setTimeout(resolve, 50));
572
+ }
573
+ if (!subscriptionReadyRef.ready) {
574
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
575
+ logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
576
+ } else {
577
+ logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
578
+ }
579
+ }
580
+
581
+ // Set up topic and wait for ack
582
+ const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
583
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
584
+
585
+ // Log awaiter registration for debugging
586
+ logger.debug('jwt.refresh.awaiter.registered', {
587
+ refreshRequestId,
588
+ timeoutMs: ACK_TIMEOUT_MS,
589
+ expectedType: 'open_ack'
590
+ });
591
+
592
+ const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
593
+ try {
594
+ const parsed = message.payload;
595
+ const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
596
+
597
+ // Log matching attempts for debugging
598
+ if (parsed?.type === 'open_ack') {
599
+ logger.debug('jwt.refresh.awaiter.checking', {
600
+ refreshRequestId,
601
+ receivedRequestId: parsed.requestId,
602
+ receivedType: parsed.type,
603
+ isMatch,
604
+ topic: message.topic
605
+ });
606
+ }
607
+
608
+ return isMatch;
609
+ } catch (e) {
610
+ logger.debug('jwt.refresh.awaiter.criteria_error', {
611
+ refreshRequestId,
612
+ error: e.message
613
+ });
614
+ return false;
615
+ }
616
+ }, ACK_TIMEOUT_MS);
617
+
618
+ // Publish refresh request
619
+ // QPA-CLI-09: Catch ECONNRESET during publish to prevent fatal exit
620
+ const publishSuccess = await publishRefreshRequestWithErrorHandling(
621
+ coordinatorCoreRef,
622
+ cmdOpenTopic,
623
+ refreshPayload,
624
+ refreshRequestId,
625
+ logger
626
+ );
627
+
628
+ // If publish returned false, ECONNRESET was caught and buffered
629
+ // Throw an error that MqttControlPlaneClient recognizes as offline error
630
+ // This ensures refreshPending stays true and re-arm logic knows refresh is needed
631
+ // The error will be caught by MqttControlPlaneClient and buffered (not bubbled up)
632
+ if (publishSuccess === false) {
633
+ const bufferedError = new Error('Connection closed during refresh publish');
634
+ bufferedError.code = 'ECONNRESET';
635
+ throw bufferedError;
636
+ }
637
+
638
+ // Wait for ack with reconnect retry on timeout
639
+ let ackResult;
640
+ try {
641
+ ackResult = await ackPromise;
642
+ } catch (timeoutError) {
643
+ // QPA-CLI-07: On timeout, reconnect control-plane and retry once
644
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
645
+ logger.debug('jwt.refresh.timeout', {
646
+ error: timeoutError.message,
647
+ action: 'reconnect_and_retry',
648
+ requestId: refreshRequestId
649
+ });
650
+
651
+ // Cancel any existing awaiters for this requestId before retrying
652
+ // This prevents duplicate awaiters from accumulating when retrying
653
+ const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
654
+ // Test if this awaiter matches the same requestId
655
+ try {
656
+ // Create a test message to see if the awaiter's criteria would match
657
+ // We can't directly inspect the criteria, so we test it with a mock message
658
+ const testMessage = {
659
+ topic: `asyx/tunnel/clients/${deviceIdRef}/evt/ack`,
660
+ payload: { type: 'open_ack', requestId: refreshRequestId }
661
+ };
662
+ return awaiter.criteria(testMessage);
663
+ } catch {
664
+ return false;
665
+ }
666
+ });
667
+
668
+ if (cancelled > 0) {
669
+ logger.debug('jwt.refresh.awaiter.cancelled_duplicates', {
670
+ refreshRequestId,
671
+ cancelledCount: cancelled
672
+ });
673
+ }
674
+
675
+ // Force reconnect to get fresh MQTT session
676
+ await mqttClient.forceReconnect('ack_timeout');
677
+
678
+ // Re-register awaiter with same timeout after reconnect; ack might already be queued
679
+ logger.debug('jwt.refresh.awaiter.retry_registered', {
680
+ refreshRequestId,
681
+ timeoutMs: ACK_TIMEOUT_MS
682
+ });
683
+
684
+ const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
685
+ try {
686
+ const parsed = message.payload;
687
+ const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
688
+
689
+ // Log matching attempts for debugging
690
+ if (parsed?.type === 'open_ack') {
691
+ logger.debug('jwt.refresh.awaiter.retry_checking', {
692
+ refreshRequestId,
693
+ receivedRequestId: parsed.requestId,
694
+ receivedType: parsed.type,
695
+ isMatch,
696
+ topic: message.topic
697
+ });
698
+ }
699
+
700
+ return isMatch;
701
+ } catch (e) {
702
+ logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
703
+ refreshRequestId,
704
+ error: e.message
705
+ });
706
+ return false;
707
+ }
708
+ }, ACK_TIMEOUT_MS);
709
+
710
+ try {
711
+ ackResult = await retryAckPromise;
712
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
713
+ logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
714
+ } catch (retryError) {
715
+ logger.error('jwt.refresh.timeout', {
716
+ error: retryError.message,
717
+ action: 'give_up',
718
+ requestId: refreshRequestId
719
+ });
720
+ throw new Error(`Refresh timeout after reconnect: ${retryError.message}`);
721
+ }
722
+ }
723
+
724
+ // Get new assignment
725
+ const newAssignment = getAssignment();
726
+ if (!newAssignment) {
727
+ throw new Error("No new assignment after refresh");
728
+ }
729
+
730
+ // Extract expiration from new JWT
731
+ const newJwt = newAssignment.jwt;
732
+ const parts = newJwt.split('.');
733
+ if (parts.length !== 3) {
734
+ throw new Error("Invalid JWT format in new assignment");
735
+ }
736
+
737
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
738
+ const expMs = payload.exp ? payload.exp * 1000 : null;
739
+
740
+ if (!expMs) {
741
+ throw new Error("No expiration in new JWT");
742
+ }
743
+
744
+ // QPA-CLI-05: Notify HttpTunnel that new JWT is available
745
+ // HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
746
+ if (tunnelInstanceRef.tunnel) {
747
+ // Update HttpTunnel with new JWT and assignment
748
+ tunnelInstanceRef.tunnel.jwt = newJwt;
749
+ tunnelInstanceRef.tunnel.requestId = newAssignment.requestId;
750
+ tunnelInstanceRef.tunnel.relayUrl = newAssignment.relayUrl;
751
+ tunnelInstanceRef.tunnel.headers = {
752
+ 'Authorization': `Bearer ${newJwt}`,
753
+ 'X-Asyx-DeviceId': deviceIdRef,
754
+ 'X-Asyx-RequestId': newAssignment.requestId
755
+ };
756
+
757
+ // Update jwtMeta for HttpTunnel
758
+ tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
759
+
760
+ // Record refresh timestamp and delta metrics
761
+ const { recordRefresh } = await import('../state/assignment.js');
762
+ const deltaMs = recordRefresh(Date.now());
763
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
764
+ logger.debug('jwt.refresh.delta', { deltaMs });
765
+
766
+ // Try in-band reauth if WebSocket is open
767
+ if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
768
+ const prevJti = tunnelInstanceRef.tunnel.jwtMeta?.token
769
+ ? tunnelInstanceRef.tunnel._extractJti(tunnelInstanceRef.tunnel.jwtMeta.token)
770
+ : null;
771
+ try {
772
+ const reauthSuccess = await tunnelInstanceRef.tunnel.reauthInBand(newJwt, prevJti, 'timer');
773
+ if (reauthSuccess) {
774
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
775
+ logger.debug('jwt.refresh.success', { method: 'in_band', leaseId: newAssignment.leaseId });
776
+ return expMs;
777
+ }
778
+ } catch (reauthError) {
779
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
780
+ logger.debug('jwt.reauth.exception', { error: reauthError.message });
781
+ }
782
+ }
783
+
784
+ // Fallback to reconnect
785
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
786
+ logger.debug('jwt.refresh.reconnect', { leaseId: newAssignment.leaseId });
787
+ await tunnelInstanceRef.tunnel._attemptConnect();
788
+ }
789
+
790
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
791
+ logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
792
+ return expMs;
793
+ },
794
+ });
273
795
 
274
- // CLI-IMG-ControlPlane-Watchdog: Expose helpers from transport
796
+ // Create Transport adapter and MqttCore
797
+ const transport = new MqttControlPlaneTransport(mqttClient);
798
+ const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
799
+
800
+ // CLI-IMG-ControlPlane-Watchdog: Expose helpers for HttpTunnel compatibility
275
801
  const isControlPlaneConnected = () => {
276
- try {
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
- }
802
+ return mqttClient.isOnline();
284
803
  };
804
+
285
805
  const waitForControlPlane = () => {
286
- try {
287
- if (t && typeof t.waitForConnect === 'function') return t.waitForConnect(CONTROL_PLANE_TIMEOUT_MS);
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);
806
+ if (mqttClient.isOnline()) {
807
+ return Promise.resolve();
306
808
  }
809
+ // Poll until connected or timeout
810
+ const start = Date.now();
811
+ return new Promise((resolve, reject) => {
812
+ const interval = setInterval(() => {
813
+ if (mqttClient.isOnline()) {
814
+ clearInterval(interval);
815
+ resolve();
816
+ } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
817
+ clearInterval(interval);
818
+ reject(new Error('control_plane_timeout'));
819
+ }
820
+ }, 250);
821
+ });
307
822
  };
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
823
 
318
- t.onDisconnect((err) => {
319
- const msg = err ? err.message || err : "closed";
320
- logger.warn("mqtt.control_plane.disconnected", { reason: msg });
321
- process.stderr.write(`[mqtt] Control-plane connection lost: ${msg}\n`);
322
- });
323
-
324
- // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
325
- const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
326
- const reconnectMin = parseInt(process.env.ASYX_CONTROL_PLANE_RECONNECT_MIN_MS || "1000", 10);
327
- const reconnectMax = parseInt(process.env.ASYX_CONTROL_PLANE_RECONNECT_MAX_MS || "30000", 10);
328
- const cleanSession = process.env.ASYX_CONTROL_PLANE_CLEAN === "true";
824
+ // QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
825
+ // Note: MqttControlPlaneClient doesn't expose this yet - can be added if needed
826
+ const getLastMqttError = () => {
827
+ // TODO: Add getLastMqttError to MqttControlPlaneClient if needed
828
+ return null;
829
+ };
830
+
831
+ // QPA-CLI-03: Expose helper to force reconnect
832
+ const getForceReconnect = () => {
833
+ // MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
834
+ return async () => {
835
+ if (!mqttClient.isOnline()) {
836
+ await mqttClient.disconnect();
837
+ await mqttClient.connect();
838
+ }
839
+ };
840
+ };
329
841
 
330
842
  // 3) Connect to control plane
331
843
  try {
332
- await core.connect({
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
844
+ await mqttClient.connect();
341
845
  } catch (e) {
342
846
  logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
343
847
  process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
@@ -345,24 +849,30 @@ async function httpTunnel(localPort) {
345
849
  }
346
850
 
347
851
  // 4) Set up topics and message handling
348
- const evtWildcard = `asyx/tunnel/clients/${cfg.clientId}/evt/#`;
349
- const cmdOpenTopic = `asyx/tunnel/clients/${cfg.clientId}/cmd/open`;
350
- const acknowledgmentTopic = `asyx/tunnel/clients/${cfg.clientId}/evt/ack`;
852
+ // CLI-MQTT-UniqueID-CleanSession: Use baseClientId for topics (not session client ID) to maintain topic stability
853
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
854
+ const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
855
+ const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
351
856
 
352
- // CLI-IMG-MQTT-Parity: Only subscribe on first connect for persistent sessions
353
- if (isFirstConnect) {
354
- await core.subscribe(evtWildcard, 0);
355
- isFirstConnect = false;
356
- }
857
+ // Subscribe to topics after initial connect
858
+ // Note: MqttControlPlaneClient.onConnected callback will handle resubscription on reconnect
859
+ await core.subscribe(evtWildcard, 0);
860
+ // Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
861
+ subscriptionReadyRef.ready = true;
357
862
 
358
863
  // 5) Set up message ingress and dispatcher
359
864
  const ingress = new MessageIngress({
360
865
  maxAwaiters: 100,
361
- observability: process.env.ASYX_DEBUG === '1'
866
+ observability: process.env.ASYX_DEBUG === '1',
867
+ logger // QPA-CLI-10: Pass logger for quiet mode
362
868
  });
363
869
 
364
870
  ingress.setDispatcher(dispatchEvt);
365
871
 
872
+ // QPA-CLI-05: Store coordinator references for onRefreshLease callback
873
+ coordinatorCoreRef = core;
874
+ coordinatorIngressRef = ingress;
875
+
366
876
  core.onMessage(async (m) => {
367
877
  try {
368
878
  await ingress.handleMessage(m);
@@ -395,6 +905,11 @@ async function httpTunnel(localPort) {
395
905
  clientId: cfg.clientId,
396
906
  ...fingerprint
397
907
  };
908
+
909
+ // QPA-04: Include secGroupSlug in cmd/open payload if provided
910
+ if (secGroupSlug) {
911
+ openPayload.secGroupSlug = secGroupSlug;
912
+ }
398
913
 
399
914
  // Publish the open request
400
915
  await core.publish({
@@ -407,7 +922,7 @@ async function httpTunnel(localPort) {
407
922
  logger.info("cli.cmd.open.sent", { requestId });
408
923
 
409
924
  // 7) Wait for ack and then connect to relay
410
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "10000", 10);
925
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
411
926
 
412
927
  try {
413
928
  const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
@@ -422,13 +937,17 @@ async function httpTunnel(localPort) {
422
937
  } catch {}
423
938
 
424
939
  // 8) Connect to relay using thin client behavior
940
+ // QPA-CLI-05: Pass mqttClient for refresh scheduling
425
941
  await connectToRelay(
426
942
  assignment,
427
943
  cfg.clientId,
428
944
  localPort,
429
945
  core,
430
946
  ingress,
431
- { isControlPlaneConnected, waitForControlPlane, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS }
947
+ { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
948
+ secGroupSlug,
949
+ tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here before infinite promise
950
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
432
951
  );
433
952
 
434
953
  } catch (error) {
@@ -444,7 +963,10 @@ async function connectToRelay(
444
963
  localPort,
445
964
  coordinatorCore,
446
965
  coordinatorIngress,
447
- controlPlaneHelpers
966
+ controlPlaneHelpers,
967
+ secGroupSlug,
968
+ tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
969
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
448
970
  ) {
449
971
  // Import WebSocket bridge logic (ported from client-mvp)
450
972
  const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
@@ -460,7 +982,11 @@ async function connectToRelay(
460
982
  // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
461
983
  isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
462
984
  waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
985
+ getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
986
+ getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
463
987
  controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
988
+ // QPA-04: Pass secGroupSlug to HttpTunnel
989
+ secGroupSlug,
464
990
  log: {
465
991
  info: (msgOrFields, maybeFields) => {
466
992
  if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
@@ -481,19 +1007,43 @@ async function connectToRelay(
481
1007
  }
482
1008
  });
483
1009
 
1010
+ // QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
1011
+ if (tunnelInstanceRef) {
1012
+ tunnelInstanceRef.tunnel = tunnel;
1013
+ }
1014
+
484
1015
  try {
485
1016
  await tunnel.open();
486
1017
 
487
- // CLI-RES-DPJWT-LEAD: Schedule initial proactive refresh
488
- tunnel.scheduleRefresh(assignment.jwt, 'open_ack');
1018
+ // QPA-CLI-05: Schedule initial proactive refresh via MqttControlPlaneClient
1019
+ // TCP-S4: Skip refresh scheduling for TCP tunnels (refresh not implemented yet)
1020
+ // HTTP tunnels continue to schedule refresh as before
1021
+ // Note: This is a temporary limitation until TCP refresh is implemented
489
1022
 
1023
+ // QPA-CLI-11: Vault UX messaging - Final tunnel live message
1024
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
490
1025
  logger.info("tunnel.active", { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
491
- process.stdout.write(`🌐 HTTP tunnel active on http://localhost:${localPort}\n`);
492
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
493
- process.stdout.write(` Lease: ${assignment.leaseMs}ms\n`);
1026
+
1027
+ // Show QuickPass secured message if QuickPass was requested and enabled
1028
+ if (secGroupSlug && assignment.quickpassSlug) {
1029
+ process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
1030
+ }
1031
+
1032
+ // Tunnel live message
1033
+ process.stdout.write(`🌐 Tunnel live at http://localhost:${localPort}\n`);
1034
+
1035
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
1036
+ // Most users don't need to know the lease term; they just care the tunnel stays alive
1037
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
1038
+ if (logLevel === 'info' || logLevel === 'debug') {
1039
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
1040
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
1041
+ }
1042
+
494
1043
  process.stdout.write(` Press Ctrl+C to stop\n`);
495
1044
 
496
1045
  // CLI-IMG-WSReconnect: Set up graceful shutdown
1046
+ // QPA-CLI-05: Also disconnect MqttControlPlaneClient on shutdown
497
1047
  let shuttingDown = false;
498
1048
  const onSig = async (sig) => {
499
1049
  if (shuttingDown) return;
@@ -511,6 +1061,13 @@ async function connectToRelay(
511
1061
  logger.error('tunnel.close.error', { error: e.message });
512
1062
  process.stderr.write(`Error closing tunnel: ${e.message}\n`);
513
1063
  }
1064
+ // QPA-CLI-05: Disconnect MqttControlPlaneClient to clear timers
1065
+ try {
1066
+ await mqttClient.disconnect();
1067
+ } catch (e) {
1068
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1069
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
1070
+ }
514
1071
  clearTimeout(killer);
515
1072
  process.exit(0);
516
1073
  };
@@ -520,7 +1077,8 @@ async function connectToRelay(
520
1077
  // CLI-REFRESH-SIGNAL: External trigger to force JWT refresh (avoids SIGUSR1 inspector conflict)
521
1078
  try {
522
1079
  process.once('SIGUSR2', () => {
523
- logger.warn('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
1080
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1081
+ logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
524
1082
  try { tunnel.attemptJwtRefresh(); } catch (e) {
525
1083
  logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
526
1084
  }
@@ -537,4 +1095,515 @@ async function connectToRelay(
537
1095
  }
538
1096
  }
539
1097
 
1098
+ /**
1099
+ * Build TCP target string from port.
1100
+ * Defaults to 127.0.0.1 (localhost-only in v4.1).
1101
+ * @param {number} port - Port number
1102
+ * @returns {string} Target string in format "127.0.0.1:port"
1103
+ */
1104
+ function buildTcpTarget(port) {
1105
+ return `127.0.0.1:${port}`;
1106
+ }
1107
+
1108
+ /**
1109
+ * Validate that target is localhost-only (127.0.0.1, ::1, or localhost).
1110
+ * @param {string} target - Target string in format "host:port"
1111
+ * @returns {boolean} True if target is localhost-only
1112
+ */
1113
+ function isLocalhostTarget(target) {
1114
+ // Extract host part (before the colon)
1115
+ const host = target.split(':')[0];
1116
+
1117
+ // Normalize hostname to lowercase for comparison
1118
+ const normalizedHost = host.toLowerCase();
1119
+
1120
+ // Allowed localhost values
1121
+ const allowedHosts = ['127.0.0.1', '::1', 'localhost'];
1122
+
1123
+ return allowedHosts.includes(normalizedHost);
1124
+ }
1125
+
1126
+ /**
1127
+ * TCP tunnel implementation (TCP-S2: cmd/open Payload + Compatibility).
1128
+ * Builds and sends MQTT cmd/open payload with protocol:"tcp" and target.
1129
+ * Reuses existing MQTT control-plane infrastructure.
1130
+ * @param {number} localPort - Local port number
1131
+ * @param {string} [serviceName] - Optional service name
1132
+ */
1133
+ async function tcpTunnel(localPort, serviceName, kind = null) {
1134
+ logger.info('cli.tcp.start', { localPort, serviceName });
1135
+ process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1136
+
1137
+ // TCP-S1: Validation complete, target constructed
1138
+ const target = buildTcpTarget(localPort);
1139
+ logger.info('cli.tcp.target', { target });
1140
+
1141
+ // 0) Imports (kept local to this command to avoid global side-effects)
1142
+ const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
1143
+ const { MqttCore } = await import("@asyx/mqtt-core");
1144
+ const { waitForAssignment } = await import("../state/assignment.js");
1145
+ const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
1146
+ const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
1147
+ const { readFileSync } = await import("node:fs");
1148
+
1149
+ // 1) Load IoT config (throws with clear messages if misconfigured)
1150
+ let cfg;
1151
+ try {
1152
+ cfg = loadAwsIotConfig();
1153
+ } catch (e) {
1154
+ logger.error("config.error", { error: e?.message || String(e) });
1155
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
1156
+ process.exit(1);
1157
+ }
1158
+
1159
+ logger.info("cli.tcp.control_plane.establish", {});
1160
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
1161
+
1162
+ // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
1163
+ const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
1164
+
1165
+ // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
1166
+ const port = 443;
1167
+ const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
1168
+
1169
+ // Load certificates for MQTT TLS options
1170
+ const ca = readFileSync(cfg.caPath);
1171
+ const cert = readFileSync(cfg.certPath);
1172
+ const key = readFileSync(cfg.keyPath);
1173
+
1174
+ // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
1175
+ const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
1176
+
1177
+ // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
1178
+ const baseClientId = cfg.clientId;
1179
+
1180
+ // 2) Build MqttControlPlaneClient for connection management
1181
+ const mqttClient = new MqttControlPlaneClient({
1182
+ url: mqttUrl,
1183
+ baseClientId,
1184
+ mqttOptions: {
1185
+ protocol: 'mqtts',
1186
+ port: 443,
1187
+ cert,
1188
+ key,
1189
+ ca,
1190
+ rejectUnauthorized: true,
1191
+ keepalive,
1192
+ connectTimeout: 8000,
1193
+ // ALPN for port 443 (AWS IoT)
1194
+ ALPNProtocols: ['x-amzn-mqtt-ca'],
1195
+ },
1196
+ mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
1197
+ logger,
1198
+ onConnected: async (mqttClientInstance) => {
1199
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1200
+ logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
1201
+ process.stdout.write("✅ Control-plane sealed\n");
1202
+
1203
+ // Resubscribe to topics on reconnect
1204
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1205
+ try {
1206
+ await mqttClient.subscribe(evtWildcard, 0);
1207
+ logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
1208
+ } catch (e) {
1209
+ logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
1210
+ }
1211
+ },
1212
+ onOffline: (reason) => {
1213
+ logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
1214
+ process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
1215
+ },
1216
+ onFatalError: (reason, err) => {
1217
+ logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
1218
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
1219
+ process.exit(1);
1220
+ },
1221
+ // TCP-S2: Refresh lease callback (similar to HTTP, but with TCP protocol)
1222
+ // TCP-S4: Make refresh non-fatal - disable refresh scheduling for TCP until implemented
1223
+ onRefreshLease: async () => {
1224
+ // TCP refresh not yet implemented - log and skip (non-fatal)
1225
+ logger.warn('tcp.refresh.not_implemented', {
1226
+ note: 'TCP refresh is not yet implemented; lease will expire naturally'
1227
+ });
1228
+ // Return without throwing to prevent fatal errors
1229
+ return;
1230
+ },
1231
+ });
1232
+
1233
+ // Create Transport adapter and MqttCore
1234
+ const transport = new MqttControlPlaneTransport(mqttClient);
1235
+ const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
1236
+
1237
+ // CLI-IMG-ControlPlane-Watchdog: Expose helpers for TcpTunnel compatibility
1238
+ const isControlPlaneConnected = () => {
1239
+ return mqttClient.isOnline();
1240
+ };
1241
+
1242
+ const waitForControlPlane = () => {
1243
+ if (mqttClient.isOnline()) {
1244
+ return Promise.resolve();
1245
+ }
1246
+ // Poll until connected or timeout
1247
+ const start = Date.now();
1248
+ return new Promise((resolve, reject) => {
1249
+ const interval = setInterval(() => {
1250
+ if (mqttClient.isOnline()) {
1251
+ clearInterval(interval);
1252
+ resolve();
1253
+ } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
1254
+ clearInterval(interval);
1255
+ reject(new Error('control_plane_timeout'));
1256
+ }
1257
+ }, 250);
1258
+ });
1259
+ };
1260
+
1261
+ // QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
1262
+ const getLastMqttError = () => {
1263
+ // TODO: Add getLastMqttError to MqttControlPlaneClient if needed
1264
+ return null;
1265
+ };
1266
+
1267
+ // QPA-CLI-03: Expose helper to force reconnect
1268
+ const getForceReconnect = () => {
1269
+ // MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
1270
+ return async () => {
1271
+ if (!mqttClient.isOnline()) {
1272
+ await mqttClient.disconnect();
1273
+ await mqttClient.connect();
1274
+ }
1275
+ };
1276
+ };
1277
+
1278
+ // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
1279
+ const tunnelInstanceRef = { tunnel: null };
1280
+
1281
+ // 3) Connect to control plane
1282
+ try {
1283
+ await mqttClient.connect();
1284
+ } catch (e) {
1285
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
1286
+ process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
1287
+ process.exit(1);
1288
+ }
1289
+
1290
+ // 4) Set up topics and message handling
1291
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1292
+ const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
1293
+ const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
1294
+
1295
+ // Subscribe to topics after initial connect
1296
+ await core.subscribe(evtWildcard, 0);
1297
+
1298
+ // 5) Set up message ingress and dispatcher
1299
+ const ingress = new MessageIngress({
1300
+ maxAwaiters: 100,
1301
+ observability: process.env.ASYX_DEBUG === '1',
1302
+ logger
1303
+ });
1304
+
1305
+ ingress.setDispatcher(dispatchEvt);
1306
+
1307
+ core.onMessage(async (m) => {
1308
+ try {
1309
+ await ingress.handleMessage(m);
1310
+ } catch (e) {
1311
+ if (e && e.code === "SETUP_REQUIRED") {
1312
+ process.stderr.write(`❌ ${e.message}\n`);
1313
+ try { await core.end(); } catch {}
1314
+ process.exit(2);
1315
+ }
1316
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
1317
+ process.stderr.write(`❌ ${e.message}\n`);
1318
+ try { await core.end(); } catch {}
1319
+ process.exit(1);
1320
+ }
1321
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
1322
+ try { await core.end(); } catch {}
1323
+ process.exit(1);
1324
+ }
1325
+ });
1326
+
1327
+ // 6) Publish cmd/open request with TCP protocol
1328
+ const requestId = crypto.randomUUID();
1329
+ const { getFpHash } = await import("../lib/fingerprint.js");
1330
+ const fingerprint = await getFpHash(cfg.clientId);
1331
+
1332
+ // TCP-S2: Build TCP cmd/open payload
1333
+ // E3-S8: Include kind field if provided
1334
+ const openPayload = {
1335
+ requestId,
1336
+ proto: 'tcp', // Protocol identifier
1337
+ target: target, // "127.0.0.1:<port>" from TCP-S1
1338
+ clientId: cfg.clientId,
1339
+ ...fingerprint
1340
+ };
1341
+
1342
+ // TCP-S2: Include optional opts.name if service name provided
1343
+ // E3-S8: Include opts.kind if provided
1344
+ openPayload.opts = {
1345
+ preferredPort: null // Can be wired to a flag later if needed
1346
+ };
1347
+
1348
+ if (serviceName) {
1349
+ openPayload.opts.name = serviceName;
1350
+ }
1351
+
1352
+ if (kind) {
1353
+ openPayload.opts.kind = kind;
1354
+ }
1355
+
1356
+ // Publish the open request
1357
+ await core.publish({
1358
+ topic: cmdOpenTopic,
1359
+ payload: JSON.stringify(openPayload),
1360
+ qos: 1,
1361
+ retain: false
1362
+ });
1363
+
1364
+ logger.info("cli.cmd.open.sent", { requestId, protocol: 'tcp', target });
1365
+
1366
+ // 7) Wait for ack and assignment
1367
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
1368
+
1369
+ try {
1370
+ const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
1371
+ logger.info("cli.ack.wait.start", { requestId });
1372
+ const assignment = await assignmentPromise;
1373
+ logger.info("cli.ack.wait.resolved", { requestId });
1374
+ logger.info("cli.assignment.received", {
1375
+ relayId: assignment.relayId,
1376
+ leaseId: assignment.leaseId,
1377
+ tcpAliasFqdn: assignment.tcpAliasFqdn,
1378
+ publicPort: assignment.publicPort
1379
+ });
1380
+
1381
+ // Persist assignment for refresh/fallback paths
1382
+ try {
1383
+ const { setAssignment } = await import("../state/assignment.js");
1384
+ setAssignment(assignment);
1385
+ } catch {}
1386
+
1387
+ // TCP-S3: Handle warnings array (alias unavailable)
1388
+ const warnings = assignment.warnings || [];
1389
+ if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
1390
+ logger.warn('tcp.alias.unavailable', {
1391
+ requestId,
1392
+ fqdn: assignment.fqdn,
1393
+ publicPort: assignment.publicPort
1394
+ });
1395
+ }
1396
+
1397
+ // TCP-S3: Build and display UX based on alias and SRV presence
1398
+ // E3-S8: Check for SRV status for Minecraft tunnels
1399
+ const tcpAliasFqdn = assignment.tcpAliasFqdn;
1400
+ const srvProvisioned = assignment.srvProvisioned === true;
1401
+ const srvFqdn = assignment.srvFqdn || null;
1402
+ const fqdn = assignment.fqdn;
1403
+ const publicPort = assignment.publicPort;
1404
+ const aliasRequestedButFailed = warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE');
1405
+
1406
+ if (tcpAliasFqdn) {
1407
+ // Alias present: show both alias and host:port
1408
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1409
+ process.stdout.write(` ${tcpAliasFqdn}\n`);
1410
+ process.stdout.write(` or\n`);
1411
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1412
+ // E3-S8: Show SRV info if available
1413
+ if (srvProvisioned && srvFqdn) {
1414
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
1415
+ }
1416
+ } else if (srvProvisioned && srvFqdn) {
1417
+ // E3-S8: SRV available but no alias (Minecraft without --name)
1418
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1419
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1420
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
1421
+ } else if (aliasRequestedButFailed) {
1422
+ // User requested alias (--name) but provisioning failed
1423
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1424
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1425
+ process.stdout.write(` (alias unavailable; using host:port only)\n`);
1426
+ } else {
1427
+ // No alias requested, no SRV: just show host:port (normal case for plain --tcp)
1428
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1429
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1430
+ }
1431
+
1432
+ // TCP-S3: Log alias readiness if previously null alias becomes non-null
1433
+ // (This would require tracking previous assignment state, but for now we just log current state)
1434
+ if (tcpAliasFqdn) {
1435
+ logger.debug('tcp.alias.ready', {
1436
+ requestId,
1437
+ tcpAliasFqdn,
1438
+ fqdn,
1439
+ publicPort
1440
+ });
1441
+ }
1442
+
1443
+ // TCP-S4: Connect to relay using TcpTunnel for data-plane readiness
1444
+ await connectToRelayTcp(
1445
+ assignment,
1446
+ cfg.clientId,
1447
+ localPort,
1448
+ core,
1449
+ ingress,
1450
+ { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
1451
+ tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here
1452
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
1453
+ );
1454
+
1455
+ } catch (error) {
1456
+ // TCP-S3: Handle Coordinator error codes distinctly
1457
+ const errorCode = error.code || error.reason || error.data?.reason;
1458
+
1459
+ if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
1460
+ logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
1461
+ process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
1462
+ try { await core.end(); } catch {}
1463
+ process.exit(1);
1464
+ }
1465
+
1466
+ if (errorCode === 'TENANT_TCP_LEASE_LIMIT_REACHED' || errorCode === 'tenant_tcp_lease_limit_reached') {
1467
+ const relayId = error.relayId || error.data?.relayId || 'unknown';
1468
+ logger.error("cli.tcp.error.lease_limit", { error: error.message, relayId });
1469
+ process.stderr.write(`Tenant TCP lease limit reached on relay ${relayId}\n`);
1470
+ try { await core.end(); } catch {}
1471
+ process.exit(1);
1472
+ }
1473
+
1474
+ // TCP_ALIAS_UNAVAILABLE is handled as a warning, not an error
1475
+
1476
+ // Generic error handling
1477
+ logger.error("cli.ack.wait.failed", { error: error.message, errorCode });
1478
+ process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
1479
+ try { await core.end(); } catch {}
1480
+ process.exit(1);
1481
+ }
1482
+ }
1483
+
1484
+ export async function connectToRelayTcp(
1485
+ assignment,
1486
+ deviceId,
1487
+ localPort,
1488
+ coordinatorCore,
1489
+ coordinatorIngress,
1490
+ controlPlaneHelpers,
1491
+ tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
1492
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
1493
+ ) {
1494
+ // Import TCP tunnel logic
1495
+ const { TcpTunnel } = await import("../tunnel/tcp-tunnel.js");
1496
+
1497
+ const tunnel = new TcpTunnel({
1498
+ relayUrl: assignment.relayUrl,
1499
+ jwt: assignment.jwt, // Use JWT as-is (no validation)
1500
+ deviceId,
1501
+ requestId: assignment.requestId,
1502
+ localPort,
1503
+ leaseId: assignment.leaseId, // E3-S3: Pass leaseId for TCP relay WebSocket query parameters
1504
+ coordinatorCore, // CLI-IMG-WSReconnect: Pass coordinator connection for JWT refresh (not used for TCP yet)
1505
+ coordinatorIngress, // CLI-IMG-WSReconnect: Pass coordinator ingress for JWT refresh (not used for TCP yet)
1506
+ // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
1507
+ isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
1508
+ waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
1509
+ getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
1510
+ getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
1511
+ controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
1512
+ log: {
1513
+ info: (msgOrFields, maybeFields) => {
1514
+ if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
1515
+ return logger.info(maybeFields, msgOrFields);
1516
+ },
1517
+ warn: (msgOrFields, maybeFields) => {
1518
+ if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
1519
+ return logger.warn(maybeFields, msgOrFields);
1520
+ },
1521
+ error: (msgOrFields, maybeFields) => {
1522
+ if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
1523
+ return logger.error(maybeFields, msgOrFields);
1524
+ },
1525
+ debug: (msgOrFields, maybeFields) => {
1526
+ if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
1527
+ return logger.debug(maybeFields, msgOrFields);
1528
+ }
1529
+ }
1530
+ });
1531
+
1532
+ // QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
1533
+ if (tunnelInstanceRef) {
1534
+ tunnelInstanceRef.tunnel = tunnel;
1535
+ }
1536
+
1537
+ try {
1538
+ await tunnel.open();
1539
+
1540
+ // TCP-S4: Log tunnel active
1541
+ logger.info("tunnel.active", {
1542
+ target: `tcp://127.0.0.1:${localPort}`,
1543
+ relayId: assignment.relayId,
1544
+ leaseMs: assignment.leaseMs
1545
+ });
1546
+
1547
+ // Tunnel live message
1548
+ process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
1549
+ process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
1550
+
1551
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
1552
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
1553
+ if (logLevel === 'info' || logLevel === 'debug') {
1554
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
1555
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
1556
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
1557
+ }
1558
+
1559
+ process.stdout.write(` Press Ctrl+C to stop\n`);
1560
+
1561
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
1562
+ let shuttingDown = false;
1563
+ const onSig = async (sig) => {
1564
+ if (shuttingDown) return;
1565
+ shuttingDown = true;
1566
+ logger.info("cli.signal.shutdown", { sig });
1567
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
1568
+
1569
+ const killer = setTimeout(() => {
1570
+ logger.error("tunnel.close.timeout", {});
1571
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
1572
+ process.exit(0);
1573
+ }, 3000);
1574
+
1575
+ try {
1576
+ // TCP-S4: Close tunnel and all active streams
1577
+ tunnel.close();
1578
+ await mqttClient.disconnect();
1579
+ } catch (e) {
1580
+ logger.debug('tunnel.shutdown.error', { error: e.message });
1581
+ }
1582
+
1583
+ clearTimeout(killer);
1584
+ process.exit(0);
1585
+ };
1586
+
1587
+ process.once("SIGINT", onSig);
1588
+ process.once("SIGTERM", onSig);
1589
+
1590
+ // Keep process alive until SIGINT/SIGTERM
1591
+ await new Promise(() => {});
1592
+
1593
+ } catch (error) {
1594
+ logger.error("tunnel.open.failed", { error: error.message });
1595
+ try {
1596
+ tunnel.close();
1597
+ } catch (e) {
1598
+ logger.debug('tunnel.close.error', { error: e.message });
1599
+ }
1600
+ try {
1601
+ await mqttClient.disconnect();
1602
+ } catch (e) {
1603
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
1604
+ }
1605
+ process.exit(1);
1606
+ }
1607
+ }
1608
+
540
1609
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }