asyx 0.2.4 → 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.
- package/README.md +101 -1
- package/package.json +10 -3
- package/src/commands/tunnel.js +1215 -40
- package/src/commands/validate-target-host.js +68 -0
- package/src/lib/jwt-verifier.js +260 -0
- package/src/mqtt/events/handlers.js +80 -13
- package/src/mqtt/events/index.js +203 -0
- package/src/state/assignment.js +139 -35
- package/src/state/instance-registry.js +130 -0
- package/src/tunnel/http-tunnel.js +20 -15
- package/src/tunnel/udp-tunnel.js +648 -0
- package/src/udp-v1/framing.js +203 -0
package/src/commands/tunnel.js
CHANGED
|
@@ -94,6 +94,7 @@ export default async function tunnel(args = []) {
|
|
|
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
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.
|
|
135
|
-
logger.error("cli.args.invalid", { reason: "--
|
|
136
|
-
process.stderr.write("Error: --
|
|
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
|
|
|
@@ -160,6 +179,47 @@ export default async function tunnel(args = []) {
|
|
|
160
179
|
return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
|
|
161
180
|
}
|
|
162
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);
|
|
221
|
+
}
|
|
222
|
+
|
|
163
223
|
logger.error("cli.args.unknown", { args: args.join(' ') });
|
|
164
224
|
process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
|
|
165
225
|
process.exit(2);
|
|
@@ -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,16 @@ 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
|
+
}
|
|
216
288
|
} else if (arg === '--external-port' || arg === '--ext-port') {
|
|
217
289
|
// TPB-03B: Parse --external-port flag (alias --ext-port)
|
|
218
290
|
if (i + 1 < args.length) {
|
|
@@ -441,6 +513,9 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
441
513
|
// CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
|
|
442
514
|
const baseClientId = cfg.clientId;
|
|
443
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
|
+
|
|
444
519
|
// QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
|
|
445
520
|
const tunnelInstanceRef = { tunnel: null };
|
|
446
521
|
|
|
@@ -475,7 +550,76 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
475
550
|
logger,
|
|
476
551
|
onConnected: async (mqttClientInstance) => {
|
|
477
552
|
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
478
|
-
|
|
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
|
+
|
|
479
623
|
// QPA-CLI-11: Vault UX messaging - Control-plane sealed
|
|
480
624
|
process.stdout.write("✅ Control-plane sealed\n");
|
|
481
625
|
|
|
@@ -512,18 +656,22 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
512
656
|
process.exit(1);
|
|
513
657
|
},
|
|
514
658
|
// QPA-CLI-05: Wire onRefreshLease to handle JWT refresh via coordinator
|
|
659
|
+
// TPB-12: Capture instanceId in closure for per-instance routing
|
|
515
660
|
onRefreshLease: async () => {
|
|
516
661
|
if (!coordinatorCoreRef || !coordinatorIngressRef) {
|
|
517
662
|
throw new Error("Coordinator not available for refresh");
|
|
518
663
|
}
|
|
519
664
|
|
|
665
|
+
// TPB-12: Get instanceId from mqttClient (captured in closure)
|
|
666
|
+
const refreshInstanceId = mqttClient.getClientId();
|
|
667
|
+
|
|
520
668
|
const { getAssignment } = await import('../state/assignment.js');
|
|
521
669
|
const { getFpHash } = await import('../lib/fingerprint.js');
|
|
522
670
|
|
|
523
|
-
// Get
|
|
524
|
-
const currentAssignment = getAssignment();
|
|
671
|
+
// TPB-12: Get assignment for this specific instance
|
|
672
|
+
const currentAssignment = getAssignment(refreshInstanceId);
|
|
525
673
|
if (!currentAssignment) {
|
|
526
|
-
throw new Error(
|
|
674
|
+
throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
|
|
527
675
|
}
|
|
528
676
|
|
|
529
677
|
const leaseId = currentAssignment.leaseId;
|
|
@@ -535,8 +683,10 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
535
683
|
const refreshRequestId = `refresh-${Date.now()}`;
|
|
536
684
|
const fingerprint = await getFpHash(deviceIdRef);
|
|
537
685
|
|
|
686
|
+
// TPB-12: Include instanceId in refresh payload
|
|
538
687
|
const refreshPayload = {
|
|
539
688
|
requestId: refreshRequestId,
|
|
689
|
+
instanceId: refreshInstanceId, // TPB-12: Per-instance routing
|
|
540
690
|
refreshOf: leaseId,
|
|
541
691
|
proto: 'http',
|
|
542
692
|
localPort: localPortRef,
|
|
@@ -601,6 +751,8 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
601
751
|
// Log awaiter registration for debugging
|
|
602
752
|
logger.debug('jwt.refresh.awaiter.registered', {
|
|
603
753
|
refreshRequestId,
|
|
754
|
+
instanceId: refreshInstanceId,
|
|
755
|
+
tunnelType: 'http',
|
|
604
756
|
timeoutMs: ACK_TIMEOUT_MS,
|
|
605
757
|
expectedType: 'open_ack'
|
|
606
758
|
});
|
|
@@ -608,21 +760,43 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
608
760
|
const ackPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
609
761
|
try {
|
|
610
762
|
const parsed = message.payload;
|
|
611
|
-
const
|
|
763
|
+
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
764
|
+
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
612
765
|
|
|
613
766
|
// Log matching attempts for debugging
|
|
614
|
-
if (parsed?.type === 'open_ack') {
|
|
767
|
+
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
615
768
|
logger.debug('jwt.refresh.awaiter.checking', {
|
|
616
769
|
refreshRequestId,
|
|
617
770
|
receivedRequestId: parsed.requestId,
|
|
618
771
|
receivedType: parsed.type,
|
|
619
|
-
|
|
772
|
+
isAck,
|
|
773
|
+
isReject,
|
|
620
774
|
topic: message.topic
|
|
621
775
|
});
|
|
622
776
|
}
|
|
623
777
|
|
|
624
|
-
|
|
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;
|
|
625
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
|
+
}
|
|
626
800
|
logger.debug('jwt.refresh.awaiter.criteria_error', {
|
|
627
801
|
refreshRequestId,
|
|
628
802
|
error: e.message
|
|
@@ -655,7 +829,19 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
655
829
|
let ackResult;
|
|
656
830
|
try {
|
|
657
831
|
ackResult = await ackPromise;
|
|
658
|
-
} catch (
|
|
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;
|
|
659
845
|
// QPA-CLI-07: On timeout, reconnect control-plane and retry once
|
|
660
846
|
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
661
847
|
logger.debug('jwt.refresh.timeout', {
|
|
@@ -700,21 +886,43 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
700
886
|
const retryAckPromise = coordinatorIngressRef.registerAwaiter((message) => {
|
|
701
887
|
try {
|
|
702
888
|
const parsed = message.payload;
|
|
703
|
-
const
|
|
889
|
+
const isAck = parsed && parsed.type === 'open_ack' && parsed.requestId === refreshRequestId;
|
|
890
|
+
const isReject = parsed && parsed.type === 'open_reject' && parsed.requestId === refreshRequestId;
|
|
704
891
|
|
|
705
892
|
// Log matching attempts for debugging
|
|
706
|
-
if (parsed?.type === 'open_ack') {
|
|
893
|
+
if (parsed?.type === 'open_ack' || parsed?.type === 'open_reject') {
|
|
707
894
|
logger.debug('jwt.refresh.awaiter.retry_checking', {
|
|
708
895
|
refreshRequestId,
|
|
709
896
|
receivedRequestId: parsed.requestId,
|
|
710
897
|
receivedType: parsed.type,
|
|
711
|
-
|
|
898
|
+
isAck,
|
|
899
|
+
isReject,
|
|
712
900
|
topic: message.topic
|
|
713
901
|
});
|
|
714
902
|
}
|
|
715
903
|
|
|
716
|
-
|
|
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;
|
|
717
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
|
+
}
|
|
718
926
|
logger.debug('jwt.refresh.awaiter.retry_criteria_error', {
|
|
719
927
|
refreshRequestId,
|
|
720
928
|
error: e.message
|
|
@@ -728,6 +936,16 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
728
936
|
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
729
937
|
logger.debug('jwt.refresh.timeout.retry_success', { requestId: refreshRequestId });
|
|
730
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
|
+
|
|
731
949
|
logger.error('jwt.refresh.timeout', {
|
|
732
950
|
error: retryError.message,
|
|
733
951
|
action: 'give_up',
|
|
@@ -861,6 +1079,11 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
861
1079
|
process.exit(1);
|
|
862
1080
|
}
|
|
863
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
|
+
|
|
864
1087
|
// 4) Set up topics and message handling
|
|
865
1088
|
// CLI-MQTT-UniqueID-CleanSession: Use baseClientId for topics (not session client ID) to maintain topic stability
|
|
866
1089
|
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
@@ -882,6 +1105,17 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
882
1105
|
|
|
883
1106
|
ingress.setDispatcher(dispatchEvt);
|
|
884
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
|
+
|
|
885
1119
|
// QPA-CLI-05: Store coordinator references for onRefreshLease callback
|
|
886
1120
|
coordinatorCoreRef = core;
|
|
887
1121
|
coordinatorIngressRef = ingress;
|
|
@@ -911,8 +1145,13 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
911
1145
|
const { getFpHash } = await import("../lib/fingerprint.js");
|
|
912
1146
|
const fingerprint = await getFpHash(cfg.clientId);
|
|
913
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
|
|
914
1152
|
const openPayload = {
|
|
915
1153
|
requestId,
|
|
1154
|
+
instanceId, // TPB-12: Per-instance routing
|
|
916
1155
|
proto: 'http',
|
|
917
1156
|
localPort,
|
|
918
1157
|
clientId: cfg.clientId,
|
|
@@ -932,7 +1171,7 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
932
1171
|
retain: false
|
|
933
1172
|
});
|
|
934
1173
|
|
|
935
|
-
logger.info("cli.cmd.open.sent", { requestId });
|
|
1174
|
+
logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'http' });
|
|
936
1175
|
|
|
937
1176
|
// 7) Wait for ack and then connect to relay
|
|
938
1177
|
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
@@ -941,16 +1180,20 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
941
1180
|
const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
|
|
942
1181
|
logger.info("cli.ack.wait.start", { requestId });
|
|
943
1182
|
const assignment = await assignmentPromise;
|
|
944
|
-
logger.info("cli.ack.wait.resolved", { requestId });
|
|
945
|
-
logger.info("cli.assignment.received", { relayId: assignment.relayId });
|
|
946
|
-
// Persist assignment
|
|
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
|
|
947
1186
|
try {
|
|
948
1187
|
const { setAssignment } = await import("../state/assignment.js");
|
|
949
|
-
|
|
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);
|
|
950
1192
|
} catch {}
|
|
951
1193
|
|
|
952
1194
|
// 8) Connect to relay using thin client behavior
|
|
953
1195
|
// QPA-CLI-05: Pass mqttClient for refresh scheduling
|
|
1196
|
+
// TPB-12: Pass instanceId for per-instance assignment routing
|
|
954
1197
|
await connectToRelay(
|
|
955
1198
|
assignment,
|
|
956
1199
|
cfg.clientId,
|
|
@@ -960,11 +1203,19 @@ async function httpTunnel(localPort, secGroupSlug) {
|
|
|
960
1203
|
{ isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
|
|
961
1204
|
secGroupSlug,
|
|
962
1205
|
tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here before infinite promise
|
|
963
|
-
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
|
|
964
1208
|
);
|
|
965
1209
|
|
|
966
1210
|
} catch (error) {
|
|
967
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
|
+
}
|
|
968
1219
|
try { await core.end(); } catch {}
|
|
969
1220
|
process.exit(1);
|
|
970
1221
|
}
|
|
@@ -979,7 +1230,8 @@ export async function connectToRelay(
|
|
|
979
1230
|
controlPlaneHelpers,
|
|
980
1231
|
secGroupSlug,
|
|
981
1232
|
tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
|
|
982
|
-
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
|
|
983
1235
|
) {
|
|
984
1236
|
// Import WebSocket bridge logic (ported from client-mvp)
|
|
985
1237
|
const { HttpTunnel } = await import("../tunnel/http-tunnel.js");
|
|
@@ -1000,6 +1252,8 @@ export async function connectToRelay(
|
|
|
1000
1252
|
controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
|
|
1001
1253
|
// QPA-04: Pass secGroupSlug to HttpTunnel
|
|
1002
1254
|
secGroupSlug,
|
|
1255
|
+
// TPB-12: Pass instanceId to HttpTunnel for per-instance assignment routing
|
|
1256
|
+
instanceId,
|
|
1003
1257
|
log: {
|
|
1004
1258
|
info: (msgOrFields, maybeFields) => {
|
|
1005
1259
|
if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
|
|
@@ -1212,6 +1466,17 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1212
1466
|
// CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
|
|
1213
1467
|
const baseClientId = cfg.clientId;
|
|
1214
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
|
+
|
|
1215
1480
|
// 2) Build MqttControlPlaneClient for connection management
|
|
1216
1481
|
const mqttClient = new MqttControlPlaneClient({
|
|
1217
1482
|
url: mqttUrl,
|
|
@@ -1232,7 +1497,76 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1232
1497
|
logger,
|
|
1233
1498
|
onConnected: async (mqttClientInstance) => {
|
|
1234
1499
|
// QPA-CLI-10: Telemetry logs default to debug for quiet mode
|
|
1235
|
-
|
|
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
|
+
|
|
1236
1570
|
process.stdout.write("✅ Control-plane sealed\n");
|
|
1237
1571
|
|
|
1238
1572
|
// Resubscribe to topics on reconnect
|
|
@@ -1244,24 +1578,219 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1244
1578
|
logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
|
|
1245
1579
|
}
|
|
1246
1580
|
},
|
|
1247
|
-
onOffline: (reason) => {
|
|
1248
|
-
logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
|
|
1249
|
-
process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
|
|
1250
|
-
},
|
|
1251
1581
|
onFatalError: (reason, err) => {
|
|
1252
1582
|
logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
|
|
1253
1583
|
process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
|
|
1254
1584
|
process.exit(1);
|
|
1255
1585
|
},
|
|
1256
|
-
//
|
|
1257
|
-
// 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)
|
|
1258
1587
|
onRefreshLease: async () => {
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
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
|
|
1262
1791
|
});
|
|
1263
|
-
|
|
1264
|
-
return;
|
|
1792
|
+
|
|
1793
|
+
return expMs;
|
|
1265
1794
|
},
|
|
1266
1795
|
});
|
|
1267
1796
|
|
|
@@ -1322,6 +1851,11 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1322
1851
|
process.exit(1);
|
|
1323
1852
|
}
|
|
1324
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
|
+
|
|
1325
1859
|
// 4) Set up topics and message handling
|
|
1326
1860
|
const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
|
|
1327
1861
|
const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
|
|
@@ -1338,6 +1872,21 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1338
1872
|
});
|
|
1339
1873
|
|
|
1340
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;
|
|
1341
1890
|
|
|
1342
1891
|
core.onMessage(async (m) => {
|
|
1343
1892
|
try {
|
|
@@ -1364,10 +1913,15 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1364
1913
|
const { getFpHash } = await import("../lib/fingerprint.js");
|
|
1365
1914
|
const fingerprint = await getFpHash(cfg.clientId);
|
|
1366
1915
|
|
|
1916
|
+
// TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
|
|
1917
|
+
setExpectedRequestId(instanceId, requestId);
|
|
1918
|
+
|
|
1367
1919
|
// TCP-S2: Build TCP cmd/open payload
|
|
1368
1920
|
// E3-S8: Include kind field if provided
|
|
1921
|
+
// TPB-12: Include instanceId for per-instance routing
|
|
1369
1922
|
const openPayload = {
|
|
1370
1923
|
requestId,
|
|
1924
|
+
instanceId, // TPB-12: Per-instance routing
|
|
1371
1925
|
proto: 'tcp', // Protocol identifier
|
|
1372
1926
|
target: target, // "127.0.0.1:<port>" from TCP-S1
|
|
1373
1927
|
clientId: cfg.clientId,
|
|
@@ -1402,7 +1956,7 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1402
1956
|
retain: false
|
|
1403
1957
|
});
|
|
1404
1958
|
|
|
1405
|
-
logger.info("cli.cmd.open.sent", { requestId, protocol: 'tcp', target });
|
|
1959
|
+
logger.info("cli.cmd.open.sent", { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
|
|
1406
1960
|
|
|
1407
1961
|
// 7) Wait for ack and assignment
|
|
1408
1962
|
const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
|
|
@@ -1411,18 +1965,23 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1411
1965
|
const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
|
|
1412
1966
|
logger.info("cli.ack.wait.start", { requestId });
|
|
1413
1967
|
const assignment = await assignmentPromise;
|
|
1414
|
-
logger.info("cli.ack.wait.resolved", { requestId });
|
|
1968
|
+
logger.info("cli.ack.wait.resolved", { requestId, instanceId, tunnelType: 'tcp' });
|
|
1415
1969
|
logger.info("cli.assignment.received", {
|
|
1416
1970
|
relayId: assignment.relayId,
|
|
1417
1971
|
leaseId: assignment.leaseId,
|
|
1972
|
+
instanceId,
|
|
1973
|
+
tunnelType: 'tcp',
|
|
1418
1974
|
tcpAliasFqdn: assignment.tcpAliasFqdn,
|
|
1419
1975
|
publicPort: assignment.publicPort
|
|
1420
1976
|
});
|
|
1421
1977
|
|
|
1422
|
-
// Persist assignment
|
|
1978
|
+
// TPB-12: Persist assignment using per-instance store
|
|
1423
1979
|
try {
|
|
1424
1980
|
const { setAssignment } = await import("../state/assignment.js");
|
|
1425
|
-
|
|
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);
|
|
1426
1985
|
} catch {}
|
|
1427
1986
|
|
|
1428
1987
|
// TCP-S3: Handle warnings array (alias unavailable)
|
|
@@ -1552,7 +2111,14 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
|
|
|
1552
2111
|
// TCP_ALIAS_UNAVAILABLE is handled as a warning, not an error
|
|
1553
2112
|
|
|
1554
2113
|
// Generic error handling
|
|
1555
|
-
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
|
+
}
|
|
1556
2122
|
process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
|
|
1557
2123
|
try { await core.end(); } catch {}
|
|
1558
2124
|
process.exit(1);
|
|
@@ -1615,6 +2181,28 @@ export async function connectToRelayTcp(
|
|
|
1615
2181
|
try {
|
|
1616
2182
|
await tunnel.open();
|
|
1617
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
|
+
|
|
1618
2206
|
// TCP-S4: Log tunnel active
|
|
1619
2207
|
logger.info("tunnel.active", {
|
|
1620
2208
|
target: `tcp://127.0.0.1:${localPort}`,
|
|
@@ -1684,4 +2272,591 @@ export async function connectToRelayTcp(
|
|
|
1684
2272
|
}
|
|
1685
2273
|
}
|
|
1686
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
|
+
|
|
1687
2862
|
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|