asyx 0.5.9 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +71 -9
  2. package/SECURITY.md +5 -3
  3. package/package.json +13 -23
  4. package/src/commands/name.js +23 -0
  5. package/src/commands/reject-messages.js +54 -0
  6. package/src/commands/setup.js +98 -102
  7. package/src/commands/tunnel.js +279 -2425
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +9 -1
  10. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
  11. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
  12. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
  13. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
  14. package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
  15. package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
  16. package/vendor/tunnel-core/dist/errors.d.ts +49 -0
  17. package/vendor/tunnel-core/dist/errors.js +53 -0
  18. package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
  19. package/vendor/tunnel-core/dist/flows/http.js +585 -0
  20. package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
  21. package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
  22. package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
  23. package/vendor/tunnel-core/dist/flows/udp.js +376 -0
  24. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
  26. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
  27. package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
  28. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
  29. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
  30. package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
  31. package/vendor/tunnel-core/dist/lib/logger.js +58 -0
  32. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
  33. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
  34. package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
  35. package/vendor/tunnel-core/dist/lifecycle.js +29 -0
  36. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
  37. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
  38. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
  39. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
  40. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
  41. package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
  42. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
  43. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
  44. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
  46. package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
  47. package/vendor/tunnel-core/dist/state/assignment.js +322 -0
  48. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
  49. package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
  50. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
  51. package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
  52. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
  53. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
  54. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
  55. package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
  56. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
  57. package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
  58. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
  59. package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
  60. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
  61. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
  62. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
  63. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
  64. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
  65. package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
  66. package/vendor/tunnel-core/dist/types.d.ts +24 -0
  67. package/vendor/tunnel-core/dist/types.js +2 -0
  68. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
  69. package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
  70. package/vendor/tunnel-core/package.json +34 -0
  71. package/src/control-plane/MqttControlPlaneClient.js +0 -1196
  72. package/src/control-plane/MqttControlPlaneTransport.js +0 -150
  73. package/src/lib/fingerprint.js +0 -115
  74. package/src/lib/jwt-verifier.js +0 -260
  75. package/src/lib/logger.js +0 -62
  76. package/src/mqtt/awaiter-map.js +0 -247
  77. package/src/mqtt/events/handlers.js +0 -300
  78. package/src/mqtt/events/index.js +0 -222
  79. package/src/mqtt/events/schemas.js +0 -58
  80. package/src/mqtt/ingress.js +0 -182
  81. package/src/state/assignment.js +0 -333
  82. package/src/tcp-v1/framing.js +0 -203
  83. package/src/tunnel/http-tunnel.js +0 -1738
  84. package/src/tunnel/reconnect.js +0 -182
  85. package/src/tunnel/tcp-tunnel.js +0 -944
  86. package/src/tunnel/udp-tunnel.js +0 -813
  87. package/src/tunnel/ws-control.js +0 -135
  88. package/src/udp-v1/framing.js +0 -203
@@ -6,75 +6,16 @@ import { constants as fsConstants } from 'node:fs';
6
6
  import { access } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import crypto from "node:crypto";
9
- import logger from "../lib/logger.js";
10
- import { dispatch as dispatchEvt } from "../mqtt/events/index.js";
11
- import { MessageIngress } from "../mqtt/ingress.js";
9
+ import logger from "#tunnel-core/lib/logger.js";
10
+ import { dispatch as dispatchEvt } from "#tunnel-core/mqtt/events/index.js";
11
+ import { MessageIngress } from "#tunnel-core/mqtt/ingress.js";
12
12
  import { getDeviceJsonPath } from "../lib/device.js";
13
+ import './reject-messages.js'; // Story 12.1: the CLI's wording for coordinator refusals
14
+ import { createControlPlaneSession } from '#tunnel-core/control-plane/session.js';
15
+ import { publishRefreshRequestWithErrorHandling, jwtExpOf } from '#tunnel-core/lib/refresh-helpers.js';
16
+ // Re-exported for existing tests that import it from here.
17
+ export { publishRefreshRequestWithErrorHandling };
13
18
 
14
- /**
15
- * QPA-CLI-09: Publish refresh request with ECONNRESET error handling.
16
- * Catches connection reset errors during publish and returns a sentinel value
17
- * instead of throwing, so the CLI doesn't exit with "Unexpected error".
18
- *
19
- * @param {Object} coordinatorCore - MQTT core client with publish method
20
- * @param {string} topic - MQTT topic to publish to
21
- * @param {Object} payload - Refresh payload object (will be JSON stringified)
22
- * @param {string} refreshRequestId - Request ID for logging
23
- * @param {Object} logger - Logger instance
24
- * @returns {Promise<boolean>} Returns true on success, false on ECONNRESET (buffered), throws on other errors
25
- */
26
- export async function publishRefreshRequestWithErrorHandling(
27
- coordinatorCore,
28
- topic,
29
- payload,
30
- refreshRequestId,
31
- logger
32
- ) {
33
- try {
34
- await coordinatorCore.publish({
35
- topic,
36
- payload: JSON.stringify(payload),
37
- qos: 1,
38
- retain: false
39
- });
40
-
41
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
42
- logger.debug('jwt.refresh.request.sent', { refreshRequestId });
43
- return true;
44
- } catch (publishError) {
45
- // Check if this is a connection reset error (transient condition)
46
- const isConnectionError =
47
- publishError?.code === 'ECONNRESET' ||
48
- publishError?.errno === -54 || // macOS/Linux ECONNRESET errno
49
- publishError?.message?.includes('ECONNRESET') ||
50
- publishError?.message?.includes('Connection closed') ||
51
- publishError?.message?.includes('connection closed');
52
-
53
- if (isConnectionError) {
54
- // QPA-CLI-09: Return false instead of throwing - refresh is buffered, CLI stays alive
55
- // The MqttControlPlaneClient will detect the disconnect and set refreshPending=true
56
- // The re-arm logic will retry after reconnect
57
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
58
- logger.debug('jwt.refresh.publish.econnreset', {
59
- refreshRequestId,
60
- error: publishError?.message || String(publishError),
61
- code: publishError?.code,
62
- action: 'buffered_for_retry'
63
- });
64
-
65
- // Return false to indicate buffered (don't throw - prevents "Unexpected error" log)
66
- return false;
67
- }
68
-
69
- // For non-connection errors (e.g., JSON parse, invalid payload), rethrow
70
- logger.error('jwt.refresh.publish.error', {
71
- refreshRequestId,
72
- error: publishError?.message || String(publishError),
73
- code: publishError?.code
74
- });
75
- throw publishError;
76
- }
77
- }
78
19
 
79
20
  export default async function tunnel(args = []) {
80
21
  // Device credential guard - use same path resolution as device.js
@@ -444,7 +385,7 @@ async function connect() {
444
385
  const issuedAt = new Date().toISOString();
445
386
 
446
387
  // CP-3C: Collect hardware fingerprint
447
- const { getFpHash } = await import("../lib/fingerprint.js");
388
+ const { getFpHash } = await import("#tunnel-core/lib/fingerprint.js");
448
389
  const fingerprint = await getFpHash(cfg.clientId);
449
390
 
450
391
  // Warn if fingerprint unavailable
@@ -553,18 +494,12 @@ async function connect() {
553
494
  }
554
495
 
555
496
  async function httpTunnel(localPort, secGroupSlug) {
556
- logger.info('cli.http.start', { localPort, secGroupSlug });
557
- // QPA-CLI-11: Vault UX messaging - Initializing tunnel
497
+ logger.info("cli.http.start", { localPort, secGroupSlug });
558
498
  process.stdout.write(`⚙️ Initializing tunnel on port ${localPort}…\n`);
559
-
560
- // 0) Imports (kept local to this command to avoid global side-effects)
499
+
561
500
  const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
562
- const { MqttCore } = await import("@asyx/mqtt-core");
563
- const { waitForAssignment } = await import("../state/assignment.js");
564
- const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
565
- const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
566
501
  const { readFileSync } = await import("node:fs");
567
-
502
+
568
503
  // 1) Load IoT config (throws with clear messages if misconfigured)
569
504
  let cfg;
570
505
  try {
@@ -574,884 +509,116 @@ async function httpTunnel(localPort, secGroupSlug) {
574
509
  process.stderr.write(`Config error: ${e?.message || e}\n`);
575
510
  process.exit(1);
576
511
  }
577
-
512
+
578
513
  logger.info("cli.http.control_plane.establish", {});
579
514
  // QPA-CLI-11: Vault UX messaging - Negotiating control-plane security
580
515
  process.stdout.write(`🔐 Negotiating control-plane security…\n`);
581
516
 
582
- // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
583
- const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
584
-
585
- // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
586
- // WebSocket endpoints ignore client certificates, so we must use TLS
587
- const port = 443;
588
- const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
589
-
590
- // Load certificates for MQTT TLS options
591
- const ca = readFileSync(cfg.caPath);
592
- const cert = readFileSync(cfg.certPath);
593
- const key = readFileSync(cfg.keyPath);
594
-
595
- // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
596
- const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
597
-
598
- // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
599
- const baseClientId = cfg.clientId;
600
-
601
- // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect (must be before MqttControlPlaneClient)
602
- const instanceIdRef = { instanceId: null };
603
-
604
- // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
605
- const tunnelInstanceRef = { tunnel: null };
606
-
607
- // QPA-CLI-05: Store coordinator references for onRefreshLease callback
608
- // These will be set after core and ingress are created
609
- let coordinatorCoreRef = null;
610
- let coordinatorIngressRef = null;
611
- let deviceIdRef = cfg.clientId;
612
- let localPortRef = localPort;
613
- let secGroupSlugRef = secGroupSlug;
614
- // Track subscription state to ensure refresh requests wait for subscription to be active
615
- let subscriptionReadyRef = { ready: false };
616
-
617
- // 2) Build MqttControlPlaneClient for connection management
618
- // Use mqtts (TLS) protocol with client certificates for AWS IoT authentication
619
- const mqttClient = new MqttControlPlaneClient({
620
- url: mqttUrl,
621
- baseClientId,
622
- mqttOptions: {
623
- protocol: 'mqtts',
624
- port: 443,
625
- cert,
626
- key,
627
- ca,
628
- rejectUnauthorized: true,
629
- keepalive,
630
- connectTimeout: 8000,
631
- // ALPN for port 443 (AWS IoT)
632
- ALPNProtocols: ['x-amzn-mqtt-ca'],
633
- },
634
- mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
517
+ // Story 12.1 (step 2b): the HTTP flow lives in @asyx/tunnel-core; the CLI prints its events and
518
+ // maps its error codes to the same messages and exit codes as before.
519
+ const { createHttpTunnel } = await import("#tunnel-core/flows/http.js");
520
+ const handle = createHttpTunnel({
521
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
522
+ localPort,
523
+ secGroupSlug,
635
524
  logger,
636
- onConnected: async (mqttClientInstance) => {
637
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
638
- const newClientId = mqttClient.getClientId();
639
- logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
640
-
641
- // TPB-12: Update instance registry if clientId changed on reconnect
642
- if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
643
- const oldInstanceId = instanceIdRef.instanceId;
644
- logger.debug("cli.instance.clientid_rotated", {
645
- oldInstanceId,
646
- newInstanceId: newClientId,
647
- tunnelType: 'http'
648
- });
649
-
650
- // Unregister old instance and register new one
651
- const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
652
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
653
-
654
- // Get old instance context to preserve metadata
655
- const oldContext = getInstance(oldInstanceId);
656
- if (oldContext) {
657
- // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
658
- const preservedRequestId = oldContext.expectedRequestId;
659
-
660
- // Register new instance FIRST (before unregistering old) to ensure routing works
661
- registerInstance(newClientId, {
662
- tunnelType: 'http',
663
- setAssignment: setAssignmentFn,
664
- getAssignment: getAssignmentFn,
665
- metadata: oldContext.metadata || { baseClientId, localPort, secGroupSlug }
666
- });
667
-
668
- // Migrate expectedRequestId to new instance (preserves in-flight refresh/reconnect)
669
- if (preservedRequestId) {
670
- const { setExpectedRequestId } = await import("../state/instance-registry.js");
671
- setExpectedRequestId(newClientId, preservedRequestId);
672
- logger.debug("cli.instance.expected_requestid_migrated", {
673
- oldInstanceId,
674
- newInstanceId: newClientId,
675
- requestId: preservedRequestId,
676
- tunnelType: 'http'
677
- });
678
- }
679
-
680
- // Now unregister old instance (this will clean up old expectedRequestId mapping)
681
- unregisterInstance(oldInstanceId);
682
-
683
- // Move the assignment onto the new id and drop the old key.
684
- const migration = migrateInstanceAssignment({
685
- oldId: oldInstanceId,
686
- newId: newClientId,
687
- tunnel: tunnelInstanceRef.tunnel,
688
- });
689
- if (migration.moved) {
690
- logger.debug("cli.instance.assignment_migrated", {
691
- oldInstanceId,
692
- newInstanceId: newClientId,
693
- leaseId: migration.leaseId,
694
- tunnelType: 'http',
695
- assignmentCount: migration.size,
696
- });
697
- }
698
-
699
- logger.debug("cli.instance.reregistered", {
700
- oldInstanceId,
701
- newInstanceId: newClientId,
702
- tunnelType: 'http'
703
- });
704
- }
705
-
706
- // Update instanceId ref
707
- instanceIdRef.instanceId = newClientId;
708
- }
709
-
710
- // QPA-CLI-11: Vault UX messaging - Control-plane sealed
711
- process.stdout.write("✅ Control-plane sealed\n");
712
-
713
- // Resubscribe to topics on reconnect (MqttControlPlaneClient manages subscriptions)
714
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
715
- subscriptionReadyRef.ready = false;
716
- try {
717
- await mqttClient.subscribe(evtWildcard, 0);
718
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
719
- logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
720
- // Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
721
- // This prevents race conditions where refresh requests are published before subscription is active
722
- subscriptionReadyRef.ready = true;
723
- } catch (e) {
724
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
725
- logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
726
- // Mark ready even on failure to avoid blocking forever
727
- subscriptionReadyRef.ready = true;
728
- }
729
-
730
- // QPA-CLI-05: Auto-resume is now handled by MqttControlPlaneClient's refresh buffering
731
- // The onRefreshLease callback will be called automatically when MQTT reconnects if refreshPending is true
732
- },
733
- onOffline: (reason) => {
734
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
735
- logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
736
- process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
737
- // Clear subscription ready flag on disconnect so we wait for resubscription on reconnect
738
- subscriptionReadyRef.ready = false;
739
- },
740
- onFatalError: (reason, err) => {
741
- logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
742
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
743
- process.exit(1);
744
- },
745
- // QPA-CLI-05: Wire onRefreshLease to handle JWT refresh via coordinator
746
- // TPB-12: Capture instanceId in closure for per-instance routing
747
- onRefreshLease: async () => {
748
- if (!coordinatorCoreRef || !coordinatorIngressRef) {
749
- throw new Error("Coordinator not available for refresh");
750
- }
751
-
752
- // TPB-12: Get instanceId from mqttClient (captured in closure)
753
- const refreshInstanceId = mqttClient.getClientId();
754
-
755
- const { getAssignment, readRefreshAssignment } = await import('../state/assignment.js');
756
- const { getFpHash } = await import('../lib/fingerprint.js');
757
-
758
- // TPB-12: Get assignment for this specific instance
759
- const currentAssignment = getAssignment(refreshInstanceId);
760
- if (!currentAssignment) {
761
- throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
762
- }
763
-
764
- const leaseId = currentAssignment.leaseId;
765
- if (!leaseId) {
766
- throw new Error("No leaseId in current assignment");
767
- }
768
-
769
- // Build refresh payload
770
- const refreshRequestId = `refresh-${Date.now()}`;
771
- const fingerprint = await getFpHash(deviceIdRef);
772
-
773
- // TPB-12: Include instanceId in refresh payload
774
- const refreshPayload = {
775
- requestId: refreshRequestId,
776
- instanceId: refreshInstanceId, // TPB-12: Per-instance routing
777
- refreshOf: leaseId,
778
- proto: 'http',
779
- localPort: localPortRef,
780
- clientId: deviceIdRef,
781
- ...fingerprint
782
- };
783
-
784
- // QPA-04: Include secGroupSlug in refresh payload if provided
785
- if (secGroupSlugRef) {
786
- refreshPayload.secGroupSlug = secGroupSlugRef;
787
- }
788
-
789
- // Cancel any existing awaiters for this leaseId before starting a new refresh
790
- // This prevents duplicate awaiters from accumulating when multiple refresh attempts happen
791
- const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
792
- const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
793
- // Test if this awaiter matches open_ack messages (likely a stale refresh awaiter)
794
- try {
795
- const testMessage = {
796
- topic: ackTopic,
797
- payload: { type: 'open_ack', requestId: 'test' }
798
- };
799
- // If the criteria matches open_ack messages, it's likely a refresh awaiter
800
- const matches = awaiter.criteria(testMessage);
801
- // Only cancel if it matches open_ack (we don't want to cancel other awaiters)
802
- return matches;
803
- } catch {
804
- return false;
805
- }
806
- });
807
-
808
- if (cancelled > 0) {
809
- logger.debug('jwt.refresh.awaiter.cancelled_stale', {
810
- refreshRequestId,
811
- cancelledCount: cancelled,
812
- reason: 'new_refresh_starting'
813
- });
814
- }
815
-
816
- // Wait for subscription to be ready before publishing (prevents race where ack is published before subscription is active)
817
- // Only wait if subscription is not ready (e.g., after reconnect before resubscription completes)
818
- if (!subscriptionReadyRef.ready) {
819
- logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
820
- // Wait up to 2 seconds for subscription to be ready (should be immediate after subscribe() resolves)
821
- const maxWait = 2000;
822
- const startWait = Date.now();
823
- while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
824
- await new Promise(resolve => setTimeout(resolve, 50));
825
- }
826
- if (!subscriptionReadyRef.ready) {
827
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
828
- logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
829
- } else {
830
- logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
831
- }
832
- }
833
-
834
- // Set up topic and wait for ack
835
- const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
836
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
837
-
838
- // Log awaiter registration for debugging
839
- logger.debug('jwt.refresh.awaiter.registered', {
840
- refreshRequestId,
841
- instanceId: refreshInstanceId,
842
- tunnelType: 'http',
843
- timeoutMs: ACK_TIMEOUT_MS,
844
- expectedType: 'open_ack'
845
- });
846
-
847
- const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
848
- try {
849
- const parsed = message.payload;
850
- const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
851
- const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
852
-
853
- // Log matching attempts for debugging
854
- if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
855
- logger.debug('jwt.refresh.awaiter.checking', {
856
- refreshRequestId,
857
- receivedRequestId: parsed.requestId,
858
- receivedType: parsed.type,
859
- isAck,
860
- isReject,
861
- topic: message.topic
862
- });
863
- }
864
-
865
- // If we get a reject, throw an error so the awaiter rejects the promise
866
- if (isReject) {
867
- const reason = parsed.data?.reason || 'unknown';
868
- if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
869
- const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
870
- leaseClosedError.code = 'LEASE_CLOSED';
871
- leaseClosedError.reason = reason;
872
- throw leaseClosedError;
873
- }
874
- // For other reject reasons, also throw but with different code
875
- const rejectError = new Error(`Refresh rejected: ${reason}`);
876
- rejectError.code = 'REFRESH_REJECTED';
877
- rejectError.reason = reason;
878
- throw rejectError;
879
- }
880
-
881
- return isAck;
882
- } catch (e) {
883
- // If it's a lease_closed or refresh_rejected error, rethrow it
884
- if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
885
- throw e;
886
- }
887
- logger.debug('jwt.refresh.awaiter.criteria_error', {
888
- refreshRequestId,
889
- error: e.message
890
- });
891
- return false;
892
- }
893
- }, ACK_TIMEOUT_MS);
894
-
895
- // Publish refresh request
896
- // QPA-CLI-09: Catch ECONNRESET during publish to prevent fatal exit
897
- const publishSuccess = await publishRefreshRequestWithErrorHandling(
898
- coordinatorCoreRef,
899
- cmdOpenTopic,
900
- refreshPayload,
901
- refreshRequestId,
902
- logger
903
- );
904
-
905
- // If publish returned false, ECONNRESET was caught and buffered
906
- // Throw an error that MqttControlPlaneClient recognizes as offline error
907
- // This ensures refreshPending stays true and re-arm logic knows refresh is needed
908
- // The error will be caught by MqttControlPlaneClient and buffered (not bubbled up)
909
- if (publishSuccess === false) {
910
- const bufferedError = new Error('Connection closed during refresh publish');
911
- bufferedError.code = 'ECONNRESET';
912
- throw bufferedError;
913
- }
914
-
915
- // Wait for ack with reconnect retry on timeout
916
- let ackResult;
917
- try {
918
- ackResult = await ackPromise;
919
- } catch (error) {
920
- // Check if this is a lease_closed error - don't retry, treat as fatal
921
- if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
922
- logger.error('jwt.refresh.rejected', {
923
- reason: error.reason || 'unknown',
924
- requestId: refreshRequestId,
925
- action: 'fatal'
926
- });
927
- throw new Error(`Cannot refresh closed lease: ${error.reason || 'lease_closed'}`);
928
- }
929
-
930
- // Otherwise treat as timeout and retry
931
- const timeoutError = error;
932
- // QPA-CLI-07: On timeout, reconnect control-plane and retry once
933
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
934
- logger.debug('jwt.refresh.timeout', {
935
- error: timeoutError.message,
936
- action: 'reconnect_and_retry',
937
- requestId: refreshRequestId
938
- });
939
-
940
- // Cancel any existing awaiters for this requestId before retrying
941
- // This prevents duplicate awaiters from accumulating when retrying
942
- const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
943
- // Test if this awaiter matches the same requestId
944
- try {
945
- // Create a test message to see if the awaiter's criteria would match
946
- // We can't directly inspect the criteria, so we test it with a mock message
947
- const testMessage = {
948
- topic: `asyx/tunnel/clients/${deviceIdRef}/evt/ack`,
949
- payload: { type: 'open_ack', requestId: refreshRequestId }
950
- };
951
- return awaiter.criteria(testMessage);
952
- } catch {
953
- return false;
954
- }
955
- });
956
-
957
- if (cancelled > 0) {
958
- logger.debug('jwt.refresh.awaiter.cancelled_duplicates', {
959
- refreshRequestId,
960
- cancelledCount: cancelled
961
- });
962
- }
963
-
964
- // Force reconnect to get fresh MQTT session
965
- await mqttClient.forceReconnect('ack_timeout');
966
-
967
- // Re-register awaiter with same timeout after reconnect; ack might already be queued
968
- logger.debug('jwt.refresh.awaiter.retry_registered', {
969
- refreshRequestId,
970
- timeoutMs: ACK_TIMEOUT_MS
971
- });
972
-
973
- const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
974
- try {
975
- const parsed = message.payload;
976
- const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
977
- const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
978
-
979
- // Log matching attempts for debugging
980
- if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
981
- logger.debug('jwt.refresh.awaiter.retry_checking', {
982
- refreshRequestId,
983
- receivedRequestId: parsed.requestId,
984
- receivedType: parsed.type,
985
- isAck,
986
- isReject,
987
- topic: message.topic
988
- });
989
- }
990
-
991
- // If we get a reject, throw an error so the awaiter rejects the promise
992
- if (isReject) {
993
- const reason = parsed.data?.reason || 'unknown';
994
- if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
995
- const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
996
- leaseClosedError.code = 'LEASE_CLOSED';
997
- leaseClosedError.reason = reason;
998
- throw leaseClosedError;
999
- }
1000
- // For other reject reasons, also throw but with different code
1001
- const rejectError = new Error(`Refresh rejected: ${reason}`);
1002
- rejectError.code = 'REFRESH_REJECTED';
1003
- rejectError.reason = reason;
1004
- throw rejectError;
1005
- }
1006
-
1007
- return isAck;
1008
- } catch (e) {
1009
- // If it's a lease_closed or refresh_rejected error, rethrow it
1010
- if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
1011
- throw e;
1012
- }
1013
- logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
1014
- refreshRequestId,
1015
- error: e.message
1016
- });
1017
- return false;
1018
- }
1019
- }, ACK_TIMEOUT_MS);
1020
-
1021
- try {
1022
- ackResult = await retryAckPromise;
1023
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1024
- logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
1025
- } catch (retryError) {
1026
- // Check if this is a lease_closed error - don't retry, treat as fatal
1027
- if (retryError.code === 'LEASE_CLOSED' || retryError.code === 'REFRESH_REJECTED') {
1028
- logger.error('jwt.refresh.rejected.retry', {
1029
- reason: retryError.reason || 'unknown',
1030
- requestId: refreshRequestId,
1031
- action: 'fatal'
1032
- });
1033
- throw new Error(`Cannot refresh closed lease: ${retryError.reason || 'lease_closed'}`);
1034
- }
1035
-
1036
- logger.error('jwt.refresh.timeout', {
1037
- error: retryError.message,
1038
- action: 'give_up',
1039
- requestId: refreshRequestId
1040
- });
1041
- throw new Error(`Refresh timeout after reconnect: ${retryError.message}`);
1042
- }
1043
- }
1044
-
1045
- // Get new assignment for this client id. An unkeyed read is null once
1046
- // rotation has left more than one map entry.
1047
- const { assignment: newAssignment, expMs } = readRefreshAssignment(refreshInstanceId);
1048
- const newJwt = newAssignment.jwt;
1049
-
1050
- // QPA-CLI-05: Notify HttpTunnel that new JWT is available
1051
- // HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
1052
- if (tunnelInstanceRef.tunnel) {
1053
- // Update HttpTunnel with new JWT and assignment
1054
- tunnelInstanceRef.tunnel.jwt = newJwt;
1055
- tunnelInstanceRef.tunnel.requestId = newAssignment.requestId;
1056
- tunnelInstanceRef.tunnel.relayUrl = newAssignment.relayUrl;
1057
- tunnelInstanceRef.tunnel.headers = {
1058
- 'Authorization': `Bearer ${newJwt}`,
1059
- 'X-Asyx-DeviceId': deviceIdRef,
1060
- 'X-Asyx-RequestId': newAssignment.requestId
1061
- };
1062
-
1063
- // Update jwtMeta for HttpTunnel
1064
- tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
1065
-
1066
- // Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
1067
- // to avoid double-counting when refresh happens via in-band reauth
1068
-
1069
- // Try in-band reauth if WebSocket is open
1070
- if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
1071
- const prevJti = tunnelInstanceRef.tunnel.jwtMeta?.token
1072
- ? tunnelInstanceRef.tunnel._extractJti(tunnelInstanceRef.tunnel.jwtMeta.token)
1073
- : null;
1074
- try {
1075
- const reauthSuccess = await tunnelInstanceRef.tunnel.reauthInBand(newJwt, prevJti, 'timer');
1076
- if (reauthSuccess) {
1077
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1078
- logger.debug('jwt.refresh.success', { method: 'in_band', leaseId: newAssignment.leaseId });
1079
- return expMs;
1080
- }
1081
- } catch (reauthError) {
1082
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1083
- logger.debug('jwt.reauth.exception', { error: reauthError.message });
1084
- }
1085
- }
1086
-
1087
- // Fallback to reconnect
1088
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1089
- logger.debug('jwt.refresh.reconnect', { leaseId: newAssignment.leaseId });
1090
- await tunnelInstanceRef.tunnel._attemptConnect();
1091
- }
1092
-
1093
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1094
- logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
1095
- return expMs;
1096
- },
525
+ onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
1097
526
  });
1098
-
1099
- // Create Transport adapter and MqttCore
1100
- const transport = new MqttControlPlaneTransport(mqttClient);
1101
- const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
1102
-
1103
- // CLI-IMG-ControlPlane-Watchdog: Expose helpers for HttpTunnel compatibility
1104
- const isControlPlaneConnected = () => {
1105
- return mqttClient.isOnline();
1106
- };
1107
-
1108
- const waitForControlPlane = () => {
1109
- if (mqttClient.isOnline()) {
1110
- return Promise.resolve();
1111
- }
1112
- // Poll until connected or timeout
1113
- const start = Date.now();
1114
- return new Promise((resolve, reject) => {
1115
- const interval = setInterval(() => {
1116
- if (mqttClient.isOnline()) {
1117
- clearInterval(interval);
1118
- resolve();
1119
- } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
1120
- clearInterval(interval);
1121
- reject(new Error('control_plane_timeout'));
1122
- }
1123
- }, 250);
1124
- });
1125
- };
1126
-
1127
- // QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
1128
- // Note: MqttControlPlaneClient doesn't expose this yet - can be added if needed
1129
- const getLastMqttError = () => {
1130
- // TODO: Add getLastMqttError to MqttControlPlaneClient if needed
1131
- return null;
1132
- };
1133
-
1134
- // QPA-CLI-03: Expose helper to force reconnect
1135
- const getForceReconnect = () => {
1136
- // MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
1137
- return async () => {
1138
- if (!mqttClient.isOnline()) {
1139
- await mqttClient.disconnect();
1140
- await mqttClient.connect();
1141
- }
1142
- };
1143
- };
1144
-
1145
- // 3) Connect to control plane
1146
- try {
1147
- await mqttClient.connect();
1148
- } catch (e) {
1149
- logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
1150
- process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
527
+ // QPA-CLI-11: Vault UX messaging - Control-plane sealed
528
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
529
+ handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
530
+ handle.on('control-fatal', ({ reason }) => {
531
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
1151
532
  process.exit(1);
1152
- }
1153
-
1154
- // TPB-12: Get instanceId (full MQTT clientId) after connection
1155
- instanceIdRef.instanceId = mqttClient.getClientId();
1156
- const instanceId = instanceIdRef.instanceId; // Use const for current scope, but update ref on reconnect
1157
- logger.debug("cli.instance.registered", { instanceId, tunnelType: 'http', baseClientId });
1158
-
1159
- // 4) Set up topics and message handling
1160
- // CLI-MQTT-UniqueID-CleanSession: Use baseClientId for topics (not session client ID) to maintain topic stability
1161
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1162
- const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
1163
- const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
1164
-
1165
- // Subscribe to topics after initial connect
1166
- // Note: MqttControlPlaneClient.onConnected callback will handle resubscription on reconnect
1167
- await core.subscribe(evtWildcard, 0);
1168
- // Mark subscription as ready immediately - subscribe() resolves only after broker ACKs
1169
- subscriptionReadyRef.ready = true;
1170
-
1171
- // 5) Set up message ingress and dispatcher
1172
- const ingress = new MessageIngress({
1173
- maxAwaiters: 100,
1174
- observability: process.env.ASYX_DEBUG === '1',
1175
- logger // QPA-CLI-10: Pass logger for quiet mode
1176
- });
1177
-
1178
- ingress.setDispatcher(dispatchEvt);
1179
-
1180
- // TPB-12: Register instance in registry with per-instance callbacks
1181
- const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
1182
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1183
-
1184
- registerInstance(instanceId, {
1185
- tunnelType: 'http',
1186
- setAssignment: setAssignmentFn,
1187
- getAssignment: getAssignmentFn,
1188
- metadata: { baseClientId, localPort, secGroupSlug }
1189
533
  });
1190
-
1191
- // QPA-CLI-05: Store coordinator references for onRefreshLease callback
1192
- coordinatorCoreRef = core;
1193
- coordinatorIngressRef = ingress;
1194
-
1195
- core.onMessage(async (m) => {
1196
- try {
1197
- await ingress.handleMessage(m);
1198
- } catch (e) {
1199
- if (e && e.code === "SETUP_REQUIRED") {
1200
- process.stderr.write(`❌ ${e.message}\n`);
1201
- try { await core.end(); } catch {}
1202
- process.exit(2);
1203
- }
1204
- if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
1205
- process.stderr.write(`❌ ${e.message}\n`);
1206
- try { await core.end(); } catch {}
1207
- process.exit(1);
1208
- }
1209
- process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
1210
- try { await core.end(); } catch {}
1211
- process.exit(1);
1212
- }
534
+ // Story 12.1: messages the HTTP tunnel used to print itself
535
+ handle.on('notice', ({ code, reason, mqttReason, retry, port }) => {
536
+ const mqttSuffix = (mqttReason && mqttReason !== 'unknown') ? `. MQTT reason: ${mqttReason}` : '';
537
+ if (code === 'control_plane_offline') process.stdout.write(`⚠️ Control-plane offline (${reason})${mqttSuffix}. Waiting for reconnect…\n`);
538
+ else if (code === 'control_plane_timeout') process.stdout.write(`⚠️ Control-plane offline (timeout)${mqttSuffix}. Waiting for reconnect…\n`);
539
+ else if (code === 'jwt_expired_offline') process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
540
+ else if (code === 'quickpass_refresh_delayed') process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${retry})\n`);
541
+ // Story 3.8: the tunnel stays up while the local service is down; visitors get a 502 page.
542
+ else if (code === 'local_service_unreachable') process.stdout.write(`⚠️ Nothing is answering on localhost:${port}. The tunnel stays up; visitors see a "not reachable" page until your app is back.\n`);
543
+ else if (code === 'local_service_back') process.stdout.write(`✅ Your app on localhost:${port} is answering again.\n`);
1213
544
  });
1214
-
1215
- // 6) Publish cmd/open request
1216
- const requestId = crypto.randomUUID();
1217
- const { getFpHash } = await import("../lib/fingerprint.js");
1218
- const fingerprint = await getFpHash(cfg.clientId);
1219
-
1220
- // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
1221
- setExpectedRequestId(instanceId, requestId);
1222
-
1223
- // TPB-12: Include instanceId in cmd/open payload
1224
- const openPayload = {
1225
- requestId,
1226
- instanceId, // TPB-12: Per-instance routing
1227
- proto: 'http',
1228
- localPort,
1229
- clientId: cfg.clientId,
1230
- ...fingerprint
1231
- };
1232
-
1233
- // QPA-04: Include secGroupSlug in cmd/open payload if provided
1234
- if (secGroupSlug) {
1235
- openPayload.secGroupSlug = secGroupSlug;
1236
- }
1237
-
1238
- // Publish the open request
1239
- await core.publish({
1240
- topic: cmdOpenTopic,
1241
- payload: JSON.stringify(openPayload),
1242
- qos: 1,
1243
- retain: false
545
+ handle.on('closed', ({ error }) => {
546
+ if (!error) return;
547
+ if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
548
+ // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
549
+ if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
550
+ if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
551
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
552
+ process.exit(1);
1244
553
  });
1245
554
 
1246
- logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'http' });
1247
-
1248
- // 7) Wait for ack and then connect to relay
1249
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
1250
-
1251
555
  try {
1252
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
1253
- logger.info("cli.ack.wait.start", { requestId });
1254
- const assignment = await assignmentPromise;
1255
- logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'http' });
1256
- logger.info("cli.assignment.received", { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
1257
- // TPB-12: Persist assignment using per-instance store
1258
- try {
1259
- const { setAssignment } = await import("../state/assignment.js");
1260
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
1261
- setAssignment(instanceId, assignment);
1262
- // Clear expected requestId now that assignment exists (routing will use leaseId after this)
1263
- clearExpectedRequestId(instanceId);
1264
- } catch {}
1265
-
1266
- // 8) Connect to relay using thin client behavior
1267
- // QPA-CLI-05: Pass mqttClient for refresh scheduling
1268
- // TPB-12: Pass instanceId for per-instance assignment routing
1269
- await connectToRelay(
1270
- assignment,
1271
- cfg.clientId,
1272
- localPort,
1273
- core,
1274
- ingress,
1275
- { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
1276
- secGroupSlug,
1277
- tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here before infinite promise
1278
- mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling
1279
- instanceId // TPB-12: Pass instanceId for per-instance assignment routing
1280
- );
1281
-
556
+ await handle.open();
1282
557
  } catch (error) {
1283
- logger.error("cli.ack.wait.failed", { error: error.message });
1284
- // TPB-12: Clean up expected requestId on timeout/error (prevents map leak)
1285
- try {
1286
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
1287
- clearExpectedRequestId(instanceId);
1288
- } catch (err) {
1289
- // Ignore cleanup errors
558
+ switch (error.code) {
559
+ case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
560
+ case 'assignment_failed': break; // HTTP has always exited here without a message
561
+ case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
562
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
1290
563
  }
1291
- try { await core.end(); } catch {}
1292
564
  process.exit(1);
1293
565
  }
1294
- }
1295
-
1296
- export async function connectToRelay(
1297
- assignment,
1298
- deviceId,
1299
- localPort,
1300
- coordinatorCore,
1301
- coordinatorIngress,
1302
- controlPlaneHelpers,
1303
- secGroupSlug,
1304
- tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
1305
- mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling
1306
- instanceId = null // TPB-12: Pass instanceId for per-instance assignment routing
1307
- ) {
1308
- // Import WebSocket bridge logic (ported from client-mvp)
1309
- const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
1310
-
1311
- const tunnel = new HttpTunnel({
1312
- relayUrl: assignment.relayUrl,
1313
- jwt: assignment.jwt, // Use JWT as-is (no validation)
1314
- deviceId,
1315
- requestId: assignment.requestId,
1316
- localPort,
1317
- coordinatorCore, // CLI-IMG-WSReconnect: Pass coordinator connection for JWT refresh
1318
- coordinatorIngress, // CLI-IMG-WSReconnect: Pass coordinator ingress for JWT refresh
1319
- // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
1320
- isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
1321
- waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
1322
- getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
1323
- getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
1324
- controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
1325
- // QPA-04: Pass secGroupSlug to HttpTunnel
1326
- secGroupSlug,
1327
- // TPB-12: Pass instanceId to HttpTunnel for per-instance assignment routing
1328
- instanceId,
1329
- log: {
1330
- info: (msgOrFields, maybeFields) => {
1331
- if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
1332
- return logger.info(maybeFields, msgOrFields);
1333
- },
1334
- warn: (msgOrFields, maybeFields) => {
1335
- if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
1336
- return logger.warn(maybeFields, msgOrFields);
1337
- },
1338
- error: (msgOrFields, maybeFields) => {
1339
- if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
1340
- return logger.error(maybeFields, msgOrFields);
1341
- },
1342
- debug: (msgOrFields, maybeFields) => {
1343
- if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
1344
- return logger.debug(maybeFields, msgOrFields);
1345
- }
1346
- }
1347
- });
566
+ const assignment = handle.assignment;
567
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
1348
568
 
1349
- // QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
1350
- if (tunnelInstanceRef) {
1351
- tunnelInstanceRef.tunnel = tunnel;
569
+ // QPA-CLI-11: QuickPass line only when a group was requested and the coordinator confirmed it
570
+ if (secGroupSlug && assignment.quickpassSlug) {
571
+ process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
1352
572
  }
573
+ process.stdout.write(`🌐 Tunnel live at http://localhost:${localPort}\n`);
574
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
575
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
576
+ if (logLevel === 'info' || logLevel === 'debug') {
577
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
578
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
579
+ }
580
+ process.stdout.write(` Press Ctrl+C to stop\n`);
1353
581
 
1354
- try {
1355
- await tunnel.open();
1356
-
1357
- // QPA-CLI-05: Schedule initial proactive refresh via MqttControlPlaneClient
1358
- // TCP-S4: Skip refresh scheduling for TCP tunnels (refresh not implemented yet)
1359
- // HTTP tunnels continue to schedule refresh as before
1360
- // Note: This is a temporary limitation until TCP refresh is implemented
1361
- if (mqttClient && assignment.jwt && assignment.leaseId) {
1362
- try {
1363
- // Decode JWT to get expiration timestamp (assignment doesn't store exp, must decode JWT)
1364
- const parts = assignment.jwt.split('.');
1365
- if (parts.length === 3) {
1366
- const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
1367
- const expMs = payload.exp ? payload.exp * 1000 : null;
1368
- if (expMs) {
1369
- mqttClient.scheduleRefresh(expMs, assignment.leaseId);
1370
- logger.debug('jwt.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
1371
- } else {
1372
- logger.warn('jwt.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
1373
- }
1374
- } else {
1375
- logger.warn('jwt.refresh.initial_failed', { reason: 'invalid_jwt_format' });
1376
- }
1377
- } catch (error) {
1378
- logger.warn('jwt.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
1379
- }
1380
- }
1381
-
1382
- // QPA-CLI-11: Vault UX messaging - Final tunnel live message
1383
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
1384
- logger.info("tunnel.active", { url: `http://localhost:${localPort}`, relayId: assignment.relayId, leaseMs: assignment.leaseMs });
1385
-
1386
- // Show QuickPass secured message if QuickPass was requested and enabled
1387
- if (secGroupSlug && assignment.quickpassSlug) {
1388
- process.stdout.write(`🛡️ QuickPass secured (group=${assignment.quickpassSlug})\n`);
582
+ let shuttingDown = false;
583
+ const onSig = async (sig) => {
584
+ if (shuttingDown) return;
585
+ shuttingDown = true;
586
+ logger.info("cli.signal.shutdown", { sig });
587
+ process.stdout.write(`signal ${sig} — shutting down…\n`);
588
+ const killer = setTimeout(() => {
589
+ logger.error("tunnel.close.timeout", {});
590
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
591
+ process.exit(0);
592
+ }, 3000);
593
+ try {
594
+ handle.tunnel.close();
595
+ } catch (e) {
596
+ logger.error('tunnel.close.error', { error: e.message });
597
+ process.stderr.write(`Error closing tunnel: ${e.message}\n`);
1389
598
  }
1390
-
1391
- // Tunnel live message
1392
- process.stdout.write(`🌐 Tunnel live at http://localhost:${localPort}\n`);
1393
-
1394
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
1395
- // Most users don't need to know the lease term; they just care the tunnel stays alive
1396
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
1397
- if (logLevel === 'info' || logLevel === 'debug') {
1398
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
1399
- process.stdout.write(` Lease window: ${leaseMinutes} minutes (auto-renews while active)\n`);
599
+ try {
600
+ await handle.mqttClient.disconnect();
601
+ } catch (e) {
602
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
1400
603
  }
1401
-
1402
- process.stdout.write(` Press Ctrl+C to stop\n`);
1403
-
1404
- // CLI-IMG-WSReconnect: Set up graceful shutdown
1405
- // QPA-CLI-05: Also disconnect MqttControlPlaneClient on shutdown
1406
- let shuttingDown = false;
1407
- const onSig = async (sig) => {
1408
- if (shuttingDown) return;
1409
- shuttingDown = true;
1410
- logger.info("cli.signal.shutdown", { sig });
1411
- process.stdout.write(`signal ${sig} — shutting down…\n`);
1412
- const killer = setTimeout(() => {
1413
- logger.error("tunnel.close.timeout", {});
1414
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
1415
- process.exit(0);
1416
- }, 3000);
1417
- try {
1418
- tunnel.close();
1419
- } catch (e) {
1420
- logger.error('tunnel.close.error', { error: e.message });
1421
- process.stderr.write(`Error closing tunnel: ${e.message}\n`);
1422
- }
1423
- // QPA-CLI-05: Disconnect MqttControlPlaneClient to clear timers
1424
- try {
1425
- await mqttClient.disconnect();
1426
- } catch (e) {
1427
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1428
- logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
604
+ clearTimeout(killer);
605
+ process.exit(0);
606
+ };
607
+ process.once("SIGINT", onSig);
608
+ process.once("SIGTERM", onSig);
609
+
610
+ // Manual renewal for troubleshooting
611
+ try {
612
+ process.once('SIGUSR2', () => {
613
+ logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
614
+ try { handle.attemptJwtRefresh(); } catch (e) {
615
+ logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
1429
616
  }
1430
- clearTimeout(killer);
1431
- process.exit(0);
1432
- };
1433
- process.once("SIGINT", onSig);
1434
- process.once("SIGTERM", onSig);
617
+ });
618
+ } catch {}
1435
619
 
1436
- // CLI-REFRESH-SIGNAL: External trigger to force JWT refresh (avoids SIGUSR1 inspector conflict)
1437
- try {
1438
- process.once('SIGUSR2', () => {
1439
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1440
- logger.debug('jwt.refresh.trigger', { source: 'signal', sig: 'SIGUSR2' });
1441
- try { tunnel.attemptJwtRefresh(); } catch (e) {
1442
- logger.error('jwt.refresh.trigger.error', { error: e?.message || String(e) });
1443
- }
1444
- });
1445
- } catch {}
1446
-
1447
- // Keep process alive until SIGINT/SIGTERM
1448
- await new Promise(() => {});
1449
-
1450
- } catch (error) {
1451
- logger.error('cli.tunnel.failed', { error: error.message });
1452
- process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
1453
- process.exit(1);
1454
- }
620
+ // Keep process alive until SIGINT/SIGTERM
621
+ await new Promise(() => {});
1455
622
  }
1456
623
 
1457
624
  /**
@@ -1494,19 +661,14 @@ function isLocalhostTarget(target) {
1494
661
  async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
1495
662
  logger.info('cli.tcp.start', { localPort, serviceName });
1496
663
  process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1497
-
664
+
1498
665
  // TCP-S1: Validation complete, target constructed
1499
666
  const target = buildTcpTarget(localPort);
1500
667
  logger.info('cli.tcp.target', { target });
1501
-
1502
- // 0) Imports (kept local to this command to avoid global side-effects)
668
+
1503
669
  const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
1504
- const { MqttCore } = await import("@asyx/mqtt-core");
1505
- const { waitForAssignment } = await import("../state/assignment.js");
1506
- const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
1507
- const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
1508
670
  const { readFileSync } = await import("node:fs");
1509
-
671
+
1510
672
  // 1) Load IoT config (throws with clear messages if misconfigured)
1511
673
  let cfg;
1512
674
  try {
@@ -1516,856 +678,119 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
1516
678
  process.stderr.write(`Config error: ${e?.message || e}\n`);
1517
679
  process.exit(1);
1518
680
  }
1519
-
681
+
1520
682
  logger.info("cli.tcp.control_plane.establish", {});
1521
683
  process.stdout.write(`🔐 Negotiating control-plane security…\n`);
1522
684
 
1523
- // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
1524
- const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
1525
-
1526
- // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
1527
- const port = 443;
1528
- const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
1529
-
1530
- // Load certificates for MQTT TLS options
1531
- const ca = readFileSync(cfg.caPath);
1532
- const cert = readFileSync(cfg.certPath);
1533
- const key = readFileSync(cfg.keyPath);
1534
-
1535
- // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
1536
- const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
1537
-
1538
- // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
1539
- const baseClientId = cfg.clientId;
1540
-
1541
- // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect (must be before MqttControlPlaneClient)
1542
- const instanceIdRef = { instanceId: null };
1543
-
1544
- // TPB-17: Store coordinator references for onRefreshLease callback
1545
- let coordinatorCoreRef = null;
1546
- let coordinatorIngressRef = null;
1547
- let deviceIdRef = cfg.clientId;
1548
- let localPortRef = localPort;
1549
- // Track subscription state to ensure refresh requests wait for subscription to be active
1550
- let subscriptionReadyRef = { ready: false };
1551
-
1552
- // 2) Build MqttControlPlaneClient for connection management
1553
- const mqttClient = new MqttControlPlaneClient({
1554
- url: mqttUrl,
1555
- baseClientId,
1556
- mqttOptions: {
1557
- protocol: 'mqtts',
1558
- port: 443,
1559
- cert,
1560
- key,
1561
- ca,
1562
- rejectUnauthorized: true,
1563
- keepalive,
1564
- connectTimeout: 8000,
1565
- // ALPN for port 443 (AWS IoT)
1566
- ALPNProtocols: ['x-amzn-mqtt-ca'],
1567
- },
1568
- mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
685
+ // Story 12.1 (step 2b): the TCP flow lives in @asyx/tunnel-core; the CLI prints its events and
686
+ // maps its error codes to the same messages and exit codes as before.
687
+ const { createTcpTunnel } = await import("#tunnel-core/flows/tcp.js");
688
+ const handle = createTcpTunnel({
689
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
690
+ localPort,
691
+ target,
692
+ serviceName,
693
+ kind,
694
+ requestedExternalPort,
1569
695
  logger,
1570
- onConnected: async (mqttClientInstance) => {
1571
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1572
- const newClientId = mqttClient.getClientId();
1573
- logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
1574
-
1575
- // TPB-12: Update instance registry if clientId changed on reconnect
1576
- if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
1577
- const oldInstanceId = instanceIdRef.instanceId;
1578
- logger.debug("cli.instance.clientid_rotated", {
1579
- oldInstanceId,
1580
- newInstanceId: newClientId,
1581
- tunnelType: 'tcp'
1582
- });
1583
-
1584
- // Unregister old instance and register new one
1585
- const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
1586
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
1587
-
1588
- // Get old instance context to preserve metadata
1589
- const oldContext = getInstance(oldInstanceId);
1590
- if (oldContext) {
1591
- // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
1592
- const preservedRequestId = oldContext.expectedRequestId;
1593
-
1594
- // Register new instance FIRST (before unregistering old) to ensure routing works
1595
- registerInstance(newClientId, {
1596
- tunnelType: 'tcp',
1597
- setAssignment: setAssignmentFn,
1598
- getAssignment: getAssignmentFn,
1599
- metadata: oldContext.metadata || { baseClientId, localPort, serviceName, kind, requestedExternalPort }
1600
- });
1601
-
1602
- // Migrate expectedRequestId to new instance (preserves in-flight refresh/reconnect)
1603
- if (preservedRequestId) {
1604
- const { setExpectedRequestId } = await import("../state/instance-registry.js");
1605
- setExpectedRequestId(newClientId, preservedRequestId);
1606
- logger.debug("cli.instance.expected_requestid_migrated", {
1607
- oldInstanceId,
1608
- newInstanceId: newClientId,
1609
- requestId: preservedRequestId,
1610
- tunnelType: 'tcp'
1611
- });
1612
- }
1613
-
1614
- // Now unregister old instance (this will clean up old expectedRequestId mapping)
1615
- unregisterInstance(oldInstanceId);
1616
-
1617
- const migration = migrateInstanceAssignment({
1618
- oldId: oldInstanceId,
1619
- newId: newClientId,
1620
- });
1621
- if (migration.moved) {
1622
- logger.debug("cli.instance.assignment_migrated", {
1623
- oldInstanceId,
1624
- newInstanceId: newClientId,
1625
- leaseId: migration.leaseId,
1626
- tunnelType: 'tcp',
1627
- assignmentCount: migration.size,
1628
- });
1629
- }
1630
-
1631
- logger.debug("cli.instance.reregistered", {
1632
- oldInstanceId,
1633
- newInstanceId: newClientId,
1634
- tunnelType: 'tcp'
1635
- });
1636
- }
1637
-
1638
- // Update instanceId ref
1639
- instanceIdRef.instanceId = newClientId;
1640
- }
1641
-
1642
- process.stdout.write("✅ Control-plane sealed\n");
1643
-
1644
- // Resubscribe to topics on reconnect
1645
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1646
- try {
1647
- await mqttClient.subscribe(evtWildcard, 0);
1648
- logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
1649
- } catch (e) {
1650
- logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
1651
- }
1652
- },
1653
- onFatalError: (reason, err) => {
1654
- logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
1655
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
1656
- process.exit(1);
1657
- },
1658
- // TPB-17: TCP refresh callback (control-plane only, no data-plane reauth)
1659
- onRefreshLease: async () => {
1660
- if (!coordinatorCoreRef || !coordinatorIngressRef) {
1661
- throw new Error("Coordinator not available for refresh");
1662
- }
1663
-
1664
- // TPB-12: Get instanceId from mqttClient (captured in closure)
1665
- const refreshInstanceId = mqttClient.getClientId();
1666
-
1667
- const { getAssignment } = await import('../state/assignment.js');
1668
- const { getFpHash } = await import('../lib/fingerprint.js');
1669
-
1670
- // TPB-12: Get assignment for this specific instance
1671
- const currentAssignment = getAssignment(refreshInstanceId);
1672
- if (!currentAssignment) {
1673
- throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
696
+ onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
697
+ });
698
+ // QPA-CLI-11: Vault UX messaging - Control-plane sealed
699
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
700
+ handle.on('control-fatal', ({ reason }) => {
701
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
702
+ process.exit(1);
703
+ });
704
+ handle.on('closed', ({ error }) => {
705
+ if (!error) return;
706
+ if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
707
+ // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
708
+ if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
709
+ if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
710
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
711
+ process.exit(1);
712
+ });
713
+ // TCP-S3 / E3-S8: where the server is reachable, printed when the assignment arrives
714
+ handle.on('assigned', ({ tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed }) => {
715
+ if (tcpAliasFqdn) {
716
+ process.stdout.write(`Your TCP server is available at:\n\n`);
717
+ process.stdout.write(` ${tcpAliasFqdn}\n`);
718
+ process.stdout.write(` or\n`);
719
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
720
+ if (srvProvisioned && srvFqdn) {
721
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
1674
722
  }
723
+ } else if (srvProvisioned && srvFqdn) {
724
+ process.stdout.write(`Your TCP server is available at:\n\n`);
725
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
726
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
727
+ } else if (aliasRequestedButFailed) {
728
+ process.stdout.write(`Your TCP server is available at:\n\n`);
729
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
730
+ process.stdout.write(` (alias unavailable; using host:port only)\n`);
731
+ } else {
732
+ process.stdout.write(`Your TCP server is available at:\n\n`);
733
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
734
+ }
735
+ });
1675
736
 
1676
- const leaseId = currentAssignment.leaseId;
1677
- if (!leaseId) {
1678
- throw new Error("No leaseId in current assignment");
1679
- }
737
+ try {
738
+ await handle.open();
739
+ } catch (error) {
740
+ const d = error.details || {};
741
+ switch (error.code) {
742
+ case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
743
+ case 'tcp_port_out_of_block': process.stderr.write(`Requested external port ${d.requestedPort} is outside your assigned block ${d.blockStart}–${d.blockEnd}.\n`); break;
744
+ case 'tcp_port_already_in_use': process.stderr.write(`External port ${d.requestedPort} is already in use by another active tunnel.\n`); break;
745
+ case 'tcp_port_block_exhausted_for_tenant':
746
+ case 'tcp_port_block_exhausted': process.stderr.write(`All 10 ports in your block ${d.blockStart}–${d.blockEnd} are currently in use.\n`); break;
747
+ case 'tcp_port_capacity_exhausted': process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`); break;
748
+ case 'tenant_tcp_lease_limit_reached': process.stderr.write(`Tenant TCP lease limit reached on relay ${d.relayId}\n`); break;
749
+ case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
750
+ case 'tunnel_connect_failed': break; // TCP has always exited here without a message
751
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
752
+ }
753
+ process.exit(1);
754
+ }
755
+ const assignment = handle.assignment;
1680
756
 
1681
- // Build refresh payload
1682
- const refreshRequestId = `refresh-${Date.now()}`;
1683
- const fingerprint = await getFpHash(deviceIdRef);
1684
-
1685
- // TPB-17: Include instanceId and proto:"tcp" in refresh payload
1686
- const refreshPayload = {
1687
- requestId: refreshRequestId,
1688
- instanceId: refreshInstanceId, // TPB-12: Per-instance routing
1689
- refreshOf: leaseId,
1690
- proto: 'tcp', // TPB-17: TCP protocol identifier
1691
- localPort: localPortRef,
1692
- clientId: deviceIdRef,
1693
- ...fingerprint
1694
- };
1695
-
1696
- // Cancel any existing awaiters for this leaseId before starting a new refresh
1697
- const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
1698
- const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
1699
- try {
1700
- const testMessage = {
1701
- topic: ackTopic,
1702
- payload: { type: 'open_ack', requestId: 'test' }
1703
- };
1704
- return awaiter.criteria(testMessage);
1705
- } catch {
1706
- return false;
1707
- }
1708
- });
1709
-
1710
- if (cancelled > 0) {
1711
- logger.debug('jwt.refresh.awaiter.cancelled_stale', {
1712
- refreshRequestId,
1713
- cancelledCount: cancelled,
1714
- reason: 'new_refresh_starting'
1715
- });
1716
- }
757
+ process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
758
+ process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
759
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
760
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
761
+ if (logLevel === 'info' || logLevel === 'debug') {
762
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
763
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
764
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
765
+ }
766
+ process.stdout.write(` Press Ctrl+C to stop\n`);
1717
767
 
1718
- // Wait for subscription to be ready before publishing
1719
- if (!subscriptionReadyRef.ready) {
1720
- logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
1721
- const maxWait = 2000;
1722
- const startWait = Date.now();
1723
- while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
1724
- await new Promise(resolve => setTimeout(resolve, 50));
1725
- }
1726
- if (!subscriptionReadyRef.ready) {
1727
- logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
1728
- } else {
1729
- logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
1730
- }
1731
- }
768
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
769
+ let shuttingDown = false;
770
+ const onSig = async (sig) => {
771
+ if (shuttingDown) return;
772
+ shuttingDown = true;
773
+ logger.info("cli.signal.shutdown", { sig });
774
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
775
+ const killer = setTimeout(() => {
776
+ logger.error("tunnel.close.timeout", {});
777
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
778
+ process.exit(0);
779
+ }, 3000);
780
+ try {
781
+ await handle.close();
782
+ } catch (e) {
783
+ logger.debug('tunnel.shutdown.error', { error: e.message });
784
+ }
785
+ clearTimeout(killer);
786
+ process.exit(0);
787
+ };
788
+ process.once("SIGINT", onSig);
789
+ process.once("SIGTERM", onSig);
1732
790
 
1733
- // Set up topic and wait for ack
1734
- const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
1735
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
1736
-
1737
- logger.debug('jwt.refresh.awaiter.registered', {
1738
- refreshRequestId,
1739
- instanceId: refreshInstanceId,
1740
- tunnelType: 'tcp',
1741
- timeoutMs: ACK_TIMEOUT_MS,
1742
- expectedType: 'open_ack'
1743
- });
1744
-
1745
- const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
1746
- try {
1747
- const parsed = message.payload;
1748
- const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
1749
- const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
1750
-
1751
- if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
1752
- logger.debug('jwt.refresh.awaiter.checking', {
1753
- refreshRequestId,
1754
- receivedRequestId: parsed.requestId,
1755
- receivedType: parsed.type,
1756
- isAck,
1757
- isReject,
1758
- topic: message.topic
1759
- });
1760
- }
1761
-
1762
- // TPB-17: For TCP, refresh failures are non-fatal (tunnel continues until WS closes)
1763
- // But we still throw on lease_closed/REFRESH_REJECTED to let MqttControlPlaneClient handle it
1764
- if (isReject) {
1765
- const reason = parsed.data?.reason || 'unknown';
1766
- if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
1767
- const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
1768
- leaseClosedError.code = 'LEASE_CLOSED';
1769
- leaseClosedError.reason = reason;
1770
- throw leaseClosedError;
1771
- }
1772
- const rejectError = new Error(`Refresh rejected: ${reason}`);
1773
- rejectError.code = 'REFRESH_REJECTED';
1774
- rejectError.reason = reason;
1775
- throw rejectError;
1776
- }
1777
-
1778
- return isAck;
1779
- } catch (e) {
1780
- if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
1781
- throw e;
1782
- }
1783
- logger.debug('jwt.refresh.awaiter.criteria_error', {
1784
- refreshRequestId,
1785
- error: e.message
1786
- });
1787
- return false;
1788
- }
1789
- }, ACK_TIMEOUT_MS);
1790
-
1791
- // Publish refresh request
1792
- const publishSuccess = await publishRefreshRequestWithErrorHandling(
1793
- coordinatorCoreRef,
1794
- cmdOpenTopic,
1795
- refreshPayload,
1796
- refreshRequestId,
1797
- logger
1798
- );
1799
-
1800
- if (publishSuccess === false) {
1801
- const bufferedError = new Error('Connection closed during refresh publish');
1802
- bufferedError.code = 'ECONNRESET';
1803
- throw bufferedError;
1804
- }
1805
-
1806
- // Wait for ack (non-fatal for TCP - tunnel continues on failure)
1807
- let ackResult;
1808
- try {
1809
- ackResult = await ackPromise;
1810
- } catch (error) {
1811
- // TPB-17: For TCP, refresh failures are non-fatal
1812
- // Log and return null to indicate refresh failed, but don't throw
1813
- // The tunnel will continue until WebSocket closes naturally
1814
- if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
1815
- logger.warn('tcp.refresh.rejected', {
1816
- reason: error.reason || 'unknown',
1817
- requestId: refreshRequestId,
1818
- action: 'non_fatal_continue'
1819
- });
1820
- // Return null to indicate refresh failed, but don't throw (non-fatal)
1821
- return null;
1822
- }
1823
-
1824
- // Timeout or other errors - also non-fatal for TCP
1825
- logger.warn('tcp.refresh.timeout', {
1826
- error: error.message,
1827
- requestId: refreshRequestId,
1828
- action: 'non_fatal_continue'
1829
- });
1830
- return null;
1831
- }
1832
-
1833
- // Get new assignment (updated by open_ack handler)
1834
- const newAssignment = getAssignment(refreshInstanceId);
1835
- if (!newAssignment) {
1836
- logger.warn('tcp.refresh.no_assignment', { requestId: refreshRequestId });
1837
- return null;
1838
- }
1839
-
1840
- // Extract expiration from new JWT
1841
- const newJwt = newAssignment.jwt;
1842
- const parts = newJwt.split('.');
1843
- if (parts.length !== 3) {
1844
- logger.warn('tcp.refresh.invalid_jwt', { requestId: refreshRequestId });
1845
- return null;
1846
- }
1847
-
1848
- const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
1849
- const expMs = payload.exp ? payload.exp * 1000 : null;
1850
-
1851
- if (!expMs) {
1852
- logger.warn('tcp.refresh.no_exp', { requestId: refreshRequestId });
1853
- return null;
1854
- }
1855
-
1856
- // TPB-17: TCP refresh updates assignment/JWT for reconnect use
1857
- // No data-plane reauth needed (TCP uses TCP-v1 framing, not WebSocket auth)
1858
- // The assignment is already updated by the open_ack handler
1859
- logger.debug('tcp.refresh.success', {
1860
- leaseId: newAssignment.leaseId,
1861
- expMs,
1862
- requestId: refreshRequestId
1863
- });
1864
-
1865
- return expMs;
1866
- },
1867
- });
1868
-
1869
- // Create Transport adapter and MqttCore
1870
- const transport = new MqttControlPlaneTransport(mqttClient);
1871
- const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
1872
-
1873
- // CLI-IMG-ControlPlane-Watchdog: Expose helpers for TcpTunnel compatibility
1874
- const isControlPlaneConnected = () => {
1875
- return mqttClient.isOnline();
1876
- };
1877
-
1878
- const waitForControlPlane = () => {
1879
- if (mqttClient.isOnline()) {
1880
- return Promise.resolve();
1881
- }
1882
- // Poll until connected or timeout
1883
- const start = Date.now();
1884
- return new Promise((resolve, reject) => {
1885
- const interval = setInterval(() => {
1886
- if (mqttClient.isOnline()) {
1887
- clearInterval(interval);
1888
- resolve();
1889
- } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
1890
- clearInterval(interval);
1891
- reject(new Error('control_plane_timeout'));
1892
- }
1893
- }, 250);
1894
- });
1895
- };
1896
-
1897
- // QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
1898
- const getLastMqttError = () => {
1899
- // TODO: Add getLastMqttError to MqttControlPlaneClient if needed
1900
- return null;
1901
- };
1902
-
1903
- // QPA-CLI-03: Expose helper to force reconnect
1904
- const getForceReconnect = () => {
1905
- // MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
1906
- return async () => {
1907
- if (!mqttClient.isOnline()) {
1908
- await mqttClient.disconnect();
1909
- await mqttClient.connect();
1910
- }
1911
- };
1912
- };
1913
-
1914
- // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
1915
- const tunnelInstanceRef = { tunnel: null };
1916
-
1917
- // 3) Connect to control plane
1918
- try {
1919
- await mqttClient.connect();
1920
- } catch (e) {
1921
- logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
1922
- process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
1923
- process.exit(1);
1924
- }
1925
-
1926
- // TPB-12: Get instanceId (full MQTT clientId) after connection
1927
- instanceIdRef.instanceId = mqttClient.getClientId();
1928
- const instanceId = instanceIdRef.instanceId; // Use const for current scope, but update ref on reconnect
1929
- logger.debug("cli.instance.registered", { instanceId, tunnelType: 'tcp', baseClientId });
1930
-
1931
- // 4) Set up topics and message handling
1932
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1933
- const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
1934
- const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
1935
-
1936
- // Subscribe to topics after initial connect
1937
- await core.subscribe(evtWildcard, 0);
1938
-
1939
- // 5) Set up message ingress and dispatcher
1940
- const ingress = new MessageIngress({
1941
- maxAwaiters: 100,
1942
- observability: process.env.ASYX_DEBUG === '1',
1943
- logger
1944
- });
1945
-
1946
- ingress.setDispatcher(dispatchEvt);
1947
-
1948
- // TPB-12: Register instance in registry with per-instance callbacks
1949
- const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
1950
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1951
-
1952
- registerInstance(instanceId, {
1953
- tunnelType: 'tcp',
1954
- setAssignment: setAssignmentFn,
1955
- getAssignment: getAssignmentFn,
1956
- metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort }
1957
- });
1958
-
1959
- // TPB-17: Store coordinator references for onRefreshLease callback
1960
- coordinatorCoreRef = core;
1961
- coordinatorIngressRef = ingress;
1962
-
1963
- core.onMessage(async (m) => {
1964
- try {
1965
- await ingress.handleMessage(m);
1966
- } catch (e) {
1967
- if (e && e.code === "SETUP_REQUIRED") {
1968
- process.stderr.write(`❌ ${e.message}\n`);
1969
- try { await core.end(); } catch {}
1970
- process.exit(2);
1971
- }
1972
- if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
1973
- process.stderr.write(`❌ ${e.message}\n`);
1974
- try { await core.end(); } catch {}
1975
- process.exit(1);
1976
- }
1977
- process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
1978
- try { await core.end(); } catch {}
1979
- process.exit(1);
1980
- }
1981
- });
1982
-
1983
- // 6) Publish cmd/open request with TCP protocol
1984
- const requestId = crypto.randomUUID();
1985
- const { getFpHash } = await import("../lib/fingerprint.js");
1986
- const fingerprint = await getFpHash(cfg.clientId);
1987
-
1988
- // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
1989
- setExpectedRequestId(instanceId, requestId);
1990
-
1991
- // TCP-S2: Build TCP cmd/open payload
1992
- // E3-S8: Include kind field if provided
1993
- // TPB-12: Include instanceId for per-instance routing
1994
- const openPayload = {
1995
- requestId,
1996
- instanceId, // TPB-12: Per-instance routing
1997
- proto: 'tcp', // Protocol identifier
1998
- target: target, // "127.0.0.1:<port>" from TCP-S1
1999
- clientId: cfg.clientId,
2000
- ...fingerprint
2001
- };
2002
-
2003
- // TCP-S2: Include optional opts.name if service name provided
2004
- // E3-S8: Include opts.kind if provided
2005
- // TPB-03B: Include requestedExternalPort if provided
2006
- openPayload.opts = {
2007
- preferredPort: null // Can be wired to a flag later if needed
2008
- };
2009
-
2010
- if (serviceName) {
2011
- openPayload.opts.name = serviceName;
2012
- }
2013
-
2014
- if (kind) {
2015
- openPayload.opts.kind = kind;
2016
- }
2017
-
2018
- // TPB-03B: Include requestedExternalPort in opts (null if omitted)
2019
- if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
2020
- openPayload.opts.requestedExternalPort = requestedExternalPort;
2021
- }
2022
-
2023
- // Publish the open request
2024
- await core.publish({
2025
- topic: cmdOpenTopic,
2026
- payload: JSON.stringify(openPayload),
2027
- qos: 1,
2028
- retain: false
2029
- });
2030
-
2031
- logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
2032
-
2033
- // 7) Wait for ack and assignment
2034
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
2035
-
2036
- try {
2037
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
2038
- logger.info("cli.ack.wait.start", { requestId });
2039
- const assignment = await assignmentPromise;
2040
- logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'tcp' });
2041
- logger.info("cli.assignment.received", {
2042
- relayId: assignment.relayId,
2043
- leaseId: assignment.leaseId,
2044
- instanceId,
2045
- tunnelType: 'tcp',
2046
- tcpAliasFqdn: assignment.tcpAliasFqdn,
2047
- publicPort: assignment.publicPort
2048
- });
2049
-
2050
- // TPB-12: Persist assignment using per-instance store
2051
- try {
2052
- const { setAssignment } = await import("../state/assignment.js");
2053
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2054
- setAssignment(instanceId, assignment);
2055
- // Clear expected requestId now that assignment exists (routing will use leaseId after this)
2056
- clearExpectedRequestId(instanceId);
2057
- } catch {}
2058
-
2059
- // TCP-S3: Handle warnings array (alias unavailable)
2060
- const warnings = assignment.warnings || [];
2061
- if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
2062
- logger.warn('tcp.alias.unavailable', {
2063
- requestId,
2064
- fqdn: assignment.fqdn,
2065
- publicPort: assignment.publicPort
2066
- });
2067
- }
2068
-
2069
- // TCP-S3: Build and display UX based on alias and SRV presence
2070
- // E3-S8: Check for SRV status for Minecraft tunnels
2071
- const tcpAliasFqdn = assignment.tcpAliasFqdn;
2072
- const srvProvisioned = assignment.srvProvisioned === true;
2073
- const srvFqdn = assignment.srvFqdn || null;
2074
- const fqdn = assignment.fqdn;
2075
- const publicPort = assignment.publicPort;
2076
- const aliasRequestedButFailed = warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE');
2077
-
2078
- if (tcpAliasFqdn) {
2079
- // Alias present: show both alias and host:port
2080
- process.stdout.write(`Your TCP server is available at:\n\n`);
2081
- process.stdout.write(` ${tcpAliasFqdn}\n`);
2082
- process.stdout.write(` or\n`);
2083
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
2084
- // E3-S8: Show SRV info if available
2085
- if (srvProvisioned && srvFqdn) {
2086
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
2087
- }
2088
- } else if (srvProvisioned && srvFqdn) {
2089
- // E3-S8: SRV available but no alias (Minecraft without --name)
2090
- process.stdout.write(`Your TCP server is available at:\n\n`);
2091
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
2092
- process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
2093
- } else if (aliasRequestedButFailed) {
2094
- // User requested alias (--name) but provisioning failed
2095
- process.stdout.write(`Your TCP server is available at:\n\n`);
2096
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
2097
- process.stdout.write(` (alias unavailable; using host:port only)\n`);
2098
- } else {
2099
- // No alias requested, no SRV: just show host:port (normal case for plain --tcp)
2100
- process.stdout.write(`Your TCP server is available at:\n\n`);
2101
- process.stdout.write(` ${fqdn}:${publicPort}\n`);
2102
- }
2103
-
2104
- // TCP-S3: Log alias readiness if previously null alias becomes non-null
2105
- // (This would require tracking previous assignment state, but for now we just log current state)
2106
- if (tcpAliasFqdn) {
2107
- logger.debug('tcp.alias.ready', {
2108
- requestId,
2109
- tcpAliasFqdn,
2110
- fqdn,
2111
- publicPort
2112
- });
2113
- }
2114
-
2115
-
2116
- // Story 10.9: if the relay refuses this assignment on a reconnect (the tenant was moved to
2117
- // another relay, so the token's relay no longer matches), open again for the same public
2118
- // port; the control plane places the new lease on the tenant's current relay.
2119
- const reassignSamePort = async () => {
2120
- const { setAssignment: setA, getAssignment: getA } = await import("../state/assignment.js");
2121
- const cur = getA(instanceIdRef.instanceId) || assignment;
2122
- const rid = crypto.randomUUID();
2123
- const again = { ...openPayload, requestId: rid, opts: { ...(openPayload.opts || {}), requestedExternalPort: cur.publicPort ?? assignment.publicPort } };
2124
- setExpectedRequestId(instanceIdRef.instanceId, rid);
2125
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
2126
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
2127
- setA(instanceIdRef.instanceId, next);
2128
- logger.info("tcp.reassign.ok", { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
2129
- return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
2130
- };
2131
-
2132
- // TCP-S4: Connect to relay using TcpTunnel for data-plane readiness
2133
- await connectToRelayTcp(
2134
- assignment,
2135
- cfg.clientId,
2136
- localPort,
2137
- core,
2138
- ingress,
2139
- { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
2140
- tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here
2141
- mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
2142
- reassignSamePort
2143
- );
2144
-
2145
- } catch (error) {
2146
- // TCP-S3: Handle Coordinator error codes distinctly
2147
- // TPB-03B: Handle new port block error codes
2148
- const errorCode = error.code || error.reason || error.data?.reason;
2149
-
2150
- // TPB-03B: TCP_PORT_OUT_OF_BLOCK
2151
- if (errorCode === 'TCP_PORT_OUT_OF_BLOCK' || errorCode === 'tcp_port_out_of_block') {
2152
- const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
2153
- const blockStart = error.blockStart || error.data?.blockStart || 'A';
2154
- const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
2155
- logger.error("cli.tcp.error.port_out_of_block", {
2156
- error: error.message,
2157
- requestedPort,
2158
- blockStart,
2159
- blockEnd
2160
- });
2161
- process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
2162
- try { await core.end(); } catch {}
2163
- process.exit(1);
2164
- }
2165
-
2166
- // TPB-03B: TCP_PORT_ALREADY_IN_USE
2167
- if (errorCode === 'TCP_PORT_ALREADY_IN_USE' || errorCode === 'tcp_port_already_in_use') {
2168
- const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
2169
- logger.error("cli.tcp.error.port_already_in_use", { error: error.message, requestedPort });
2170
- process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
2171
- try { await core.end(); } catch {}
2172
- process.exit(1);
2173
- }
2174
-
2175
- // TPB-03B: TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT
2176
- if (errorCode === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || errorCode === 'tcp_port_block_exhausted_for_tenant' ||
2177
- errorCode === 'TCP_PORT_BLOCK_EXHAUSTED' || errorCode === 'tcp_port_block_exhausted') {
2178
- const blockStart = error.blockStart || error.data?.blockStart || 'A';
2179
- const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
2180
- logger.error("cli.tcp.error.block_exhausted", { error: error.message, blockStart, blockEnd });
2181
- process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
2182
- try { await core.end(); } catch {}
2183
- process.exit(1);
2184
- }
2185
-
2186
- if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
2187
- logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
2188
- process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
2189
- try { await core.end(); } catch {}
2190
- process.exit(1);
2191
- }
2192
-
2193
- if (errorCode === 'TENANT_TCP_LEASE_LIMIT_REACHED' || errorCode === 'tenant_tcp_lease_limit_reached') {
2194
- const relayId = error.relayId || error.data?.relayId || 'unknown';
2195
- logger.error("cli.tcp.error.lease_limit", { error: error.message, relayId });
2196
- process.stderr.write(`Tenant TCP lease limit reached on relay ${relayId}\n`);
2197
- try { await core.end(); } catch {}
2198
- process.exit(1);
2199
- }
2200
-
2201
- // TCP_ALIAS_UNAVAILABLE is handled as a warning, not an error
2202
-
2203
- // Generic error handling
2204
- logger.error("cli.ack.wait.failed", { error: error.message, errorCode, instanceId, tunnelType: 'tcp' });
2205
- // TPB-12: Clean up expected requestId on timeout/error (prevents map leak)
2206
- try {
2207
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2208
- clearExpectedRequestId(instanceId);
2209
- } catch (err) {
2210
- // Ignore cleanup errors
2211
- }
2212
- process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
2213
- try { await core.end(); } catch {}
2214
- process.exit(1);
2215
- }
2216
- }
2217
-
2218
- export async function connectToRelayTcp(
2219
- assignment,
2220
- deviceId,
2221
- localPort,
2222
- coordinatorCore,
2223
- coordinatorIngress,
2224
- controlPlaneHelpers,
2225
- tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
2226
- mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
2227
- reassign = null // Story 10.9: new assignment after a relay refuses the old one
2228
- ) {
2229
- // Import TCP tunnel logic
2230
- const { TcpTunnel } = await import("../tunnel/tcp-tunnel.js");
2231
- const { getAssignment: getStoredAssignment } = await import("../state/assignment.js");
2232
-
2233
- const tunnel = new TcpTunnel({
2234
- relayUrl: assignment.relayUrl,
2235
- jwt: assignment.jwt, // Use JWT as-is (no validation)
2236
- // Story 11.2: reconnects use the newest token (kept fresh by the TPB-17 refresh)
2237
- getJwt: () => (mqttClient ? getStoredAssignment(mqttClient.getClientId())?.jwt : null) || null,
2238
- reassign,
2239
- deviceId,
2240
- requestId: assignment.requestId,
2241
- localPort,
2242
- leaseId: assignment.leaseId, // E3-S3: Pass leaseId for TCP relay WebSocket query parameters
2243
- coordinatorCore, // CLI-IMG-WSReconnect: Pass coordinator connection for JWT refresh (not used for TCP yet)
2244
- coordinatorIngress, // CLI-IMG-WSReconnect: Pass coordinator ingress for JWT refresh (not used for TCP yet)
2245
- // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
2246
- isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
2247
- waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
2248
- getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
2249
- getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
2250
- controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
2251
- log: {
2252
- info: (msgOrFields, maybeFields) => {
2253
- if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
2254
- return logger.info(maybeFields, msgOrFields);
2255
- },
2256
- warn: (msgOrFields, maybeFields) => {
2257
- if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
2258
- return logger.warn(maybeFields, msgOrFields);
2259
- },
2260
- error: (msgOrFields, maybeFields) => {
2261
- if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
2262
- return logger.error(maybeFields, msgOrFields);
2263
- },
2264
- debug: (msgOrFields, maybeFields) => {
2265
- if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
2266
- return logger.debug(maybeFields, msgOrFields);
2267
- }
2268
- }
2269
- });
2270
-
2271
- // QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
2272
- if (tunnelInstanceRef) {
2273
- tunnelInstanceRef.tunnel = tunnel;
2274
- }
2275
-
2276
- try {
2277
- await tunnel.open();
2278
-
2279
- // TPB-17: Schedule initial proactive refresh via MqttControlPlaneClient for TCP
2280
- if (mqttClient && assignment.jwt && assignment.leaseId) {
2281
- try {
2282
- // Decode JWT to get expiration timestamp (assignment doesn't store exp, must decode JWT)
2283
- const parts = assignment.jwt.split('.');
2284
- if (parts.length === 3) {
2285
- const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
2286
- const expMs = payload.exp ? payload.exp * 1000 : null;
2287
- if (expMs) {
2288
- mqttClient.scheduleRefresh(expMs, assignment.leaseId);
2289
- logger.debug('tcp.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
2290
- } else {
2291
- logger.warn('tcp.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
2292
- }
2293
- } else {
2294
- logger.warn('tcp.refresh.initial_failed', { reason: 'invalid_jwt_format' });
2295
- }
2296
- } catch (error) {
2297
- logger.warn('tcp.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
2298
- }
2299
- }
2300
-
2301
- // TCP-S4: Log tunnel active
2302
- logger.info("tunnel.active", {
2303
- target: `tcp://127.0.0.1:${localPort}`,
2304
- relayId: assignment.relayId,
2305
- leaseMs: assignment.leaseMs
2306
- });
2307
-
2308
- // Tunnel live message
2309
- process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
2310
- process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
2311
-
2312
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
2313
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
2314
- if (logLevel === 'info' || logLevel === 'debug') {
2315
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
2316
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
2317
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
2318
- }
2319
-
2320
- process.stdout.write(` Press Ctrl+C to stop\n`);
2321
-
2322
- // CLI-IMG-WSReconnect: Set up graceful shutdown
2323
- let shuttingDown = false;
2324
- const onSig = async (sig) => {
2325
- if (shuttingDown) return;
2326
- shuttingDown = true;
2327
- logger.info("cli.signal.shutdown", { sig });
2328
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
2329
-
2330
- const killer = setTimeout(() => {
2331
- logger.error("tunnel.close.timeout", {});
2332
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
2333
- process.exit(0);
2334
- }, 3000);
2335
-
2336
- try {
2337
- // TCP-S4: Close tunnel and all active streams
2338
- tunnel.close();
2339
- await mqttClient.disconnect();
2340
- } catch (e) {
2341
- logger.debug('tunnel.shutdown.error', { error: e.message });
2342
- }
2343
-
2344
- clearTimeout(killer);
2345
- process.exit(0);
2346
- };
2347
-
2348
- process.once("SIGINT", onSig);
2349
- process.once("SIGTERM", onSig);
2350
-
2351
- // Keep process alive until SIGINT/SIGTERM
2352
- await new Promise(() => {});
2353
-
2354
- } catch (error) {
2355
- logger.error("tunnel.open.failed", { error: error.message });
2356
- try {
2357
- tunnel.close();
2358
- } catch (e) {
2359
- logger.debug('tunnel.close.error', { error: e.message });
2360
- }
2361
- try {
2362
- await mqttClient.disconnect();
2363
- } catch (e) {
2364
- logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
2365
- }
2366
- process.exit(1);
2367
- }
2368
- }
791
+ // Keep process alive until SIGINT/SIGTERM
792
+ await new Promise(() => {});
793
+ }
2369
794
 
2370
795
  /**
2371
796
  * UDP tunnel implementation (UDP-S1: CLI – UDP entrypoint & WS connect).
@@ -2379,18 +804,13 @@ export async function connectToRelayTcp(
2379
804
  async function udpTunnel(targetPort, requestedExternalPort = null, targetHost = '127.0.0.1') {
2380
805
  logger.info('cli.udp.start', { targetPort, requestedExternalPort, targetHost });
2381
806
  process.stdout.write(`⚙️ Initializing UDP tunnel to ${targetHost}:${targetPort}…\n`);
2382
-
807
+
2383
808
  // UDP-S13: --port is targetPort, not a port we bind to
2384
809
  logger.info('cli.udp.target', { target: `${targetHost}:${targetPort}` });
2385
-
2386
- // 0) Imports (kept local to this command to avoid global side-effects)
810
+
2387
811
  const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
2388
- const { MqttCore } = await import("@asyx/mqtt-core");
2389
- const { waitForAssignment } = await import("../state/assignment.js");
2390
- const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
2391
- const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
2392
812
  const { readFileSync } = await import("node:fs");
2393
-
813
+
2394
814
  // 1) Load IoT config (throws with clear messages if misconfigured)
2395
815
  let cfg;
2396
816
  try {
@@ -2400,666 +820,100 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
2400
820
  process.stderr.write(`Config error: ${e?.message || e}\n`);
2401
821
  process.exit(1);
2402
822
  }
2403
-
823
+
2404
824
  logger.info("cli.udp.control_plane.establish", {});
2405
825
  process.stdout.write(`🔐 Negotiating control-plane security…\n`);
2406
826
 
2407
- // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
2408
- const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
2409
-
2410
- // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
2411
- const port = 443;
2412
- const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
2413
-
2414
- // Load certificates for MQTT TLS options
2415
- const ca = readFileSync(cfg.caPath);
2416
- const cert = readFileSync(cfg.certPath);
2417
- const key = readFileSync(cfg.keyPath);
2418
-
2419
- // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
2420
- const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
2421
-
2422
- // CLI-MQTT-UniqueID-CleanSession: Use base client ID
2423
- const baseClientId = cfg.clientId;
2424
-
2425
- // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect
2426
- const instanceIdRef = { instanceId: null };
2427
-
2428
- // UDP-S1: Store coordinator references (not used for refresh yet, but kept for consistency)
2429
- let coordinatorCoreRef = null;
2430
- let coordinatorIngressRef = null;
2431
- let deviceIdRef = cfg.clientId;
2432
- let targetPortRef = targetPort; // UDP-S13: Use targetPort instead of localPort
2433
- let targetHostRef = targetHost; // UDP-S13: Store targetHost reference
2434
- // Track subscription state
2435
- let subscriptionReadyRef = { ready: false };
2436
-
2437
- // 2) Build MqttControlPlaneClient for connection management
2438
- const mqttClient = new MqttControlPlaneClient({
2439
- url: mqttUrl,
2440
- baseClientId,
2441
- mqttOptions: {
2442
- protocol: 'mqtts',
2443
- port: 443,
2444
- cert,
2445
- key,
2446
- ca,
2447
- rejectUnauthorized: true,
2448
- keepalive,
2449
- connectTimeout: 8000,
2450
- // ALPN for port 443 (AWS IoT)
2451
- ALPNProtocols: ['x-amzn-mqtt-ca'],
2452
- },
2453
- mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
827
+ // Story 12.1 (step 2b): the UDP flow lives in @asyx/tunnel-core; the CLI prints its events and
828
+ // maps its error codes to the same messages and exit codes as before.
829
+ const { createUdpTunnel } = await import("#tunnel-core/flows/udp.js");
830
+ const handle = createUdpTunnel({
831
+ credentials: { endpoint: cfg.endpoint, clientId: cfg.clientId, ca: readFileSync(cfg.caPath), cert: readFileSync(cfg.certPath), key: readFileSync(cfg.keyPath) },
832
+ targetPort,
833
+ targetHost,
834
+ requestedExternalPort,
2454
835
  logger,
2455
- onConnected: async (mqttClientInstance) => {
2456
- const newClientId = mqttClient.getClientId();
2457
- logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
2458
-
2459
- // TPB-12: Update instance registry if clientId changed on reconnect
2460
- if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
2461
- const oldInstanceId = instanceIdRef.instanceId;
2462
- logger.debug("cli.instance.clientid_rotated", {
2463
- oldInstanceId,
2464
- newInstanceId: newClientId,
2465
- tunnelType: 'udp'
2466
- });
2467
-
2468
- // Unregister old instance and register new one (similar to TCP/HTTP)
2469
- const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
2470
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
2471
-
2472
- const oldContext = getInstance(oldInstanceId);
2473
- if (oldContext) {
2474
- const preservedRequestId = oldContext.expectedRequestId;
2475
-
2476
- registerInstance(newClientId, {
2477
- tunnelType: 'udp',
2478
- setAssignment: setAssignmentFn,
2479
- getAssignment: getAssignmentFn,
2480
- metadata: oldContext.metadata || { baseClientId, targetPort, targetHost, requestedExternalPort }
2481
- });
2482
-
2483
- if (preservedRequestId) {
2484
- const { setExpectedRequestId } = await import("../state/instance-registry.js");
2485
- setExpectedRequestId(newClientId, preservedRequestId);
2486
- }
2487
-
2488
- unregisterInstance(oldInstanceId);
2489
-
2490
- const migration = migrateInstanceAssignment({
2491
- oldId: oldInstanceId,
2492
- newId: newClientId,
2493
- });
2494
- if (migration.moved) {
2495
- logger.debug("cli.instance.assignment_migrated", {
2496
- oldInstanceId,
2497
- newInstanceId: newClientId,
2498
- leaseId: migration.leaseId,
2499
- tunnelType: 'udp',
2500
- assignmentCount: migration.size,
2501
- });
2502
- }
2503
- }
2504
-
2505
- instanceIdRef.instanceId = newClientId;
2506
- }
2507
-
2508
- process.stdout.write("✅ Control-plane sealed\n");
2509
-
2510
- // Resubscribe to topics on reconnect
2511
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
2512
- subscriptionReadyRef.ready = false;
2513
- try {
2514
- await mqttClient.subscribe(evtWildcard, 0);
2515
- logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
2516
- subscriptionReadyRef.ready = true;
2517
- } catch (e) {
2518
- logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
2519
- subscriptionReadyRef.ready = true;
2520
- }
2521
- },
2522
- onOffline: (reason) => {
2523
- logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
2524
- process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
2525
- subscriptionReadyRef.ready = false;
2526
- },
2527
- onFatalError: (reason, err) => {
2528
- logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
2529
- process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
2530
- process.exit(1);
2531
- },
2532
- // Story 11.2: UDP refresh (control plane UDP-S3), so a reconnect after the first
2533
- // token expires still has a valid token. Same flow as TCP (TPB-17); failures are
2534
- // non-fatal: the open tunnel keeps running.
2535
- onRefreshLease: async () => {
2536
- if (!coordinatorCoreRef || !coordinatorIngressRef) {
2537
- throw new Error("Coordinator not available for refresh");
2538
- }
2539
- const refreshInstanceId = mqttClient.getClientId();
2540
- const { getAssignment } = await import('../state/assignment.js');
2541
- const { getFpHash } = await import('../lib/fingerprint.js');
2542
- const currentAssignment = getAssignment(refreshInstanceId);
2543
- if (!currentAssignment?.leaseId) {
2544
- throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
2545
- }
2546
- const refreshRequestId = `refresh-${Date.now()}`;
2547
- const fingerprint = await getFpHash(deviceIdRef);
2548
- const refreshPayload = {
2549
- requestId: refreshRequestId,
2550
- instanceId: refreshInstanceId,
2551
- refreshOf: currentAssignment.leaseId,
2552
- proto: 'udp',
2553
- protocol: 'udp',
2554
- tunnelMode: 'udpWs-v1',
2555
- targetHost: targetHostRef,
2556
- targetPort: targetPortRef,
2557
- clientId: deviceIdRef,
2558
- ...fingerprint
2559
- };
2560
- const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
2561
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
2562
- const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
2563
- const parsed = message.payload;
2564
- if (parsed && parsed.requestId === refreshRequestId && parsed.type === 'open_reject') {
2565
- const rejectError = new Error(`Refresh rejected: ${parsed.data?.reason || 'unknown'}`);
2566
- rejectError.code = 'REFRESH_REJECTED';
2567
- throw rejectError;
2568
- }
2569
- return !!parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
2570
- }, ACK_TIMEOUT_MS);
2571
- const publishSuccess = await publishRefreshRequestWithErrorHandling(
2572
- coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
2573
- if (publishSuccess === false) {
2574
- const bufferedError = new Error('Connection closed during refresh publish');
2575
- bufferedError.code = 'ECONNRESET';
2576
- throw bufferedError;
2577
- }
2578
- try {
2579
- await ackPromise;
2580
- } catch (error) {
2581
- logger.warn('udp.refresh.failed', { error: error.message, requestId: refreshRequestId, action: 'non_fatal_continue' });
2582
- return null;
2583
- }
2584
- // The open_ack handler stored the new assignment for this instance
2585
- const exp = jwtExpOf(getAssignment(refreshInstanceId)?.jwt);
2586
- if (!exp) {
2587
- logger.warn('udp.refresh.no_exp', { requestId: refreshRequestId });
2588
- return null;
2589
- }
2590
- logger.debug('udp.refresh.success', { leaseId: currentAssignment.leaseId, expMs: exp * 1000, requestId: refreshRequestId });
2591
- return exp * 1000;
2592
- },
836
+ onObserve: (line) => console.log(line), // ASYX_DEBUG=1 ingress lines, printed as before
2593
837
  });
2594
-
2595
- // Create Transport adapter and MqttCore
2596
- const transport = new MqttControlPlaneTransport(mqttClient);
2597
- const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
2598
-
2599
- // CLI-IMG-ControlPlane-Watchdog: Expose helpers
2600
- const isControlPlaneConnected = () => {
2601
- return mqttClient.isOnline();
2602
- };
2603
-
2604
- const waitForControlPlane = () => {
2605
- if (mqttClient.isOnline()) {
2606
- return Promise.resolve();
2607
- }
2608
- const start = Date.now();
2609
- return new Promise((resolve, reject) => {
2610
- const interval = setInterval(() => {
2611
- if (mqttClient.isOnline()) {
2612
- clearInterval(interval);
2613
- resolve();
2614
- } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
2615
- clearInterval(interval);
2616
- reject(new Error('control_plane_timeout'));
2617
- }
2618
- }, 250);
2619
- });
2620
- };
2621
-
2622
- const getLastMqttError = () => {
2623
- return null;
2624
- };
2625
-
2626
- const getForceReconnect = () => {
2627
- return async () => {
2628
- if (!mqttClient.isOnline()) {
2629
- await mqttClient.disconnect();
2630
- await mqttClient.connect();
2631
- }
2632
- };
2633
- };
2634
-
2635
- // UDP-S1: Store tunnel reference for reconnect hook
2636
- const tunnelInstanceRef = { tunnel: null };
2637
-
2638
- // 3) Connect to control plane
2639
- try {
2640
- await mqttClient.connect();
2641
- } catch (e) {
2642
- logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
2643
- process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
838
+ // QPA-CLI-11: Vault UX messaging - Control-plane sealed
839
+ handle.on('control-connected', () => process.stdout.write("✅ Control-plane sealed\n"));
840
+ handle.on('control-offline', ({ reason }) => process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`));
841
+ handle.on('control-fatal', ({ reason }) => {
842
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
2644
843
  process.exit(1);
2645
- }
2646
-
2647
- // TPB-12: Get instanceId (full MQTT clientId) after connection
2648
- instanceIdRef.instanceId = mqttClient.getClientId();
2649
- const instanceId = instanceIdRef.instanceId;
2650
- logger.debug("cli.instance.registered", { instanceId, tunnelType: 'udp', baseClientId });
2651
-
2652
- // 4) Set up topics and message handling
2653
- const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
2654
- const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
2655
- const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
2656
-
2657
- // Subscribe to topics after initial connect
2658
- await core.subscribe(evtWildcard, 0);
2659
- subscriptionReadyRef.ready = true;
2660
-
2661
- // 5) Set up message ingress and dispatcher
2662
- const ingress = new MessageIngress({
2663
- maxAwaiters: 100,
2664
- observability: process.env.ASYX_DEBUG === '1',
2665
- logger
2666
- });
2667
-
2668
- ingress.setDispatcher(dispatchEvt);
2669
-
2670
- // TPB-12: Register instance in registry with per-instance callbacks
2671
- const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
2672
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
2673
-
2674
- registerInstance(instanceId, {
2675
- tunnelType: 'udp',
2676
- setAssignment: setAssignmentFn,
2677
- getAssignment: getAssignmentFn,
2678
- metadata: { baseClientId, targetPort, targetHost, requestedExternalPort }
2679
- });
2680
-
2681
- // UDP-S1: Store coordinator references
2682
- coordinatorCoreRef = core;
2683
- coordinatorIngressRef = ingress;
2684
-
2685
- core.onMessage(async (m) => {
2686
- try {
2687
- await ingress.handleMessage(m);
2688
- } catch (e) {
2689
- if (e && e.code === "SETUP_REQUIRED") {
2690
- process.stderr.write(`❌ ${e.message}\n`);
2691
- try { await core.end(); } catch {}
2692
- process.exit(2);
2693
- }
2694
- if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
2695
- process.stderr.write(`❌ ${e.message}\n`);
2696
- try { await core.end(); } catch {}
2697
- process.exit(1);
2698
- }
2699
- process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
2700
- try { await core.end(); } catch {}
2701
- process.exit(1);
2702
- }
2703
844
  });
2704
-
2705
- // 6) Publish cmd/open request with UDP protocol
2706
- const requestId = crypto.randomUUID();
2707
- const { getFpHash } = await import("../lib/fingerprint.js");
2708
- const fingerprint = await getFpHash(cfg.clientId);
2709
-
2710
- // TPB-12: Track expected requestId for pre-assignment routing
2711
- setExpectedRequestId(instanceId, requestId);
2712
-
2713
- // UDP-S1: Build UDP cmd/open payload
2714
- // UDP-S13: Include targetHost and targetPort (from --port, which is the app's listening port)
2715
- // TPB-12: Include instanceId for per-instance routing
2716
- // AC1.2: Include tenantId to match control-plane contract (v4.1 validation phase uses "tunnel" as literal)
2717
- const openPayload = {
2718
- requestId,
2719
- instanceId, // TPB-12: Per-instance routing
2720
- protocol: 'udp', // UDP-S1: Protocol identifier
2721
- tunnelMode: 'udpWs-v1', // UDP-S1: Tunnel mode
2722
- port: targetPort, // UDP-S13: targetPort (app's listening port, not a port we bind)
2723
- targetHost: targetHost, // UDP-S13: Target host (must be loopback)
2724
- targetPort: targetPort, // UDP-S13: Target port (from --port)
2725
- clientId: cfg.clientId,
2726
- tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
2727
- ...fingerprint
2728
- };
2729
-
2730
- // UDP-S1: Include optional externalPort if provided
2731
- if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
2732
- openPayload.externalPort = requestedExternalPort;
2733
- }
2734
-
2735
- // Publish the open request
2736
- await core.publish({
2737
- topic: cmdOpenTopic,
2738
- payload: JSON.stringify(openPayload),
2739
- qos: 1,
2740
- retain: false
845
+ handle.on('closed', ({ error }) => {
846
+ if (!error) return;
847
+ if (error.code === 'setup_required') { process.stderr.write(`❌ ${error.message}\n`); process.exit(2); }
848
+ // Story 12.1: the tunnel ended where it used to call process.exit; same code, no message
849
+ if (error.details?.exitCode !== undefined) process.exit(error.details.exitCode);
850
+ if (error.name === 'RefusedError') { process.stderr.write(`❌ ${error.message}\n`); process.exit(1); }
851
+ process.stderr.write(`❌ Unexpected: ${error.message}\n`);
852
+ process.exit(1);
2741
853
  });
2742
854
 
2743
- logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
2744
-
2745
- // 7) Wait for ack and assignment
2746
- const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
2747
-
2748
855
  try {
2749
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
2750
- logger.info("cli.ack.wait.start", { requestId });
2751
- const assignment = await assignmentPromise;
2752
- logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'udp' });
2753
- logger.info("cli.assignment.received", {
2754
- relayId: assignment.relayId,
2755
- leaseId: assignment.leaseId,
2756
- instanceId,
2757
- tunnelType: 'udp',
2758
- publicPort: assignment.publicPort
2759
- });
2760
-
2761
- // UDP-S1: Validate assignment (AC1.4/AC5.1: comprehensive validation)
2762
- if (!assignment.relayUrl) {
2763
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
2764
- error.code = 'UDP_RELAY_UNAVAILABLE';
2765
- throw error;
2766
- }
2767
-
2768
- if (!assignment.tunnelMode || assignment.tunnelMode !== 'udpWs-v1') {
2769
- const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid tunnelMode in assignment: ${assignment.tunnelMode}, expected udpWs-v1`);
2770
- error.code = 'UDP_RELAY_UNAVAILABLE';
2771
- throw error;
2772
- }
2773
-
2774
- if (!assignment.protocol || assignment.protocol !== 'udp') {
2775
- const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid protocol in assignment: ${assignment.protocol}, expected udp`);
2776
- error.code = 'UDP_RELAY_UNAVAILABLE';
2777
- throw error;
2778
- }
2779
-
2780
- if (!assignment.relayId) {
2781
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayId in assignment');
2782
- error.code = 'UDP_RELAY_UNAVAILABLE';
2783
- throw error;
2784
- }
2785
-
2786
- if (!assignment.publicPort) {
2787
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing publicPort in assignment');
2788
- error.code = 'UDP_RELAY_UNAVAILABLE';
2789
- throw error;
2790
- }
2791
-
2792
- const assignmentJwt = assignment.assignmentJwt || assignment.jwt;
2793
- if (!assignmentJwt) {
2794
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing assignmentJwt in assignment');
2795
- error.code = 'UDP_RELAY_UNAVAILABLE';
2796
- throw error;
2797
- }
2798
-
2799
- // AC1.4/AC5.1: Verify JWT signature and claims using JWKS (fail fast if JWKS unavailable)
2800
- try {
2801
- const { verifyAssignmentJWT } = await import("../lib/jwt-verifier.js");
2802
- await verifyAssignmentJWT(assignmentJwt, {
2803
- relayId: assignment.relayId,
2804
- protocol: 'udp',
2805
- tunnelMode: 'udpWs-v1',
2806
- leaseId: assignment.leaseId
2807
- });
2808
- logger.debug('udp.assignment.jwt_verified', {
2809
- relayId: assignment.relayId,
2810
- leaseId: assignment.leaseId
2811
- });
2812
- } catch (jwtError) {
2813
- // Map all JWT verification errors to UDP_RELAY_UNAVAILABLE
2814
- const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
2815
- error.code = 'UDP_RELAY_UNAVAILABLE';
2816
- logger.error('udp.assignment.jwt_verification_failed', {
2817
- error: jwtError.message,
2818
- code: jwtError.code,
2819
- relayId: assignment.relayId,
2820
- leaseId: assignment.leaseId
2821
- });
2822
- throw error;
2823
- }
2824
-
2825
- // TPB-12: Persist assignment using per-instance store
2826
- try {
2827
- const { setAssignment } = await import("../state/assignment.js");
2828
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2829
- setAssignment(instanceId, assignment);
2830
- clearExpectedRequestId(instanceId);
2831
- } catch {}
2832
-
2833
-
2834
- // Story 10.9: if the relay refuses this assignment on a reconnect (the tenant was moved to
2835
- // another relay, so the token's relay no longer matches), open again for the same public
2836
- // port; the control plane places the new lease on the tenant's current relay.
2837
- const reassignSamePort = async () => {
2838
- const { setAssignment: setA, getAssignment: getA } = await import("../state/assignment.js");
2839
- const cur = getA(instanceIdRef.instanceId) || assignment;
2840
- const rid = crypto.randomUUID();
2841
- const again = { ...openPayload, requestId: rid, externalPort: cur.publicPort ?? assignment.publicPort };
2842
- setExpectedRequestId(instanceIdRef.instanceId, rid);
2843
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
2844
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
2845
- setA(instanceIdRef.instanceId, next);
2846
- logger.info("udp.reassign.ok", { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
2847
- return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
2848
- };
2849
-
2850
- // UDP-S1: Connect to relay using UdpTunnel
2851
- // UDP-S13: Pass targetHost and targetPort (not localPort that we bind to)
2852
- await connectToRelayUdp(
2853
- assignment,
2854
- cfg.clientId,
2855
- targetHost,
2856
- targetPort,
2857
- core,
2858
- ingress,
2859
- { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
2860
- tunnelInstanceRef,
2861
- mqttClient,
2862
- instanceId,
2863
- reassignSamePort
2864
- );
2865
-
856
+ await handle.open();
2866
857
  } catch (error) {
2867
- logger.error("cli.ack.wait.failed", { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
2868
-
2869
- // UDP-S1: Handle UDP-specific error codes
2870
- if (error.code === 'UDP_RELAY_UNAVAILABLE') {
2871
- process.stderr.write(`❌ ${error.message}\n`);
2872
- try { await core.end(); } catch {}
2873
- process.exit(1);
858
+ switch (error.code) {
859
+ case 'control_plane_connect_failed': process.stderr.write(`Tunnel command failed: ${error.message}\n`); break;
860
+ case 'udp_relay_unavailable': process.stderr.write(`❌ ${error.message}\n`); break;
861
+ case 'assignment_failed': process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`); break;
862
+ case 'tunnel_connect_failed': process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`); break;
863
+ default: process.stderr.write(`❌ Unexpected: ${error?.message || String(error)}\n`);
2874
864
  }
2875
-
2876
- // TPB-12: Clean up expected requestId on timeout/error
2877
- try {
2878
- const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2879
- clearExpectedRequestId(instanceId);
2880
- } catch (err) {
2881
- // Ignore cleanup errors
2882
- }
2883
- process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
2884
- try { await core.end(); } catch {}
2885
865
  process.exit(1);
2886
866
  }
2887
- }
867
+ const assignment = handle.assignment;
2888
868
 
2889
- export async function connectToRelayUdp(
2890
- assignment,
2891
- deviceId,
2892
- targetHost,
2893
- targetPort,
2894
- coordinatorCore,
2895
- coordinatorIngress,
2896
- controlPlaneHelpers,
2897
- tunnelInstanceRef,
2898
- mqttClient,
2899
- instanceId = null,
2900
- reassign = null // Story 10.9: new assignment after a relay refuses the old one
2901
- ) {
2902
- // Import UDP tunnel logic
2903
- const { UdpTunnel } = await import("../tunnel/udp-tunnel.js");
2904
- const { getAssignment: getStoredAssignment } = await import("../state/assignment.js");
2905
-
2906
- const tunnel = new UdpTunnel({
2907
- reassign,
2908
- relayUrl: assignment.relayUrl,
2909
- jwt: assignment.assignmentJwt || assignment.jwt, // UDP-S1: Use assignmentJwt if available
2910
- // Story 11.2: reconnects use the newest token (kept fresh by the UDP refresh)
2911
- getJwt: () => {
2912
- const stored = instanceId ? getStoredAssignment(instanceId) : null;
2913
- return stored?.assignmentJwt || stored?.jwt || null;
2914
- },
2915
- deviceId,
2916
- requestId: assignment.requestId,
2917
- targetHost, // UDP-S13: Target host (must be loopback)
2918
- targetPort, // UDP-S13: Target port (app's listening port, not a port we bind)
2919
- leaseId: assignment.leaseId,
2920
- relayId: assignment.relayId, // AC5.1: Pass relayId for JWT validation
2921
- coordinatorCore,
2922
- coordinatorIngress,
2923
- isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
2924
- waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
2925
- getLastMqttError: controlPlaneHelpers.getLastMqttError,
2926
- getForceReconnect: controlPlaneHelpers.getForceReconnect,
2927
- controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
2928
- log: {
2929
- info: (msgOrFields, maybeFields) => {
2930
- if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
2931
- return logger.info(maybeFields, msgOrFields);
2932
- },
2933
- warn: (msgOrFields, maybeFields) => {
2934
- if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
2935
- return logger.warn(maybeFields, msgOrFields);
2936
- },
2937
- error: (msgOrFields, maybeFields) => {
2938
- if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
2939
- return logger.error(maybeFields, msgOrFields);
2940
- },
2941
- debug: (msgOrFields, maybeFields) => {
2942
- if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
2943
- return logger.debug(maybeFields, msgOrFields);
2944
- }
869
+ // Tunnel live message (UDP-S13: both fqdn and fqdn:publicPort; the CLI does not bind the service port)
870
+ process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
871
+ process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
872
+ if (assignment.fqdn) {
873
+ process.stdout.write(` Your UDP server is available at:\n`);
874
+ process.stdout.write(` ${assignment.fqdn}\n`);
875
+ if (assignment.publicPort) {
876
+ process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
2945
877
  }
2946
- });
2947
-
2948
- // UDP-S1: Store tunnel instance before opening
2949
- if (tunnelInstanceRef) {
2950
- tunnelInstanceRef.tunnel = tunnel;
878
+ } else if (assignment.publicPort) {
879
+ process.stdout.write(` Public port: ${assignment.publicPort}\n`);
2951
880
  }
881
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
882
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
883
+ if (logLevel === 'info' || logLevel === 'debug') {
884
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
885
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
886
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
887
+ }
888
+ process.stdout.write(` Press Ctrl+C to stop\n`);
2952
889
 
2953
- try {
2954
- await tunnel.open();
2955
-
2956
- // Story 11.2: schedule the first proactive token refresh (as TCP, TPB-17)
2957
- const firstExp = jwtExpOf(assignment.assignmentJwt || assignment.jwt);
2958
- if (mqttClient && firstExp && assignment.leaseId) {
2959
- mqttClient.scheduleRefresh(firstExp * 1000, assignment.leaseId);
2960
- logger.debug('udp.refresh.initial_scheduled', { expMs: firstExp * 1000, leaseId: assignment.leaseId });
2961
- }
2962
-
2963
- // UDP-S1: Log tunnel active
2964
- // UDP-S13: Use targetHost and targetPort (not localPort)
2965
- logger.info("tunnel.active", {
2966
- target: `udp://${targetHost}:${targetPort}`,
2967
- relayId: assignment.relayId,
2968
- leaseMs: assignment.leaseMs,
2969
- publicPort: assignment.publicPort
2970
- });
2971
-
2972
- // Tunnel live message
2973
- // UDP-S13: Print both fqdn and fqdn:publicPort
2974
- // UDP-S13: Clarify that CLI doesn't bind the service port
2975
- process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
2976
- process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
2977
-
2978
- // UDP-S13: Show public endpoint (both fqdn and fqdn:publicPort)
2979
- if (assignment.fqdn) {
2980
- process.stdout.write(` Your UDP server is available at:\n`);
2981
- process.stdout.write(` ${assignment.fqdn}\n`);
2982
- if (assignment.publicPort) {
2983
- process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
2984
- }
2985
- } else if (assignment.publicPort) {
2986
- process.stdout.write(` Public port: ${assignment.publicPort}\n`);
2987
- }
2988
-
2989
- // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
2990
- const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
2991
- if (logLevel === 'info' || logLevel === 'debug') {
2992
- process.stdout.write(` Relay: ${assignment.relayId}\n`);
2993
- const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
2994
- process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
2995
- }
2996
-
2997
- process.stdout.write(` Press Ctrl+C to stop\n`);
2998
-
2999
- // CLI-IMG-WSReconnect: Set up graceful shutdown
3000
- let shuttingDown = false;
3001
- const onSig = async (sig) => {
3002
- if (shuttingDown) return;
3003
- shuttingDown = true;
3004
- logger.info("cli.signal.shutdown", { sig });
3005
- process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
3006
-
3007
- const killer = setTimeout(() => {
3008
- logger.error("tunnel.close.timeout", {});
3009
- process.stderr.write("tunnel.close() timed out; forcing exit\n");
3010
- process.exit(0);
3011
- }, 3000);
3012
-
3013
- try {
3014
- tunnel.close();
3015
- await mqttClient.disconnect();
3016
- } catch (e) {
3017
- logger.debug('tunnel.shutdown.error', { error: e.message });
3018
- }
3019
-
3020
- clearTimeout(killer);
890
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
891
+ let shuttingDown = false;
892
+ const onSig = async (sig) => {
893
+ if (shuttingDown) return;
894
+ shuttingDown = true;
895
+ logger.info("cli.signal.shutdown", { sig });
896
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
897
+ const killer = setTimeout(() => {
898
+ logger.error("tunnel.close.timeout", {});
899
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
3021
900
  process.exit(0);
3022
- };
3023
-
3024
- process.once("SIGINT", onSig);
3025
- process.once("SIGTERM", onSig);
3026
-
3027
- // Keep process alive until SIGINT/SIGTERM
3028
- await new Promise(() => {});
3029
-
3030
- } catch (error) {
3031
- logger.error("tunnel.open.failed", { error: error.message });
3032
-
3033
- // UDP-S1: Handle UDP_RELAY_UNAVAILABLE error
3034
- if (error.code === 'UDP_RELAY_UNAVAILABLE') {
3035
- process.stderr.write(`❌ ${error.message}\n`);
3036
- } else {
3037
- process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
3038
- }
3039
-
3040
- try {
3041
- tunnel.close();
3042
- } catch (e) {
3043
- logger.debug('tunnel.close.error', { error: e.message });
3044
- }
901
+ }, 3000);
3045
902
  try {
3046
- await mqttClient.disconnect();
903
+ await handle.close();
3047
904
  } catch (e) {
3048
- logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
905
+ logger.debug('tunnel.shutdown.error', { error: e.message });
3049
906
  }
3050
- process.exit(1);
3051
- }
907
+ clearTimeout(killer);
908
+ process.exit(0);
909
+ };
910
+ process.once("SIGINT", onSig);
911
+ process.once("SIGTERM", onSig);
912
+
913
+ // Keep process alive until SIGINT/SIGTERM
914
+ await new Promise(() => {});
3052
915
  }
3053
916
 
3054
917
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
3055
918
 
3056
919
  // Story 11.2: exp claim (seconds) of an assignment token, or null
3057
- function jwtExpOf(jwt) {
3058
- try {
3059
- const part = String(jwt).split('.')[1];
3060
- const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
3061
- return typeof payload.exp === 'number' ? payload.exp : null;
3062
- } catch {
3063
- return null;
3064
- }
3065
- }