asyx 0.2.3 → 0.3.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.
@@ -93,7 +93,8 @@ export default async function tunnel(args = []) {
93
93
  process.stdout.write(` asyx tunnel connect Connect to control plane (TLS 8883)\n`);
94
94
  process.stdout.write(` asyx tunnel --http --port <n> Create HTTP tunnel on local port <n>\n`);
95
95
  process.stdout.write(` asyx tunnel --http --port <n> --secgroup <slug> Create HTTP tunnel with QuickPass security group\n`);
96
- process.stdout.write(` asyx tunnel --tcp --port <n> Create TCP tunnel on local port <n> (localhost only)\n`);
96
+ process.stdout.write(` asyx tunnel --tcp --port <n> [--external-port <p>] Create TCP tunnel on local port <n> (localhost only)\n`);
97
+ process.stdout.write(` asyx tunnel --udp --port <n> [--external-port <p>] Create UDP tunnel on local port <n> (localhost only)\n`);
97
98
  process.stdout.write(` asyx tunnel --minecraft [--port 25565] [--name <svc>] Create Minecraft TCP tunnel (expands to --tcp --port 25565 --kind minecraft)\n`);
98
99
  process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
99
100
  process.stdout.write(` asyx tunnel --help Show this help\n`);
@@ -119,6 +120,18 @@ export default async function tunnel(args = []) {
119
120
  process.exit(2);
120
121
  }
121
122
 
123
+ if (parsed.tcp && parsed.udp) {
124
+ logger.error("cli.args.invalid", { reason: "--tcp and --udp are mutually exclusive" });
125
+ process.stderr.write("Error: --tcp and --udp are mutually exclusive\n");
126
+ process.exit(2);
127
+ }
128
+
129
+ if (parsed.udp && parsed.http) {
130
+ logger.error("cli.args.invalid", { reason: "--udp and --http are mutually exclusive" });
131
+ process.stderr.write("Error: --udp and --http are mutually exclusive\n");
132
+ process.exit(2);
133
+ }
134
+
122
135
  // Validation: Fail fast on unsupported combinations
123
136
  if (parsed.http && !parsed.port) {
124
137
  logger.error("cli.args.invalid", { reason: "--http requires --port" });
@@ -131,9 +144,15 @@ export default async function tunnel(args = []) {
131
144
  process.exit(2);
132
145
  }
133
146
 
134
- if (parsed.port && !parsed.http && !parsed.tcp) {
135
- logger.error("cli.args.invalid", { reason: "--port requires --http or --tcp" });
136
- process.stderr.write("Error: --port requires --http or --tcp\n");
147
+ if (parsed.udp && !parsed.port) {
148
+ logger.error("cli.args.invalid", { reason: "--udp requires --port" });
149
+ process.stderr.write("Error: --udp requires --port\n");
150
+ process.exit(2);
151
+ }
152
+
153
+ if (parsed.port && !parsed.http && !parsed.tcp && !parsed.udp) {
154
+ logger.error("cli.args.invalid", { reason: "--port requires --http, --tcp, or --udp" });
155
+ process.stderr.write("Error: --port requires --http, --tcp, or --udp\n");
137
156
  process.exit(2);
138
157
  }
139
158
 
@@ -157,7 +176,48 @@ export default async function tunnel(args = []) {
157
176
  process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
158
177
  process.exit(2);
159
178
  }
160
- return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind);
179
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
180
+ }
181
+
182
+ // Handle new --udp --port flags
183
+ if (parsed.udp && parsed.port) {
184
+ // UDP-S13: --target-host defaults to 127.0.0.1
185
+ const targetHost = parsed.targetHost || '127.0.0.1';
186
+ const targetPort = parsed.port;
187
+
188
+ // UDP-S13: Validate targetPort (must be 1-65535)
189
+ if (targetPort < 1 || targetPort > 65535) {
190
+ logger.error("cli.args.invalid", {
191
+ reason: `Invalid targetPort: ${targetPort} (must be 1-65535)`
192
+ });
193
+ process.stderr.write(`Error: --port must be between 1 and 65535. Got: ${targetPort}\n`);
194
+ process.exit(2);
195
+ }
196
+
197
+ // UDP-S13: Validate target-host is loopback-only (resolve DNS if needed)
198
+ const { validateTargetHost } = await import('./validate-target-host.js');
199
+ let validationResult;
200
+ try {
201
+ validationResult = await validateTargetHost(targetHost);
202
+ } catch (error) {
203
+ logger.error("cli.args.invalid", {
204
+ reason: `Failed to resolve --target-host: ${error.message}`
205
+ });
206
+ process.stderr.write(`Error: Failed to resolve --target-host "${targetHost}": ${error.message}\n`);
207
+ process.exit(2);
208
+ }
209
+
210
+ if (!validationResult.isLoopback) {
211
+ logger.error("cli.args.invalid", {
212
+ reason: `UDP tunnels in v4.1 can only target localhost. Got: ${targetHost} (resolved to: ${validationResult.resolvedIPs.join(', ')})`
213
+ });
214
+ process.stderr.write(`Error: --target-host must resolve to loopback addresses only (127.0.0.1 / ::1).\n`);
215
+ process.stderr.write(` Target: ${targetHost}\n`);
216
+ process.stderr.write(` Resolved IPs: ${validationResult.resolvedIPs.join(', ')}\n`);
217
+ process.exit(2);
218
+ }
219
+
220
+ return udpTunnel(targetPort, parsed.externalPort, targetHost);
161
221
  }
162
222
 
163
223
  logger.error("cli.args.unknown", { args: args.join(' ') });
@@ -174,6 +234,8 @@ function parseArgs(args) {
174
234
  parsed.http = true;
175
235
  } else if (arg === '--tcp') {
176
236
  parsed.tcp = true;
237
+ } else if (arg === '--udp') {
238
+ parsed.udp = true;
177
239
  } else if (arg === '--minecraft') {
178
240
  parsed.minecraft = true;
179
241
  } else if (arg === '--minecraft') {
@@ -213,6 +275,32 @@ function parseArgs(args) {
213
275
  process.stderr.write("Error: --secgroup requires a slug\n");
214
276
  process.exit(2);
215
277
  }
278
+ } else if (arg === '--target-host') {
279
+ // UDP-S13: Parse --target-host flag (defaults to 127.0.0.1)
280
+ if (i + 1 < args.length) {
281
+ parsed.targetHost = args[i + 1];
282
+ i++; // Skip next argument as it's the target host value
283
+ } else {
284
+ logger.error("cli.args.target_host_missing", {});
285
+ process.stderr.write("Error: --target-host requires a host value\n");
286
+ process.exit(2);
287
+ }
288
+ } else if (arg === '--external-port' || arg === '--ext-port') {
289
+ // TPB-03B: Parse --external-port flag (alias --ext-port)
290
+ if (i + 1 < args.length) {
291
+ const externalPort = parseInt(args[i + 1], 10);
292
+ if (isNaN(externalPort) || externalPort < 1 || externalPort > 65535) {
293
+ logger.error("cli.args.external_port_invalid", { value: args[i + 1] });
294
+ process.stderr.write(`Error: Invalid external port number: ${args[i + 1]}\n`);
295
+ process.exit(2);
296
+ }
297
+ parsed.externalPort = externalPort;
298
+ i++; // Skip next argument as it's the external port value
299
+ } else {
300
+ logger.error("cli.args.external_port_missing", {});
301
+ process.stderr.write("Error: --external-port requires a port number\n");
302
+ process.exit(2);
303
+ }
216
304
  } else if (arg === '--help' || arg === '-h') {
217
305
  parsed.help = true;
218
306
  }
@@ -425,6 +513,9 @@ async function httpTunnel(localPort, secGroupSlug) {
425
513
  // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
426
514
  const baseClientId = cfg.clientId;
427
515
 
516
+ // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect (must be before MqttControlPlaneClient)
517
+ const instanceIdRef = { instanceId: null };
518
+
428
519
  // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
429
520
  const tunnelInstanceRef = { tunnel: null };
430
521
 
@@ -459,7 +550,76 @@ async function httpTunnel(localPort, secGroupSlug) {
459
550
  logger,
460
551
  onConnected: async (mqttClientInstance) => {
461
552
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
462
- logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
553
+ const newClientId = mqttClient.getClientId();
554
+ logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
555
+
556
+ // TPB-12: Update instance registry if clientId changed on reconnect
557
+ if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
558
+ const oldInstanceId = instanceIdRef.instanceId;
559
+ logger.debug("cli.instance.clientid_rotated", {
560
+ oldInstanceId,
561
+ newInstanceId: newClientId,
562
+ tunnelType: 'http'
563
+ });
564
+
565
+ // Unregister old instance and register new one
566
+ const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
567
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
568
+
569
+ // Get old instance context to preserve metadata
570
+ const oldContext = getInstance(oldInstanceId);
571
+ if (oldContext) {
572
+ // Get assignment from old instance to migrate it
573
+ const oldAssignment = getAssignmentFn(oldInstanceId);
574
+
575
+ // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
576
+ const preservedRequestId = oldContext.expectedRequestId;
577
+
578
+ // Register new instance FIRST (before unregistering old) to ensure routing works
579
+ registerInstance(newClientId, {
580
+ tunnelType: 'http',
581
+ setAssignment: setAssignmentFn,
582
+ getAssignment: getAssignmentFn,
583
+ metadata: oldContext.metadata || { baseClientId, localPort, secGroupSlug }
584
+ });
585
+
586
+ // Migrate expectedRequestId to new instance (preserves in-flight refresh/reconnect)
587
+ if (preservedRequestId) {
588
+ const { setExpectedRequestId } = await import("../state/instance-registry.js");
589
+ setExpectedRequestId(newClientId, preservedRequestId);
590
+ logger.debug("cli.instance.expected_requestid_migrated", {
591
+ oldInstanceId,
592
+ newInstanceId: newClientId,
593
+ requestId: preservedRequestId,
594
+ tunnelType: 'http'
595
+ });
596
+ }
597
+
598
+ // Now unregister old instance (this will clean up old expectedRequestId mapping)
599
+ unregisterInstance(oldInstanceId);
600
+
601
+ // Migrate assignment to new instanceId (updates leaseToInstance mapping)
602
+ if (oldAssignment) {
603
+ setAssignmentFn(newClientId, oldAssignment);
604
+ logger.debug("cli.instance.assignment_migrated", {
605
+ oldInstanceId,
606
+ newInstanceId: newClientId,
607
+ leaseId: oldAssignment.leaseId,
608
+ tunnelType: 'http'
609
+ });
610
+ }
611
+
612
+ logger.debug("cli.instance.reregistered", {
613
+ oldInstanceId,
614
+ newInstanceId: newClientId,
615
+ tunnelType: 'http'
616
+ });
617
+ }
618
+
619
+ // Update instanceId ref
620
+ instanceIdRef.instanceId = newClientId;
621
+ }
622
+
463
623
  // QPA-CLI-11: Vault UX messaging - Control-plane sealed
464
624
  process.stdout.write("✅ Control-plane sealed\n");
465
625
 
@@ -496,18 +656,22 @@ async function httpTunnel(localPort, secGroupSlug) {
496
656
  process.exit(1);
497
657
  },
498
658
  // QPA-CLI-05: Wire onRefreshLease to handle JWT refresh via coordinator
659
+ // TPB-12: Capture instanceId in closure for per-instance routing
499
660
  onRefreshLease: async () => {
500
661
  if (!coordinatorCoreRef || !coordinatorIngressRef) {
501
662
  throw new Error("Coordinator not available for refresh");
502
663
  }
503
664
 
665
+ // TPB-12: Get instanceId from mqttClient (captured in closure)
666
+ const refreshInstanceId = mqttClient.getClientId();
667
+
504
668
  const { getAssignment } = await import('../state/assignment.js');
505
669
  const { getFpHash } = await import('../lib/fingerprint.js');
506
670
 
507
- // Get current assignment to reuse lease
508
- const currentAssignment = getAssignment();
671
+ // TPB-12: Get assignment for this specific instance
672
+ const currentAssignment = getAssignment(refreshInstanceId);
509
673
  if (!currentAssignment) {
510
- throw new Error("No current assignment for refresh");
674
+ throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
511
675
  }
512
676
 
513
677
  const leaseId = currentAssignment.leaseId;
@@ -519,8 +683,10 @@ async function httpTunnel(localPort, secGroupSlug) {
519
683
  const refreshRequestId = `refresh-${Date.now()}`;
520
684
  const fingerprint = await getFpHash(deviceIdRef);
521
685
 
686
+ // TPB-12: Include instanceId in refresh payload
522
687
  const refreshPayload = {
523
688
  requestId: refreshRequestId,
689
+ instanceId: refreshInstanceId, // TPB-12: Per-instance routing
524
690
  refreshOf: leaseId,
525
691
  proto: 'http',
526
692
  localPort: localPortRef,
@@ -585,6 +751,8 @@ async function httpTunnel(localPort, secGroupSlug) {
585
751
  // Log awaiter registration for debugging
586
752
  logger.debug('jwt.refresh.awaiter.registered', {
587
753
  refreshRequestId,
754
+ instanceId: refreshInstanceId,
755
+ tunnelType: 'http',
588
756
  timeoutMs: ACK_TIMEOUT_MS,
589
757
  expectedType: 'open_ack'
590
758
  });
@@ -592,21 +760,43 @@ async function httpTunnel(localPort, secGroupSlug) {
592
760
  const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
593
761
  try {
594
762
  const parsed = message.payload;
595
- const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
763
+ const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
764
+ const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
596
765
 
597
766
  // Log matching attempts for debugging
598
- if (parsed?.type === 'open_ack') {
767
+ if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
599
768
  logger.debug('jwt.refresh.awaiter.checking', {
600
769
  refreshRequestId,
601
770
  receivedRequestId: parsed.requestId,
602
771
  receivedType: parsed.type,
603
- isMatch,
772
+ isAck,
773
+ isReject,
604
774
  topic: message.topic
605
775
  });
606
776
  }
607
777
 
608
- return isMatch;
778
+ // If we get a reject, throw an error so the awaiter rejects the promise
779
+ if (isReject) {
780
+ const reason = parsed.data?.reason || 'unknown';
781
+ if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
782
+ const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
783
+ leaseClosedError.code = 'LEASE_CLOSED';
784
+ leaseClosedError.reason = reason;
785
+ throw leaseClosedError;
786
+ }
787
+ // For other reject reasons, also throw but with different code
788
+ const rejectError = new Error(`Refresh rejected: ${reason}`);
789
+ rejectError.code = 'REFRESH_REJECTED';
790
+ rejectError.reason = reason;
791
+ throw rejectError;
792
+ }
793
+
794
+ return isAck;
609
795
  } catch (e) {
796
+ // If it's a lease_closed or refresh_rejected error, rethrow it
797
+ if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
798
+ throw e;
799
+ }
610
800
  logger.debug('jwt.refresh.awaiter.criteria_error', {
611
801
  refreshRequestId,
612
802
  error: e.message
@@ -639,7 +829,19 @@ async function httpTunnel(localPort, secGroupSlug) {
639
829
  let ackResult;
640
830
  try {
641
831
  ackResult = await ackPromise;
642
- } catch (timeoutError) {
832
+ } catch (error) {
833
+ // Check if this is a lease_closed error - don't retry, treat as fatal
834
+ if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
835
+ logger.error('jwt.refresh.rejected', {
836
+ reason: error.reason || 'unknown',
837
+ requestId: refreshRequestId,
838
+ action: 'fatal'
839
+ });
840
+ throw new Error(`Cannot refresh closed lease: ${error.reason || 'lease_closed'}`);
841
+ }
842
+
843
+ // Otherwise treat as timeout and retry
844
+ const timeoutError = error;
643
845
  // QPA-CLI-07: On timeout, reconnect control-plane and retry once
644
846
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
645
847
  logger.debug('jwt.refresh.timeout', {
@@ -684,21 +886,43 @@ async function httpTunnel(localPort, secGroupSlug) {
684
886
  const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
685
887
  try {
686
888
  const parsed = message.payload;
687
- const isMatch = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
889
+ const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
890
+ const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
688
891
 
689
892
  // Log matching attempts for debugging
690
- if (parsed?.type === 'open_ack') {
893
+ if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
691
894
  logger.debug('jwt.refresh.awaiter.retry_checking', {
692
895
  refreshRequestId,
693
896
  receivedRequestId: parsed.requestId,
694
897
  receivedType: parsed.type,
695
- isMatch,
898
+ isAck,
899
+ isReject,
696
900
  topic: message.topic
697
901
  });
698
902
  }
699
903
 
700
- return isMatch;
904
+ // If we get a reject, throw an error so the awaiter rejects the promise
905
+ if (isReject) {
906
+ const reason = parsed.data?.reason || 'unknown';
907
+ if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
908
+ const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
909
+ leaseClosedError.code = 'LEASE_CLOSED';
910
+ leaseClosedError.reason = reason;
911
+ throw leaseClosedError;
912
+ }
913
+ // For other reject reasons, also throw but with different code
914
+ const rejectError = new Error(`Refresh rejected: ${reason}`);
915
+ rejectError.code = 'REFRESH_REJECTED';
916
+ rejectError.reason = reason;
917
+ throw rejectError;
918
+ }
919
+
920
+ return isAck;
701
921
  } catch (e) {
922
+ // If it's a lease_closed or refresh_rejected error, rethrow it
923
+ if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
924
+ throw e;
925
+ }
702
926
  logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
703
927
  refreshRequestId,
704
928
  error: e.message
@@ -712,6 +936,16 @@ async function httpTunnel(localPort, secGroupSlug) {
712
936
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
713
937
  logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
714
938
  } catch (retryError) {
939
+ // Check if this is a lease_closed error - don't retry, treat as fatal
940
+ if (retryError.code === 'LEASE_CLOSED' || retryError.code === 'REFRESH_REJECTED') {
941
+ logger.error('jwt.refresh.rejected.retry', {
942
+ reason: retryError.reason || 'unknown',
943
+ requestId: refreshRequestId,
944
+ action: 'fatal'
945
+ });
946
+ throw new Error(`Cannot refresh closed lease: ${retryError.reason || 'lease_closed'}`);
947
+ }
948
+
715
949
  logger.error('jwt.refresh.timeout', {
716
950
  error: retryError.message,
717
951
  action: 'give_up',
@@ -757,11 +991,8 @@ async function httpTunnel(localPort, secGroupSlug) {
757
991
  // Update jwtMeta for HttpTunnel
758
992
  tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
759
993
 
760
- // Record refresh timestamp and delta metrics
761
- const { recordRefresh } = await import('../state/assignment.js');
762
- const deltaMs = recordRefresh(Date.now());
763
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
764
- logger.debug('jwt.refresh.delta', { deltaMs });
994
+ // Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
995
+ // to avoid double-counting when refresh happens via in-band reauth
765
996
 
766
997
  // Try in-band reauth if WebSocket is open
767
998
  if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
@@ -848,6 +1079,11 @@ async function httpTunnel(localPort, secGroupSlug) {
848
1079
  process.exit(1);
849
1080
  }
850
1081
 
1082
+ // TPB-12: Get instanceId (full MQTT clientId) after connection
1083
+ instanceIdRef.instanceId = mqttClient.getClientId();
1084
+ const instanceId = instanceIdRef.instanceId; // Use const for current scope, but update ref on reconnect
1085
+ logger.debug("cli.instance.registered", { instanceId, tunnelType: 'http', baseClientId });
1086
+
851
1087
  // 4) Set up topics and message handling
852
1088
  // CLI-MQTT-UniqueID-CleanSession: Use baseClientId for topics (not session client ID) to maintain topic stability
853
1089
  const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
@@ -869,6 +1105,17 @@ async function httpTunnel(localPort, secGroupSlug) {
869
1105
 
870
1106
  ingress.setDispatcher(dispatchEvt);
871
1107
 
1108
+ // TPB-12: Register instance in registry with per-instance callbacks
1109
+ const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
1110
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1111
+
1112
+ registerInstance(instanceId, {
1113
+ tunnelType: 'http',
1114
+ setAssignment: setAssignmentFn,
1115
+ getAssignment: getAssignmentFn,
1116
+ metadata: { baseClientId, localPort, secGroupSlug }
1117
+ });
1118
+
872
1119
  // QPA-CLI-05: Store coordinator references for onRefreshLease callback
873
1120
  coordinatorCoreRef = core;
874
1121
  coordinatorIngressRef = ingress;
@@ -898,8 +1145,13 @@ async function httpTunnel(localPort, secGroupSlug) {
898
1145
  const { getFpHash } = await import("../lib/fingerprint.js");
899
1146
  const fingerprint = await getFpHash(cfg.clientId);
900
1147
 
1148
+ // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
1149
+ setExpectedRequestId(instanceId, requestId);
1150
+
1151
+ // TPB-12: Include instanceId in cmd/open payload
901
1152
  const openPayload = {
902
1153
  requestId,
1154
+ instanceId, // TPB-12: Per-instance routing
903
1155
  proto: 'http',
904
1156
  localPort,
905
1157
  clientId: cfg.clientId,
@@ -919,7 +1171,7 @@ async function httpTunnel(localPort, secGroupSlug) {
919
1171
  retain: false
920
1172
  });
921
1173
 
922
- logger.info("cli.cmd.open.sent", { requestId });
1174
+ logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'http' });
923
1175
 
924
1176
  // 7) Wait for ack and then connect to relay
925
1177
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
@@ -928,16 +1180,20 @@ async function httpTunnel(localPort, secGroupSlug) {
928
1180
  const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
929
1181
  logger.info("cli.ack.wait.start", { requestId });
930
1182
  const assignment = await assignmentPromise;
931
- logger.info("cli.ack.wait.resolved", { requestId });
932
- logger.info("cli.assignment.received", { relayId: assignment.relayId });
933
- // Persist assignment for refresh/fallback paths
1183
+ logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'http' });
1184
+ logger.info("cli.assignment.received", { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
1185
+ // TPB-12: Persist assignment using per-instance store
934
1186
  try {
935
1187
  const { setAssignment } = await import("../state/assignment.js");
936
- setAssignment(assignment);
1188
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
1189
+ setAssignment(instanceId, assignment);
1190
+ // Clear expected requestId now that assignment exists (routing will use leaseId after this)
1191
+ clearExpectedRequestId(instanceId);
937
1192
  } catch {}
938
1193
 
939
1194
  // 8) Connect to relay using thin client behavior
940
1195
  // QPA-CLI-05: Pass mqttClient for refresh scheduling
1196
+ // TPB-12: Pass instanceId for per-instance assignment routing
941
1197
  await connectToRelay(
942
1198
  assignment,
943
1199
  cfg.clientId,
@@ -947,11 +1203,19 @@ async function httpTunnel(localPort, secGroupSlug) {
947
1203
  { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
948
1204
  secGroupSlug,
949
1205
  tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here before infinite promise
950
- mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
1206
+ mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling
1207
+ instanceId // TPB-12: Pass instanceId for per-instance assignment routing
951
1208
  );
952
1209
 
953
1210
  } catch (error) {
954
1211
  logger.error("cli.ack.wait.failed", { error: error.message });
1212
+ // TPB-12: Clean up expected requestId on timeout/error (prevents map leak)
1213
+ try {
1214
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
1215
+ clearExpectedRequestId(instanceId);
1216
+ } catch (err) {
1217
+ // Ignore cleanup errors
1218
+ }
955
1219
  try { await core.end(); } catch {}
956
1220
  process.exit(1);
957
1221
  }
@@ -966,7 +1230,8 @@ export async function connectToRelay(
966
1230
  controlPlaneHelpers,
967
1231
  secGroupSlug,
968
1232
  tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
969
- mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling
1233
+ mqttClient, // QPA-CLI-05: Pass mqttClient for refresh scheduling
1234
+ instanceId = null // TPB-12: Pass instanceId for per-instance assignment routing
970
1235
  ) {
971
1236
  // Import WebSocket bridge logic (ported from client-mvp)
972
1237
  const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
@@ -987,6 +1252,8 @@ export async function connectToRelay(
987
1252
  controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
988
1253
  // QPA-04: Pass secGroupSlug to HttpTunnel
989
1254
  secGroupSlug,
1255
+ // TPB-12: Pass instanceId to HttpTunnel for per-instance assignment routing
1256
+ instanceId,
990
1257
  log: {
991
1258
  info: (msgOrFields, maybeFields) => {
992
1259
  if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
@@ -1149,8 +1416,10 @@ function isLocalhostTarget(target) {
1149
1416
  * Reuses existing MQTT control-plane infrastructure.
1150
1417
  * @param {number} localPort - Local port number
1151
1418
  * @param {string} [serviceName] - Optional service name
1419
+ * @param {string} [kind] - Optional service kind
1420
+ * @param {number} [requestedExternalPort] - Optional requested external port (TPB-03B)
1152
1421
  */
1153
- async function tcpTunnel(localPort, serviceName, kind = null) {
1422
+ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
1154
1423
  logger.info('cli.tcp.start', { localPort, serviceName });
1155
1424
  process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1156
1425
 
@@ -1197,6 +1466,17 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1197
1466
  // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
1198
1467
  const baseClientId = cfg.clientId;
1199
1468
 
1469
+ // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect (must be before MqttControlPlaneClient)
1470
+ const instanceIdRef = { instanceId: null };
1471
+
1472
+ // TPB-17: Store coordinator references for onRefreshLease callback
1473
+ let coordinatorCoreRef = null;
1474
+ let coordinatorIngressRef = null;
1475
+ let deviceIdRef = cfg.clientId;
1476
+ let localPortRef = localPort;
1477
+ // Track subscription state to ensure refresh requests wait for subscription to be active
1478
+ let subscriptionReadyRef = { ready: false };
1479
+
1200
1480
  // 2) Build MqttControlPlaneClient for connection management
1201
1481
  const mqttClient = new MqttControlPlaneClient({
1202
1482
  url: mqttUrl,
@@ -1217,7 +1497,76 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1217
1497
  logger,
1218
1498
  onConnected: async (mqttClientInstance) => {
1219
1499
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1220
- logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
1500
+ const newClientId = mqttClient.getClientId();
1501
+ logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
1502
+
1503
+ // TPB-12: Update instance registry if clientId changed on reconnect
1504
+ if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
1505
+ const oldInstanceId = instanceIdRef.instanceId;
1506
+ logger.debug("cli.instance.clientid_rotated", {
1507
+ oldInstanceId,
1508
+ newInstanceId: newClientId,
1509
+ tunnelType: 'tcp'
1510
+ });
1511
+
1512
+ // Unregister old instance and register new one
1513
+ const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
1514
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1515
+
1516
+ // Get old instance context to preserve metadata
1517
+ const oldContext = getInstance(oldInstanceId);
1518
+ if (oldContext) {
1519
+ // Get assignment from old instance to migrate it
1520
+ const oldAssignment = getAssignmentFn(oldInstanceId);
1521
+
1522
+ // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
1523
+ const preservedRequestId = oldContext.expectedRequestId;
1524
+
1525
+ // Register new instance FIRST (before unregistering old) to ensure routing works
1526
+ registerInstance(newClientId, {
1527
+ tunnelType: 'tcp',
1528
+ setAssignment: setAssignmentFn,
1529
+ getAssignment: getAssignmentFn,
1530
+ metadata: oldContext.metadata || { baseClientId, localPort, serviceName, kind, requestedExternalPort }
1531
+ });
1532
+
1533
+ // Migrate expectedRequestId to new instance (preserves in-flight refresh/reconnect)
1534
+ if (preservedRequestId) {
1535
+ const { setExpectedRequestId } = await import("../state/instance-registry.js");
1536
+ setExpectedRequestId(newClientId, preservedRequestId);
1537
+ logger.debug("cli.instance.expected_requestid_migrated", {
1538
+ oldInstanceId,
1539
+ newInstanceId: newClientId,
1540
+ requestId: preservedRequestId,
1541
+ tunnelType: 'tcp'
1542
+ });
1543
+ }
1544
+
1545
+ // Now unregister old instance (this will clean up old expectedRequestId mapping)
1546
+ unregisterInstance(oldInstanceId);
1547
+
1548
+ // Migrate assignment to new instanceId (updates leaseToInstance mapping)
1549
+ if (oldAssignment) {
1550
+ setAssignmentFn(newClientId, oldAssignment);
1551
+ logger.debug("cli.instance.assignment_migrated", {
1552
+ oldInstanceId,
1553
+ newInstanceId: newClientId,
1554
+ leaseId: oldAssignment.leaseId,
1555
+ tunnelType: 'tcp'
1556
+ });
1557
+ }
1558
+
1559
+ logger.debug("cli.instance.reregistered", {
1560
+ oldInstanceId,
1561
+ newInstanceId: newClientId,
1562
+ tunnelType: 'tcp'
1563
+ });
1564
+ }
1565
+
1566
+ // Update instanceId ref
1567
+ instanceIdRef.instanceId = newClientId;
1568
+ }
1569
+
1221
1570
  process.stdout.write("✅ Control-plane sealed\n");
1222
1571
 
1223
1572
  // Resubscribe to topics on reconnect
@@ -1229,24 +1578,219 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1229
1578
  logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
1230
1579
  }
1231
1580
  },
1232
- onOffline: (reason) => {
1233
- logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
1234
- process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
1235
- },
1236
1581
  onFatalError: (reason, err) => {
1237
1582
  logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
1238
1583
  process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
1239
1584
  process.exit(1);
1240
1585
  },
1241
- // TCP-S2: Refresh lease callback (similar to HTTP, but with TCP protocol)
1242
- // TCP-S4: Make refresh non-fatal - disable refresh scheduling for TCP until implemented
1586
+ // TPB-17: TCP refresh callback (control-plane only, no data-plane reauth)
1243
1587
  onRefreshLease: async () => {
1244
- // TCP refresh not yet implemented - log and skip (non-fatal)
1245
- logger.warn('tcp.refresh.not_implemented', {
1246
- note: 'TCP refresh is not yet implemented; lease will expire naturally'
1588
+ if (!coordinatorCoreRef || !coordinatorIngressRef) {
1589
+ throw new Error("Coordinator not available for refresh");
1590
+ }
1591
+
1592
+ // TPB-12: Get instanceId from mqttClient (captured in closure)
1593
+ const refreshInstanceId = mqttClient.getClientId();
1594
+
1595
+ const { getAssignment } = await import('../state/assignment.js');
1596
+ const { getFpHash } = await import('../lib/fingerprint.js');
1597
+
1598
+ // TPB-12: Get assignment for this specific instance
1599
+ const currentAssignment = getAssignment(refreshInstanceId);
1600
+ if (!currentAssignment) {
1601
+ throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
1602
+ }
1603
+
1604
+ const leaseId = currentAssignment.leaseId;
1605
+ if (!leaseId) {
1606
+ throw new Error("No leaseId in current assignment");
1607
+ }
1608
+
1609
+ // Build refresh payload
1610
+ const refreshRequestId = `refresh-${Date.now()}`;
1611
+ const fingerprint = await getFpHash(deviceIdRef);
1612
+
1613
+ // TPB-17: Include instanceId and proto:"tcp" in refresh payload
1614
+ const refreshPayload = {
1615
+ requestId: refreshRequestId,
1616
+ instanceId: refreshInstanceId, // TPB-12: Per-instance routing
1617
+ refreshOf: leaseId,
1618
+ proto: 'tcp', // TPB-17: TCP protocol identifier
1619
+ localPort: localPortRef,
1620
+ clientId: deviceIdRef,
1621
+ ...fingerprint
1622
+ };
1623
+
1624
+ // Cancel any existing awaiters for this leaseId before starting a new refresh
1625
+ const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
1626
+ const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
1627
+ try {
1628
+ const testMessage = {
1629
+ topic: ackTopic,
1630
+ payload: { type: 'open_ack', requestId: 'test' }
1631
+ };
1632
+ return awaiter.criteria(testMessage);
1633
+ } catch {
1634
+ return false;
1635
+ }
1636
+ });
1637
+
1638
+ if (cancelled > 0) {
1639
+ logger.debug('jwt.refresh.awaiter.cancelled_stale', {
1640
+ refreshRequestId,
1641
+ cancelledCount: cancelled,
1642
+ reason: 'new_refresh_starting'
1643
+ });
1644
+ }
1645
+
1646
+ // Wait for subscription to be ready before publishing
1647
+ if (!subscriptionReadyRef.ready) {
1648
+ logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
1649
+ const maxWait = 2000;
1650
+ const startWait = Date.now();
1651
+ while (!subscriptionReadyRef.ready && (Date.now() - startWait) < maxWait) {
1652
+ await new Promise(resolve => setTimeout(resolve, 50));
1653
+ }
1654
+ if (!subscriptionReadyRef.ready) {
1655
+ logger.debug('jwt.refresh.subscription_not_ready', { refreshRequestId, waited: Date.now() - startWait });
1656
+ } else {
1657
+ logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
1658
+ }
1659
+ }
1660
+
1661
+ // Set up topic and wait for ack
1662
+ const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
1663
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
1664
+
1665
+ logger.debug('jwt.refresh.awaiter.registered', {
1666
+ refreshRequestId,
1667
+ instanceId: refreshInstanceId,
1668
+ tunnelType: 'tcp',
1669
+ timeoutMs: ACK_TIMEOUT_MS,
1670
+ expectedType: 'open_ack'
1671
+ });
1672
+
1673
+ const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
1674
+ try {
1675
+ const parsed = message.payload;
1676
+ const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
1677
+ const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
1678
+
1679
+ if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
1680
+ logger.debug('jwt.refresh.awaiter.checking', {
1681
+ refreshRequestId,
1682
+ receivedRequestId: parsed.requestId,
1683
+ receivedType: parsed.type,
1684
+ isAck,
1685
+ isReject,
1686
+ topic: message.topic
1687
+ });
1688
+ }
1689
+
1690
+ // TPB-17: For TCP, refresh failures are non-fatal (tunnel continues until WS closes)
1691
+ // But we still throw on lease_closed/REFRESH_REJECTED to let MqttControlPlaneClient handle it
1692
+ if (isReject) {
1693
+ const reason = parsed.data?.reason || 'unknown';
1694
+ if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
1695
+ const leaseClosedError = new Error('Lease is closed and cannot be refreshed');
1696
+ leaseClosedError.code = 'LEASE_CLOSED';
1697
+ leaseClosedError.reason = reason;
1698
+ throw leaseClosedError;
1699
+ }
1700
+ const rejectError = new Error(`Refresh rejected: ${reason}`);
1701
+ rejectError.code = 'REFRESH_REJECTED';
1702
+ rejectError.reason = reason;
1703
+ throw rejectError;
1704
+ }
1705
+
1706
+ return isAck;
1707
+ } catch (e) {
1708
+ if (e.code === 'LEASE_CLOSED' || e.code === 'REFRESH_REJECTED') {
1709
+ throw e;
1710
+ }
1711
+ logger.debug('jwt.refresh.awaiter.criteria_error', {
1712
+ refreshRequestId,
1713
+ error: e.message
1714
+ });
1715
+ return false;
1716
+ }
1717
+ }, ACK_TIMEOUT_MS);
1718
+
1719
+ // Publish refresh request
1720
+ const publishSuccess = await publishRefreshRequestWithErrorHandling(
1721
+ coordinatorCoreRef,
1722
+ cmdOpenTopic,
1723
+ refreshPayload,
1724
+ refreshRequestId,
1725
+ logger
1726
+ );
1727
+
1728
+ if (publishSuccess === false) {
1729
+ const bufferedError = new Error('Connection closed during refresh publish');
1730
+ bufferedError.code = 'ECONNRESET';
1731
+ throw bufferedError;
1732
+ }
1733
+
1734
+ // Wait for ack (non-fatal for TCP - tunnel continues on failure)
1735
+ let ackResult;
1736
+ try {
1737
+ ackResult = await ackPromise;
1738
+ } catch (error) {
1739
+ // TPB-17: For TCP, refresh failures are non-fatal
1740
+ // Log and return null to indicate refresh failed, but don't throw
1741
+ // The tunnel will continue until WebSocket closes naturally
1742
+ if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
1743
+ logger.warn('tcp.refresh.rejected', {
1744
+ reason: error.reason || 'unknown',
1745
+ requestId: refreshRequestId,
1746
+ action: 'non_fatal_continue'
1747
+ });
1748
+ // Return null to indicate refresh failed, but don't throw (non-fatal)
1749
+ return null;
1750
+ }
1751
+
1752
+ // Timeout or other errors - also non-fatal for TCP
1753
+ logger.warn('tcp.refresh.timeout', {
1754
+ error: error.message,
1755
+ requestId: refreshRequestId,
1756
+ action: 'non_fatal_continue'
1757
+ });
1758
+ return null;
1759
+ }
1760
+
1761
+ // Get new assignment (updated by open_ack handler)
1762
+ const newAssignment = getAssignment(refreshInstanceId);
1763
+ if (!newAssignment) {
1764
+ logger.warn('tcp.refresh.no_assignment', { requestId: refreshRequestId });
1765
+ return null;
1766
+ }
1767
+
1768
+ // Extract expiration from new JWT
1769
+ const newJwt = newAssignment.jwt;
1770
+ const parts = newJwt.split('.');
1771
+ if (parts.length !== 3) {
1772
+ logger.warn('tcp.refresh.invalid_jwt', { requestId: refreshRequestId });
1773
+ return null;
1774
+ }
1775
+
1776
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
1777
+ const expMs = payload.exp ? payload.exp * 1000 : null;
1778
+
1779
+ if (!expMs) {
1780
+ logger.warn('tcp.refresh.no_exp', { requestId: refreshRequestId });
1781
+ return null;
1782
+ }
1783
+
1784
+ // TPB-17: TCP refresh updates assignment/JWT for reconnect use
1785
+ // No data-plane reauth needed (TCP uses TCP-v1 framing, not WebSocket auth)
1786
+ // The assignment is already updated by the open_ack handler
1787
+ logger.debug('tcp.refresh.success', {
1788
+ leaseId: newAssignment.leaseId,
1789
+ expMs,
1790
+ requestId: refreshRequestId
1247
1791
  });
1248
- // Return without throwing to prevent fatal errors
1249
- return;
1792
+
1793
+ return expMs;
1250
1794
  },
1251
1795
  });
1252
1796
 
@@ -1307,6 +1851,11 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1307
1851
  process.exit(1);
1308
1852
  }
1309
1853
 
1854
+ // TPB-12: Get instanceId (full MQTT clientId) after connection
1855
+ instanceIdRef.instanceId = mqttClient.getClientId();
1856
+ const instanceId = instanceIdRef.instanceId; // Use const for current scope, but update ref on reconnect
1857
+ logger.debug("cli.instance.registered", { instanceId, tunnelType: 'tcp', baseClientId });
1858
+
1310
1859
  // 4) Set up topics and message handling
1311
1860
  const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1312
1861
  const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
@@ -1323,6 +1872,21 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1323
1872
  });
1324
1873
 
1325
1874
  ingress.setDispatcher(dispatchEvt);
1875
+
1876
+ // TPB-12: Register instance in registry with per-instance callbacks
1877
+ const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
1878
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1879
+
1880
+ registerInstance(instanceId, {
1881
+ tunnelType: 'tcp',
1882
+ setAssignment: setAssignmentFn,
1883
+ getAssignment: getAssignmentFn,
1884
+ metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort }
1885
+ });
1886
+
1887
+ // TPB-17: Store coordinator references for onRefreshLease callback
1888
+ coordinatorCoreRef = core;
1889
+ coordinatorIngressRef = ingress;
1326
1890
 
1327
1891
  core.onMessage(async (m) => {
1328
1892
  try {
@@ -1349,10 +1913,15 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1349
1913
  const { getFpHash } = await import("../lib/fingerprint.js");
1350
1914
  const fingerprint = await getFpHash(cfg.clientId);
1351
1915
 
1916
+ // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
1917
+ setExpectedRequestId(instanceId, requestId);
1918
+
1352
1919
  // TCP-S2: Build TCP cmd/open payload
1353
1920
  // E3-S8: Include kind field if provided
1921
+ // TPB-12: Include instanceId for per-instance routing
1354
1922
  const openPayload = {
1355
1923
  requestId,
1924
+ instanceId, // TPB-12: Per-instance routing
1356
1925
  proto: 'tcp', // Protocol identifier
1357
1926
  target: target, // "127.0.0.1:<port>" from TCP-S1
1358
1927
  clientId: cfg.clientId,
@@ -1361,6 +1930,7 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1361
1930
 
1362
1931
  // TCP-S2: Include optional opts.name if service name provided
1363
1932
  // E3-S8: Include opts.kind if provided
1933
+ // TPB-03B: Include requestedExternalPort if provided
1364
1934
  openPayload.opts = {
1365
1935
  preferredPort: null // Can be wired to a flag later if needed
1366
1936
  };
@@ -1372,6 +1942,11 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1372
1942
  if (kind) {
1373
1943
  openPayload.opts.kind = kind;
1374
1944
  }
1945
+
1946
+ // TPB-03B: Include requestedExternalPort in opts (null if omitted)
1947
+ if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
1948
+ openPayload.opts.requestedExternalPort = requestedExternalPort;
1949
+ }
1375
1950
 
1376
1951
  // Publish the open request
1377
1952
  await core.publish({
@@ -1381,7 +1956,7 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1381
1956
  retain: false
1382
1957
  });
1383
1958
 
1384
- logger.info("cli.cmd.open.sent", { requestId, protocol: 'tcp', target });
1959
+ logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
1385
1960
 
1386
1961
  // 7) Wait for ack and assignment
1387
1962
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
@@ -1390,18 +1965,23 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1390
1965
  const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
1391
1966
  logger.info("cli.ack.wait.start", { requestId });
1392
1967
  const assignment = await assignmentPromise;
1393
- logger.info("cli.ack.wait.resolved", { requestId });
1968
+ logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'tcp' });
1394
1969
  logger.info("cli.assignment.received", {
1395
1970
  relayId: assignment.relayId,
1396
1971
  leaseId: assignment.leaseId,
1972
+ instanceId,
1973
+ tunnelType: 'tcp',
1397
1974
  tcpAliasFqdn: assignment.tcpAliasFqdn,
1398
1975
  publicPort: assignment.publicPort
1399
1976
  });
1400
1977
 
1401
- // Persist assignment for refresh/fallback paths
1978
+ // TPB-12: Persist assignment using per-instance store
1402
1979
  try {
1403
1980
  const { setAssignment } = await import("../state/assignment.js");
1404
- setAssignment(assignment);
1981
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
1982
+ setAssignment(instanceId, assignment);
1983
+ // Clear expected requestId now that assignment exists (routing will use leaseId after this)
1984
+ clearExpectedRequestId(instanceId);
1405
1985
  } catch {}
1406
1986
 
1407
1987
  // TCP-S3: Handle warnings array (alias unavailable)
@@ -1474,8 +2054,45 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1474
2054
 
1475
2055
  } catch (error) {
1476
2056
  // TCP-S3: Handle Coordinator error codes distinctly
2057
+ // TPB-03B: Handle new port block error codes
1477
2058
  const errorCode = error.code || error.reason || error.data?.reason;
1478
2059
 
2060
+ // TPB-03B: TCP_PORT_OUT_OF_BLOCK
2061
+ if (errorCode === 'TCP_PORT_OUT_OF_BLOCK' || errorCode === 'tcp_port_out_of_block') {
2062
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
2063
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
2064
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
2065
+ logger.error("cli.tcp.error.port_out_of_block", {
2066
+ error: error.message,
2067
+ requestedPort,
2068
+ blockStart,
2069
+ blockEnd
2070
+ });
2071
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
2072
+ try { await core.end(); } catch {}
2073
+ process.exit(1);
2074
+ }
2075
+
2076
+ // TPB-03B: TCP_PORT_ALREADY_IN_USE
2077
+ if (errorCode === 'TCP_PORT_ALREADY_IN_USE' || errorCode === 'tcp_port_already_in_use') {
2078
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
2079
+ logger.error("cli.tcp.error.port_already_in_use", { error: error.message, requestedPort });
2080
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
2081
+ try { await core.end(); } catch {}
2082
+ process.exit(1);
2083
+ }
2084
+
2085
+ // TPB-03B: TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT
2086
+ if (errorCode === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || errorCode === 'tcp_port_block_exhausted_for_tenant' ||
2087
+ errorCode === 'TCP_PORT_BLOCK_EXHAUSTED' || errorCode === 'tcp_port_block_exhausted') {
2088
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
2089
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
2090
+ logger.error("cli.tcp.error.block_exhausted", { error: error.message, blockStart, blockEnd });
2091
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
2092
+ try { await core.end(); } catch {}
2093
+ process.exit(1);
2094
+ }
2095
+
1479
2096
  if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
1480
2097
  logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
1481
2098
  process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
@@ -1494,7 +2111,14 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1494
2111
  // TCP_ALIAS_UNAVAILABLE is handled as a warning, not an error
1495
2112
 
1496
2113
  // Generic error handling
1497
- logger.error("cli.ack.wait.failed", { error: error.message, errorCode });
2114
+ logger.error("cli.ack.wait.failed", { error: error.message, errorCode, instanceId, tunnelType: 'tcp' });
2115
+ // TPB-12: Clean up expected requestId on timeout/error (prevents map leak)
2116
+ try {
2117
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2118
+ clearExpectedRequestId(instanceId);
2119
+ } catch (err) {
2120
+ // Ignore cleanup errors
2121
+ }
1498
2122
  process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
1499
2123
  try { await core.end(); } catch {}
1500
2124
  process.exit(1);
@@ -1557,6 +2181,28 @@ export async function connectToRelayTcp(
1557
2181
  try {
1558
2182
  await tunnel.open();
1559
2183
 
2184
+ // TPB-17: Schedule initial proactive refresh via MqttControlPlaneClient for TCP
2185
+ if (mqttClient && assignment.jwt && assignment.leaseId) {
2186
+ try {
2187
+ // Decode JWT to get expiration timestamp (assignment doesn't store exp, must decode JWT)
2188
+ const parts = assignment.jwt.split('.');
2189
+ if (parts.length === 3) {
2190
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
2191
+ const expMs = payload.exp ? payload.exp * 1000 : null;
2192
+ if (expMs) {
2193
+ mqttClient.scheduleRefresh(expMs, assignment.leaseId);
2194
+ logger.debug('tcp.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
2195
+ } else {
2196
+ logger.warn('tcp.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
2197
+ }
2198
+ } else {
2199
+ logger.warn('tcp.refresh.initial_failed', { reason: 'invalid_jwt_format' });
2200
+ }
2201
+ } catch (error) {
2202
+ logger.warn('tcp.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
2203
+ }
2204
+ }
2205
+
1560
2206
  // TCP-S4: Log tunnel active
1561
2207
  logger.info("tunnel.active", {
1562
2208
  target: `tcp://127.0.0.1:${localPort}`,
@@ -1626,4 +2272,591 @@ export async function connectToRelayTcp(
1626
2272
  }
1627
2273
  }
1628
2274
 
2275
+ /**
2276
+ * UDP tunnel implementation (UDP-S1: CLI – UDP entrypoint & WS connect).
2277
+ * Builds and sends MQTT cmd/open payload with protocol:"udp" and tunnelMode:"udpWs-v1".
2278
+ * Reuses existing MQTT control-plane infrastructure.
2279
+ * UDP-S13: --port is the app's listening port (targetPort), CLI never binds it.
2280
+ * @param {number} targetPort - Target port of the local UDP app (from --port)
2281
+ * @param {number} [requestedExternalPort] - Optional requested external port
2282
+ * @param {string} [targetHost] - Target host (defaults to 127.0.0.1, must be loopback)
2283
+ */
2284
+ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost = '127.0.0.1') {
2285
+ logger.info('cli.udp.start', { targetPort, requestedExternalPort, targetHost });
2286
+ process.stdout.write(`⚙️ Initializing UDP tunnel to ${targetHost}:${targetPort}…\n`);
2287
+
2288
+ // UDP-S13: --port is targetPort, not a port we bind to
2289
+ logger.info('cli.udp.target', { target: `${targetHost}:${targetPort}` });
2290
+
2291
+ // 0) Imports (kept local to this command to avoid global side-effects)
2292
+ const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
2293
+ const { MqttCore } = await import("@asyx/mqtt-core");
2294
+ const { waitForAssignment } = await import("../state/assignment.js");
2295
+ const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
2296
+ const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
2297
+ const { readFileSync } = await import("node:fs");
2298
+
2299
+ // 1) Load IoT config (throws with clear messages if misconfigured)
2300
+ let cfg;
2301
+ try {
2302
+ cfg = loadAwsIotConfig();
2303
+ } catch (e) {
2304
+ logger.error("config.error", { error: e?.message || String(e) });
2305
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
2306
+ process.exit(1);
2307
+ }
2308
+
2309
+ logger.info("cli.udp.control_plane.establish", {});
2310
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
2311
+
2312
+ // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
2313
+ const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
2314
+
2315
+ // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
2316
+ const port = 443;
2317
+ const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
2318
+
2319
+ // Load certificates for MQTT TLS options
2320
+ const ca = readFileSync(cfg.caPath);
2321
+ const cert = readFileSync(cfg.certPath);
2322
+ const key = readFileSync(cfg.keyPath);
2323
+
2324
+ // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
2325
+ const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
2326
+
2327
+ // CLI-MQTT-UniqueID-CleanSession: Use base client ID
2328
+ const baseClientId = cfg.clientId;
2329
+
2330
+ // TPB-12: Store instanceId in mutable ref so it can be updated on reconnect
2331
+ const instanceIdRef = { instanceId: null };
2332
+
2333
+ // UDP-S1: Store coordinator references (not used for refresh yet, but kept for consistency)
2334
+ let coordinatorCoreRef = null;
2335
+ let coordinatorIngressRef = null;
2336
+ let deviceIdRef = cfg.clientId;
2337
+ let targetPortRef = targetPort; // UDP-S13: Use targetPort instead of localPort
2338
+ let targetHostRef = targetHost; // UDP-S13: Store targetHost reference
2339
+ // Track subscription state
2340
+ let subscriptionReadyRef = { ready: false };
2341
+
2342
+ // 2) Build MqttControlPlaneClient for connection management
2343
+ const mqttClient = new MqttControlPlaneClient({
2344
+ url: mqttUrl,
2345
+ baseClientId,
2346
+ mqttOptions: {
2347
+ protocol: 'mqtts',
2348
+ port: 443,
2349
+ cert,
2350
+ key,
2351
+ ca,
2352
+ rejectUnauthorized: true,
2353
+ keepalive,
2354
+ connectTimeout: 8000,
2355
+ // ALPN for port 443 (AWS IoT)
2356
+ ALPNProtocols: ['x-amzn-mqtt-ca'],
2357
+ },
2358
+ mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
2359
+ logger,
2360
+ onConnected: async (mqttClientInstance) => {
2361
+ const newClientId = mqttClient.getClientId();
2362
+ logger.debug("mqtt.control_plane.connected", { clientId: newClientId });
2363
+
2364
+ // TPB-12: Update instance registry if clientId changed on reconnect
2365
+ if (instanceIdRef.instanceId && newClientId !== instanceIdRef.instanceId) {
2366
+ const oldInstanceId = instanceIdRef.instanceId;
2367
+ logger.debug("cli.instance.clientid_rotated", {
2368
+ oldInstanceId,
2369
+ newInstanceId: newClientId,
2370
+ tunnelType: 'udp'
2371
+ });
2372
+
2373
+ // Unregister old instance and register new one (similar to TCP/HTTP)
2374
+ const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
2375
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
2376
+
2377
+ const oldContext = getInstance(oldInstanceId);
2378
+ if (oldContext) {
2379
+ const oldAssignment = getAssignmentFn(oldInstanceId);
2380
+ const preservedRequestId = oldContext.expectedRequestId;
2381
+
2382
+ registerInstance(newClientId, {
2383
+ tunnelType: 'udp',
2384
+ setAssignment: setAssignmentFn,
2385
+ getAssignment: getAssignmentFn,
2386
+ metadata: oldContext.metadata || { baseClientId, targetPort, targetHost, requestedExternalPort }
2387
+ });
2388
+
2389
+ if (preservedRequestId) {
2390
+ const { setExpectedRequestId } = await import("../state/instance-registry.js");
2391
+ setExpectedRequestId(newClientId, preservedRequestId);
2392
+ }
2393
+
2394
+ unregisterInstance(oldInstanceId);
2395
+
2396
+ if (oldAssignment) {
2397
+ setAssignmentFn(newClientId, oldAssignment);
2398
+ }
2399
+ }
2400
+
2401
+ instanceIdRef.instanceId = newClientId;
2402
+ }
2403
+
2404
+ process.stdout.write("✅ Control-plane sealed\n");
2405
+
2406
+ // Resubscribe to topics on reconnect
2407
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
2408
+ subscriptionReadyRef.ready = false;
2409
+ try {
2410
+ await mqttClient.subscribe(evtWildcard, 0);
2411
+ logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
2412
+ subscriptionReadyRef.ready = true;
2413
+ } catch (e) {
2414
+ logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
2415
+ subscriptionReadyRef.ready = true;
2416
+ }
2417
+ },
2418
+ onOffline: (reason) => {
2419
+ logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
2420
+ process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
2421
+ subscriptionReadyRef.ready = false;
2422
+ },
2423
+ onFatalError: (reason, err) => {
2424
+ logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
2425
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
2426
+ process.exit(1);
2427
+ },
2428
+ // UDP-S1: Refresh callback not implemented yet (similar to TCP)
2429
+ onRefreshLease: async () => {
2430
+ // UDP refresh not implemented yet - return null to indicate non-fatal
2431
+ logger.warn('udp.refresh.not_implemented', { note: 'UDP refresh not implemented yet' });
2432
+ return null;
2433
+ },
2434
+ });
2435
+
2436
+ // Create Transport adapter and MqttCore
2437
+ const transport = new MqttControlPlaneTransport(mqttClient);
2438
+ const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
2439
+
2440
+ // CLI-IMG-ControlPlane-Watchdog: Expose helpers
2441
+ const isControlPlaneConnected = () => {
2442
+ return mqttClient.isOnline();
2443
+ };
2444
+
2445
+ const waitForControlPlane = () => {
2446
+ if (mqttClient.isOnline()) {
2447
+ return Promise.resolve();
2448
+ }
2449
+ const start = Date.now();
2450
+ return new Promise((resolve, reject) => {
2451
+ const interval = setInterval(() => {
2452
+ if (mqttClient.isOnline()) {
2453
+ clearInterval(interval);
2454
+ resolve();
2455
+ } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
2456
+ clearInterval(interval);
2457
+ reject(new Error('control_plane_timeout'));
2458
+ }
2459
+ }, 250);
2460
+ });
2461
+ };
2462
+
2463
+ const getLastMqttError = () => {
2464
+ return null;
2465
+ };
2466
+
2467
+ const getForceReconnect = () => {
2468
+ return async () => {
2469
+ if (!mqttClient.isOnline()) {
2470
+ await mqttClient.disconnect();
2471
+ await mqttClient.connect();
2472
+ }
2473
+ };
2474
+ };
2475
+
2476
+ // UDP-S1: Store tunnel reference for reconnect hook
2477
+ const tunnelInstanceRef = { tunnel: null };
2478
+
2479
+ // 3) Connect to control plane
2480
+ try {
2481
+ await mqttClient.connect();
2482
+ } catch (e) {
2483
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
2484
+ process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
2485
+ process.exit(1);
2486
+ }
2487
+
2488
+ // TPB-12: Get instanceId (full MQTT clientId) after connection
2489
+ instanceIdRef.instanceId = mqttClient.getClientId();
2490
+ const instanceId = instanceIdRef.instanceId;
2491
+ logger.debug("cli.instance.registered", { instanceId, tunnelType: 'udp', baseClientId });
2492
+
2493
+ // 4) Set up topics and message handling
2494
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
2495
+ const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
2496
+ const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
2497
+
2498
+ // Subscribe to topics after initial connect
2499
+ await core.subscribe(evtWildcard, 0);
2500
+ subscriptionReadyRef.ready = true;
2501
+
2502
+ // 5) Set up message ingress and dispatcher
2503
+ const ingress = new MessageIngress({
2504
+ maxAwaiters: 100,
2505
+ observability: process.env.ASYX_DEBUG === '1',
2506
+ logger
2507
+ });
2508
+
2509
+ ingress.setDispatcher(dispatchEvt);
2510
+
2511
+ // TPB-12: Register instance in registry with per-instance callbacks
2512
+ const { registerInstance, setExpectedRequestId } = await import("../state/instance-registry.js");
2513
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
2514
+
2515
+ registerInstance(instanceId, {
2516
+ tunnelType: 'udp',
2517
+ setAssignment: setAssignmentFn,
2518
+ getAssignment: getAssignmentFn,
2519
+ metadata: { baseClientId, targetPort, targetHost, requestedExternalPort }
2520
+ });
2521
+
2522
+ // UDP-S1: Store coordinator references
2523
+ coordinatorCoreRef = core;
2524
+ coordinatorIngressRef = ingress;
2525
+
2526
+ core.onMessage(async (m) => {
2527
+ try {
2528
+ await ingress.handleMessage(m);
2529
+ } catch (e) {
2530
+ if (e && e.code === "SETUP_REQUIRED") {
2531
+ process.stderr.write(`❌ ${e.message}\n`);
2532
+ try { await core.end(); } catch {}
2533
+ process.exit(2);
2534
+ }
2535
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
2536
+ process.stderr.write(`❌ ${e.message}\n`);
2537
+ try { await core.end(); } catch {}
2538
+ process.exit(1);
2539
+ }
2540
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
2541
+ try { await core.end(); } catch {}
2542
+ process.exit(1);
2543
+ }
2544
+ });
2545
+
2546
+ // 6) Publish cmd/open request with UDP protocol
2547
+ const requestId = crypto.randomUUID();
2548
+ const { getFpHash } = await import("../lib/fingerprint.js");
2549
+ const fingerprint = await getFpHash(cfg.clientId);
2550
+
2551
+ // TPB-12: Track expected requestId for pre-assignment routing
2552
+ setExpectedRequestId(instanceId, requestId);
2553
+
2554
+ // UDP-S1: Build UDP cmd/open payload
2555
+ // UDP-S13: Include targetHost and targetPort (from --port, which is the app's listening port)
2556
+ // TPB-12: Include instanceId for per-instance routing
2557
+ // AC1.2: Include tenantId to match control-plane contract (v4.1 validation phase uses "tunnel" as literal)
2558
+ const openPayload = {
2559
+ requestId,
2560
+ instanceId, // TPB-12: Per-instance routing
2561
+ protocol: 'udp', // UDP-S1: Protocol identifier
2562
+ tunnelMode: 'udpWs-v1', // UDP-S1: Tunnel mode
2563
+ port: targetPort, // UDP-S13: targetPort (app's listening port, not a port we bind)
2564
+ targetHost: targetHost, // UDP-S13: Target host (must be loopback)
2565
+ targetPort: targetPort, // UDP-S13: Target port (from --port)
2566
+ clientId: cfg.clientId,
2567
+ tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
2568
+ ...fingerprint
2569
+ };
2570
+
2571
+ // UDP-S1: Include optional externalPort if provided
2572
+ if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
2573
+ openPayload.externalPort = requestedExternalPort;
2574
+ }
2575
+
2576
+ // Publish the open request
2577
+ await core.publish({
2578
+ topic: cmdOpenTopic,
2579
+ payload: JSON.stringify(openPayload),
2580
+ qos: 1,
2581
+ retain: false
2582
+ });
2583
+
2584
+ logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
2585
+
2586
+ // 7) Wait for ack and assignment
2587
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
2588
+
2589
+ try {
2590
+ const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
2591
+ logger.info("cli.ack.wait.start", { requestId });
2592
+ const assignment = await assignmentPromise;
2593
+ logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'udp' });
2594
+ logger.info("cli.assignment.received", {
2595
+ relayId: assignment.relayId,
2596
+ leaseId: assignment.leaseId,
2597
+ instanceId,
2598
+ tunnelType: 'udp',
2599
+ publicPort: assignment.publicPort
2600
+ });
2601
+
2602
+ // UDP-S1: Validate assignment (AC1.4/AC5.1: comprehensive validation)
2603
+ if (!assignment.relayUrl) {
2604
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
2605
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2606
+ throw error;
2607
+ }
2608
+
2609
+ if (!assignment.tunnelMode || assignment.tunnelMode !== 'udpWs-v1') {
2610
+ const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid tunnelMode in assignment: ${assignment.tunnelMode}, expected udpWs-v1`);
2611
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2612
+ throw error;
2613
+ }
2614
+
2615
+ if (!assignment.protocol || assignment.protocol !== 'udp') {
2616
+ const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid protocol in assignment: ${assignment.protocol}, expected udp`);
2617
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2618
+ throw error;
2619
+ }
2620
+
2621
+ if (!assignment.relayId) {
2622
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayId in assignment');
2623
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2624
+ throw error;
2625
+ }
2626
+
2627
+ if (!assignment.publicPort) {
2628
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing publicPort in assignment');
2629
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2630
+ throw error;
2631
+ }
2632
+
2633
+ const assignmentJwt = assignment.assignmentJwt || assignment.jwt;
2634
+ if (!assignmentJwt) {
2635
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing assignmentJwt in assignment');
2636
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2637
+ throw error;
2638
+ }
2639
+
2640
+ // AC1.4/AC5.1: Verify JWT signature and claims using JWKS (fail fast if JWKS unavailable)
2641
+ try {
2642
+ const { verifyAssignmentJWT } = await import("../lib/jwt-verifier.js");
2643
+ await verifyAssignmentJWT(assignmentJwt, {
2644
+ relayId: assignment.relayId,
2645
+ protocol: 'udp',
2646
+ tunnelMode: 'udpWs-v1',
2647
+ leaseId: assignment.leaseId
2648
+ });
2649
+ logger.debug('udp.assignment.jwt_verified', {
2650
+ relayId: assignment.relayId,
2651
+ leaseId: assignment.leaseId
2652
+ });
2653
+ } catch (jwtError) {
2654
+ // Map all JWT verification errors to UDP_RELAY_UNAVAILABLE
2655
+ const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
2656
+ error.code = 'UDP_RELAY_UNAVAILABLE';
2657
+ logger.error('udp.assignment.jwt_verification_failed', {
2658
+ error: jwtError.message,
2659
+ code: jwtError.code,
2660
+ relayId: assignment.relayId,
2661
+ leaseId: assignment.leaseId
2662
+ });
2663
+ throw error;
2664
+ }
2665
+
2666
+ // TPB-12: Persist assignment using per-instance store
2667
+ try {
2668
+ const { setAssignment } = await import("../state/assignment.js");
2669
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2670
+ setAssignment(instanceId, assignment);
2671
+ clearExpectedRequestId(instanceId);
2672
+ } catch {}
2673
+
2674
+ // UDP-S1: Connect to relay using UdpTunnel
2675
+ // UDP-S13: Pass targetHost and targetPort (not localPort that we bind to)
2676
+ await connectToRelayUdp(
2677
+ assignment,
2678
+ cfg.clientId,
2679
+ targetHost,
2680
+ targetPort,
2681
+ core,
2682
+ ingress,
2683
+ { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
2684
+ tunnelInstanceRef,
2685
+ mqttClient,
2686
+ instanceId
2687
+ );
2688
+
2689
+ } catch (error) {
2690
+ logger.error("cli.ack.wait.failed", { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
2691
+
2692
+ // UDP-S1: Handle UDP-specific error codes
2693
+ if (error.code === 'UDP_RELAY_UNAVAILABLE') {
2694
+ process.stderr.write(`❌ ${error.message}\n`);
2695
+ try { await core.end(); } catch {}
2696
+ process.exit(1);
2697
+ }
2698
+
2699
+ // TPB-12: Clean up expected requestId on timeout/error
2700
+ try {
2701
+ const { clearExpectedRequestId } = await import("../state/instance-registry.js");
2702
+ clearExpectedRequestId(instanceId);
2703
+ } catch (err) {
2704
+ // Ignore cleanup errors
2705
+ }
2706
+ process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
2707
+ try { await core.end(); } catch {}
2708
+ process.exit(1);
2709
+ }
2710
+ }
2711
+
2712
+ export async function connectToRelayUdp(
2713
+ assignment,
2714
+ deviceId,
2715
+ targetHost,
2716
+ targetPort,
2717
+ coordinatorCore,
2718
+ coordinatorIngress,
2719
+ controlPlaneHelpers,
2720
+ tunnelInstanceRef,
2721
+ mqttClient,
2722
+ instanceId = null
2723
+ ) {
2724
+ // Import UDP tunnel logic
2725
+ const { UdpTunnel } = await import("../tunnel/udp-tunnel.js");
2726
+
2727
+ const tunnel = new UdpTunnel({
2728
+ relayUrl: assignment.relayUrl,
2729
+ jwt: assignment.assignmentJwt || assignment.jwt, // UDP-S1: Use assignmentJwt if available
2730
+ deviceId,
2731
+ requestId: assignment.requestId,
2732
+ targetHost, // UDP-S13: Target host (must be loopback)
2733
+ targetPort, // UDP-S13: Target port (app's listening port, not a port we bind)
2734
+ leaseId: assignment.leaseId,
2735
+ relayId: assignment.relayId, // AC5.1: Pass relayId for JWT validation
2736
+ coordinatorCore,
2737
+ coordinatorIngress,
2738
+ isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
2739
+ waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
2740
+ getLastMqttError: controlPlaneHelpers.getLastMqttError,
2741
+ getForceReconnect: controlPlaneHelpers.getForceReconnect,
2742
+ controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
2743
+ log: {
2744
+ info: (msgOrFields, maybeFields) => {
2745
+ if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
2746
+ return logger.info(maybeFields, msgOrFields);
2747
+ },
2748
+ warn: (msgOrFields, maybeFields) => {
2749
+ if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
2750
+ return logger.warn(maybeFields, msgOrFields);
2751
+ },
2752
+ error: (msgOrFields, maybeFields) => {
2753
+ if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
2754
+ return logger.error(maybeFields, msgOrFields);
2755
+ },
2756
+ debug: (msgOrFields, maybeFields) => {
2757
+ if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
2758
+ return logger.debug(maybeFields, msgOrFields);
2759
+ }
2760
+ }
2761
+ });
2762
+
2763
+ // UDP-S1: Store tunnel instance before opening
2764
+ if (tunnelInstanceRef) {
2765
+ tunnelInstanceRef.tunnel = tunnel;
2766
+ }
2767
+
2768
+ try {
2769
+ await tunnel.open();
2770
+
2771
+ // UDP-S1: Log tunnel active
2772
+ // UDP-S13: Use targetHost and targetPort (not localPort)
2773
+ logger.info("tunnel.active", {
2774
+ target: `udp://${targetHost}:${targetPort}`,
2775
+ relayId: assignment.relayId,
2776
+ leaseMs: assignment.leaseMs,
2777
+ publicPort: assignment.publicPort
2778
+ });
2779
+
2780
+ // Tunnel live message
2781
+ // UDP-S13: Print both fqdn and fqdn:publicPort
2782
+ // UDP-S13: Clarify that CLI doesn't bind the service port
2783
+ process.stdout.write(`🔌 UDP tunnel active (ready for datagrams)\n`);
2784
+ process.stdout.write(` App target: ${targetHost}:${targetPort}\n`);
2785
+
2786
+ // UDP-S13: Show public endpoint (both fqdn and fqdn:publicPort)
2787
+ if (assignment.fqdn) {
2788
+ process.stdout.write(` Your UDP server is available at:\n`);
2789
+ process.stdout.write(` ${assignment.fqdn}\n`);
2790
+ if (assignment.publicPort) {
2791
+ process.stdout.write(` ${assignment.fqdn}:${assignment.publicPort}\n`);
2792
+ }
2793
+ } else if (assignment.publicPort) {
2794
+ process.stdout.write(` Public port: ${assignment.publicPort}\n`);
2795
+ }
2796
+
2797
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
2798
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
2799
+ if (logLevel === 'info' || logLevel === 'debug') {
2800
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
2801
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
2802
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
2803
+ }
2804
+
2805
+ process.stdout.write(` Press Ctrl+C to stop\n`);
2806
+
2807
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
2808
+ let shuttingDown = false;
2809
+ const onSig = async (sig) => {
2810
+ if (shuttingDown) return;
2811
+ shuttingDown = true;
2812
+ logger.info("cli.signal.shutdown", { sig });
2813
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
2814
+
2815
+ const killer = setTimeout(() => {
2816
+ logger.error("tunnel.close.timeout", {});
2817
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
2818
+ process.exit(0);
2819
+ }, 3000);
2820
+
2821
+ try {
2822
+ tunnel.close();
2823
+ await mqttClient.disconnect();
2824
+ } catch (e) {
2825
+ logger.debug('tunnel.shutdown.error', { error: e.message });
2826
+ }
2827
+
2828
+ clearTimeout(killer);
2829
+ process.exit(0);
2830
+ };
2831
+
2832
+ process.once("SIGINT", onSig);
2833
+ process.once("SIGTERM", onSig);
2834
+
2835
+ // Keep process alive until SIGINT/SIGTERM
2836
+ await new Promise(() => {});
2837
+
2838
+ } catch (error) {
2839
+ logger.error("tunnel.open.failed", { error: error.message });
2840
+
2841
+ // UDP-S1: Handle UDP_RELAY_UNAVAILABLE error
2842
+ if (error.code === 'UDP_RELAY_UNAVAILABLE') {
2843
+ process.stderr.write(`❌ ${error.message}\n`);
2844
+ } else {
2845
+ process.stderr.write(`❌ Tunnel connection failed: ${error.message}\n`);
2846
+ }
2847
+
2848
+ try {
2849
+ tunnel.close();
2850
+ } catch (e) {
2851
+ logger.debug('tunnel.close.error', { error: e.message });
2852
+ }
2853
+ try {
2854
+ await mqttClient.disconnect();
2855
+ } catch (e) {
2856
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
2857
+ }
2858
+ process.exit(1);
2859
+ }
2860
+ }
2861
+
1629
2862
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }