asyx 0.5.8 → 0.6.0

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