asyx 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,7 @@ npm uninstall -g asyx
23
23
 
24
24
  ## Quick Start
25
25
 
26
+
26
27
  1. **Authorize the client**
27
28
  ```bash
28
29
  asyx setup
@@ -86,7 +87,7 @@ That's it! No firewall configuration, no port forwarding, no DNS setup. The `--m
86
87
  ```
87
88
  Removes local device material; re-run `asyx setup` afterwards to restore access.
88
89
 
89
- ## What's New in v0.2.1
90
+ ## What's New in v0.2.3
90
91
 
91
92
  - **Minecraft tunnels made easy**: New `--minecraft` verb—just run `asyx tunnel --minecraft` and share your server instantly. No port numbers, no configuration, no hassle.
92
93
  - **SRV record support**: Minecraft clients automatically discover the correct port via DNS SRV records—players just enter the hostname.
@@ -152,7 +153,7 @@ HTTP tunnels support per-guest authentication via Asyx Quickpass security groups
152
153
 
153
154
  TCP tunnels in v4.1 do not enforce per-guest authentication. Access is owner-only via JWT validation; guests connecting to the public port are anonymous (no per-connection auth). TCP tunnels honor relay-level limits:
154
155
 
155
- **Minecraft Tunnels (v0.2.1+):**
156
+ **Minecraft Tunnels (v0.2.3+):**
156
157
 
157
158
  The `--minecraft` verb makes sharing your Minecraft server incredibly simple:
158
159
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Asyx Command Line Interface",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -957,7 +957,7 @@ async function httpTunnel(localPort, secGroupSlug) {
957
957
  }
958
958
  }
959
959
 
960
- async function connectToRelay(
960
+ export async function connectToRelay(
961
961
  assignment,
962
962
  deviceId,
963
963
  localPort,
@@ -1019,6 +1019,26 @@ async function connectToRelay(
1019
1019
  // TCP-S4: Skip refresh scheduling for TCP tunnels (refresh not implemented yet)
1020
1020
  // HTTP tunnels continue to schedule refresh as before
1021
1021
  // Note: This is a temporary limitation until TCP refresh is implemented
1022
+ if (mqttClient && assignment.jwt && assignment.leaseId) {
1023
+ try {
1024
+ // Decode JWT to get expiration timestamp (assignment doesn't store exp, must decode JWT)
1025
+ const parts = assignment.jwt.split('.');
1026
+ if (parts.length === 3) {
1027
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
1028
+ const expMs = payload.exp ? payload.exp * 1000 : null;
1029
+ if (expMs) {
1030
+ mqttClient.scheduleRefresh(expMs, assignment.leaseId);
1031
+ logger.debug('jwt.refresh.initial_scheduled', { expMs, leaseId: assignment.leaseId });
1032
+ } else {
1033
+ logger.warn('jwt.refresh.initial_failed', { reason: 'no_exp_in_jwt' });
1034
+ }
1035
+ } else {
1036
+ logger.warn('jwt.refresh.initial_failed', { reason: 'invalid_jwt_format' });
1037
+ }
1038
+ } catch (error) {
1039
+ logger.warn('jwt.refresh.initial_failed', { reason: 'jwt_decode_error', error: error.message });
1040
+ }
1041
+ }
1022
1042
 
1023
1043
  // QPA-CLI-11: Vault UX messaging - Final tunnel live message
1024
1044
  const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
@@ -99,11 +99,22 @@ const registry = {
99
99
  const srvFqdn = data.assignment?.srvFqdn || null;
100
100
  const warnings = data.warnings || data.assignment?.warnings || [];
101
101
 
102
+ // Extract JWT with null safety (required for tunnel authentication)
103
+ const jwt = data.assignment?.jwt || data.jwt || null;
104
+ if (!jwt) {
105
+ logger.error('open_ack.missing_jwt', {
106
+ requestId: e.requestId,
107
+ hasAssignment: !!data.assignment,
108
+ hasDataJwt: !!data.jwt
109
+ });
110
+ throw new Error('Missing JWT in assignment');
111
+ }
112
+
102
113
  setAssignment({
103
114
  requestId: e.requestId,
104
115
  relayId: data.relayId,
105
116
  relayUrl: url,
106
- jwt: data.assignment.jwt, // Stored in memory only
117
+ jwt, // Stored in memory only
107
118
  leaseMs: data.leaseMs,
108
119
  leaseId,
109
120
  quickpassSlug, // QPA-CLI-11: Store QuickPass slug for vault UX messaging
@@ -36,7 +36,7 @@ export class TcpTunnel {
36
36
  this.log = log;
37
37
  this.ws = null;
38
38
 
39
- // CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
39
+ // Coordinator connection (not used for TCP - TCP tunnels don't support JWT refresh/reconnect)
40
40
  this.coordinatorCore = coordinatorCore;
41
41
  this.coordinatorIngress = coordinatorIngress;
42
42
 
@@ -51,13 +51,9 @@ export class TcpTunnel {
51
51
  this.heartbeatTimer = null;
52
52
  this.lastActivityMs = Date.now();
53
53
 
54
- // CLI-IMG-WSReconnect: Reconnect properties
55
- this.shouldReconnect = true;
56
- this.retryCount = 0;
57
- // CLI-IMG-Retry-Ceiling: Increase retry ceiling to 60 (configurable)
58
- this.maxRetries = parseInt(process.env.ASYX_TUNNEL_MAX_RETRIES || "60", 10);
59
- this.reconnectTimer = null;
60
- this.headers = null; // Store headers for reuse during reconnects
54
+ // TCP tunnels do NOT support reconnect (unlike HTTP tunnels which have JWT refresh)
55
+ // TCP tunnels exit on WebSocket close to avoid breaking active connections
56
+ this.headers = null; // Store headers for WebSocket connection
61
57
 
62
58
  // TCP-S5: Active TCP stream connections (keyed by numeric streamId)
63
59
  this.activeStreams = new Map(); // streamId (number) -> { localSocket, idleTimer, lastActivity }
@@ -81,18 +77,8 @@ export class TcpTunnel {
81
77
  this.tcpKeepalive = process.env.ASYX_TCP_KEEPALIVE !== '0'; // Enabled by default
82
78
  this.tcpKeepaliveInitialDelay = parseInt(process.env.ASYX_TCP_KEEPALIVE_INITIAL_DELAY_MS || "60000", 10); // 60 seconds
83
79
 
84
- // CLI-JWT-REFRESH: Refresh state machine (simplified for TCP - refresh not implemented yet)
85
- this.refreshState = 'idle';
86
- this.refreshAttempts = 0;
87
- this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
88
- this.refreshRetryTimer = null;
89
- this.refreshDeadline = null;
90
- this.refreshRetryCount = 0;
91
- this.refreshRetryMaxDelay = 30000; // Max 30s between retries
92
-
93
- // CLI-REAUTH: In-band reauth configuration
94
- this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000); // 3 seconds default
95
- this.reauthInFlight = null; // Single-flight guard: Promise or null
80
+ // TCP tunnels do NOT support JWT refresh or in-band reauth (unlike HTTP tunnels)
81
+ // These properties are not used but kept for potential future implementation
96
82
  }
97
83
 
98
84
  async open() {
@@ -101,7 +87,7 @@ export class TcpTunnel {
101
87
 
102
88
  async _attemptConnect() {
103
89
  return new Promise((resolve, reject) => {
104
- // CLI-IMG-WSReconnect: Store headers for reuse during reconnects
90
+ // Store headers for WebSocket connection
105
91
  if (!this.headers) {
106
92
  this.headers = {
107
93
  'Authorization': `Bearer ${this.jwt}`,
@@ -110,7 +96,7 @@ export class TcpTunnel {
110
96
  };
111
97
  }
112
98
 
113
- // CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
99
+ // Clean up previous WebSocket if exists
114
100
  if (this.ws) {
115
101
  this.ws.removeAllListeners();
116
102
  this.ws = null;
@@ -124,10 +110,18 @@ export class TcpTunnel {
124
110
  // Add leaseId query parameter (required by TCP relay)
125
111
  if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
126
112
  urlObj.searchParams.set('leaseId', this.leaseId);
113
+ } else if (!this.leaseId) {
114
+ this.log.error('tcp.ws.missing_leaseId', { relayUrl: this.relayUrl });
115
+ reject(new Error('Missing leaseId for TCP tunnel'));
116
+ return;
127
117
  }
128
118
  // Add token query parameter (required by TCP relay)
129
119
  if (this.jwt && !urlObj.searchParams.has('token')) {
130
120
  urlObj.searchParams.set('token', this.jwt);
121
+ } else if (!this.jwt) {
122
+ this.log.error('tcp.ws.missing_jwt', { relayUrl: this.relayUrl, hasLeaseId: !!this.leaseId });
123
+ reject(new Error('Missing JWT for TCP tunnel'));
124
+ return;
131
125
  }
132
126
  wsUrl = urlObj.toString();
133
127
  }
@@ -145,8 +139,7 @@ export class TcpTunnel {
145
139
  this.ws.on('open', () => {
146
140
  this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - TCP proxy mode active');
147
141
 
148
- // CLI-IMG-WSReconnect: Reset retry count on successful connection
149
- this.retryCount = 0;
142
+ // Connection successful
150
143
 
151
144
  // TCP-S5: Start PING keepalive timer after WebSocket opens
152
145
  // NOTE: Do NOT start legacy JSON heartbeat for TCP - relay only accepts binary tcp-v1 frames
@@ -196,8 +189,10 @@ export class TcpTunnel {
196
189
  // TCP-S4: Close all active TCP streams on WebSocket close
197
190
  this.closeAllStreams();
198
191
 
199
- // CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
200
- this.scheduleReconnect(code, reason);
192
+ // TCP tunnels exit on WebSocket close (unlike HTTP tunnels which have JWT refresh)
193
+ // Reconnecting would break active TCP connections and create new leaseId conflicts
194
+ this.log.info('TCP tunnel exiting due to WebSocket close');
195
+ process.exit(1);
201
196
  });
202
197
 
203
198
  this.ws.on('error', (err) => {
@@ -205,8 +200,9 @@ export class TcpTunnel {
205
200
  // TCP-S5: Stop PING keepalive on error
206
201
  this.stopPingKeepalive();
207
202
 
208
- // CLI-IMG-WSReconnect: Handle connection errors with reconnect
209
- this.scheduleReconnect(null, err.message);
203
+ // TCP tunnels exit on WebSocket error (unlike HTTP tunnels which have JWT refresh)
204
+ this.log.info('TCP tunnel exiting due to WebSocket error');
205
+ process.exit(1);
210
206
  });
211
207
  });
212
208
  }
@@ -316,8 +312,7 @@ export class TcpTunnel {
316
312
  this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
317
313
  }
318
314
 
319
- // Disable reconnects on protocol violation
320
- this.shouldReconnect = false;
315
+ // Protocol violation - exit (TCP tunnels don't support reconnect)
321
316
  }
322
317
 
323
318
  // TCP-S5: Handle STREAM_OPEN frame
@@ -349,16 +344,51 @@ export class TcpTunnel {
349
344
  // Track stream activity
350
345
  const lastActivity = Date.now();
351
346
 
347
+ // Buffer for STREAM_DATA frames that arrive before socket is connected
348
+ const dataBuffer = [];
349
+ let socketConnected = false;
350
+
352
351
  // Handle local socket connection
353
352
  localSocket.on('connect', () => {
354
353
  this.log.debug({ streamId }, 'tcp.stream.local_connected');
354
+ socketConnected = true;
355
+
356
+ // Update stream state to mark socket as connected
357
+ const stream = this.activeStreams.get(streamId);
358
+ if (stream) {
359
+ stream.socketConnected = true;
360
+ }
361
+
362
+ // Flush any buffered STREAM_DATA frames
363
+ if (dataBuffer.length > 0) {
364
+ this.log.debug({ streamId, bufferedCount: dataBuffer.length }, 'tcp.stream.flushing_buffered_data');
365
+ if (stream && stream.localSocket && !stream.localSocket.destroyed) {
366
+ for (const bufferedData of dataBuffer) {
367
+ const written = stream.localSocket.write(bufferedData);
368
+ if (!written) {
369
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure_on_flush');
370
+ }
371
+ }
372
+ }
373
+ dataBuffer.length = 0; // Clear buffer
374
+ if (stream) {
375
+ stream.dataBuffer = []; // Also clear in stream state
376
+ }
377
+ }
355
378
  });
356
379
 
357
380
  // Pipe data from local socket to relay (using tcp-v1 framing)
358
381
  localSocket.on('data', (data) => {
359
- // Reset idle timer on activity
382
+ // Check if stream still exists (may have been closed)
360
383
  const stream = this.activeStreams.get(streamId);
361
- if (stream && stream.idleTimer) {
384
+ if (!stream) {
385
+ // Stream was closed, ignore data
386
+ this.log.debug({ streamId }, 'tcp.stream.local_data.ignored_stream_closed');
387
+ return;
388
+ }
389
+
390
+ // Reset idle timer on activity
391
+ if (stream.idleTimer) {
362
392
  clearTimeout(stream.idleTimer);
363
393
  stream.idleTimer = setTimeout(() => {
364
394
  this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
@@ -435,11 +465,13 @@ export class TcpTunnel {
435
465
  this.closeStream(streamId);
436
466
  });
437
467
 
438
- // Store stream state
468
+ // Store stream state (include dataBuffer and socketConnected for handleStreamData)
439
469
  this.activeStreams.set(streamId, {
440
470
  localSocket,
441
471
  idleTimer,
442
- lastActivity
472
+ lastActivity,
473
+ dataBuffer, // Buffer for data arriving before socket connects
474
+ socketConnected: false // Will be set to true in 'connect' handler
443
475
  });
444
476
  }
445
477
 
@@ -474,9 +506,34 @@ export class TcpTunnel {
474
506
  }, this.idleTimeoutMs);
475
507
  }
476
508
 
477
- // Write data to local socket
509
+ // Write data to local socket (buffer if not connected yet)
478
510
  if (stream.localSocket && !stream.localSocket.destroyed) {
479
- stream.localSocket.write(frame.payload);
511
+ const isConnected = stream.localSocket.readyState === 'open';
512
+
513
+ if (!isConnected) {
514
+ // Buffer data until socket is connected (prevents data loss)
515
+ if (stream.dataBuffer) {
516
+ stream.dataBuffer.push(frame.payload);
517
+ this.log.debug({
518
+ streamId,
519
+ bufferedSize: stream.dataBuffer.length,
520
+ readyState: stream.localSocket.readyState
521
+ }, 'tcp.stream_data.buffered_pending_connect');
522
+ } else {
523
+ this.log.warn({ streamId, readyState: stream.localSocket.readyState }, 'tcp.stream_data.local_socket_not_ready');
524
+ }
525
+ return;
526
+ }
527
+
528
+ const written = stream.localSocket.write(frame.payload);
529
+ if (!written) {
530
+ // Backpressure - socket buffer is full
531
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure');
532
+ // The socket will emit 'drain' when ready, but for now we'll continue
533
+ // In the future, we might want to pause reading from relay
534
+ }
535
+ } else {
536
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_unavailable');
480
537
  }
481
538
  }
482
539
 
@@ -752,98 +809,12 @@ export class TcpTunnel {
752
809
  }
753
810
  }
754
811
 
755
- // CLI-IMG-WSReconnect: Reconnect scheduling and logic
756
- scheduleReconnect(code, reason) {
757
- // Check if we should reconnect
758
- if (!this.shouldReconnect) {
759
- this.log.info('Reconnect disabled, returning');
760
- return;
761
- }
762
-
763
- // CLI-IMG-Retry-Ceiling: Check retry limit with descriptive messaging
764
- if (this.retryCount >= this.maxRetries) {
765
- this.log.error(
766
- { retryCount: this.retryCount, maxRetries: this.maxRetries },
767
- "Control-plane reconnect attempts exhausted; please restart the CLI"
768
- );
769
- process.exit(1);
770
- }
771
-
772
- // Check for JWT expiration - attempt refresh instead of exiting
773
- // Handle both jwt_invalid (code 1000) and EJWT_EXPIRED (code 1008) cases
774
- const reasonStr = reason?.toString() || '';
775
- const lower = reasonStr.toLowerCase();
776
- const isJwtInvalid = code === 1000 && lower.includes('jwt_invalid');
777
- const isJwtExpired = code === 1008 && lower.includes('ejwt_expired');
778
-
779
- if (isJwtInvalid || isJwtExpired) {
780
- const triggerReason = isJwtInvalid ? 'jwt_invalid' : 'ejwt_expired';
781
- this.log.warn('jwt.refresh.trigger', { triggerReason, code, reason: reasonStr });
782
- // TCP-S4: Refresh not implemented yet for TCP
783
- this.log.warn('tcp.refresh.not_implemented', { triggerReason });
784
- // For now, just reconnect (refresh will be implemented in future work)
785
- // this.attemptJwtRefresh();
786
- // return;
787
- }
788
-
789
- // Calculate exponential backoff with jitter
790
- const baseDelay = Math.min(1000 * Math.pow(2, this.retryCount), 30000); // Max 30s
791
- const jitter = Math.random() * 0.4 - 0.2; // ±20% jitter
792
- const delay = Math.max(1000, Math.floor(baseDelay * (1 + jitter)));
793
-
794
- this.retryCount++;
795
-
796
- // QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
797
- // reasonStr is already declared above for JWT check
798
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
799
- if (isNormalClose) {
800
- this.log.debug({
801
- delay,
802
- retryCount: this.retryCount,
803
- maxRetries: this.maxRetries,
804
- code,
805
- reason: reasonStr
806
- }, 'Tunnel WS reconnect scheduled');
807
- } else {
808
- this.log.warn({
809
- delay,
810
- retryCount: this.retryCount,
811
- maxRetries: this.maxRetries,
812
- code,
813
- reason: reasonStr
814
- }, 'Tunnel WS reconnect scheduled');
815
- }
816
-
817
- // Schedule reconnect attempt
818
- this.reconnectTimer = setTimeout(() => {
819
- this.attemptReconnect();
820
- }, delay);
821
- }
822
-
823
- async attemptReconnect() {
824
- try {
825
- this.log.info({ retryCount: this.retryCount }, 'Attempting to reconnect...');
826
- await this._attemptConnect();
827
- this.log.info('Reconnected successfully');
828
-
829
- // CLI-IMG-WSReconnect: Clear reconnect timer on successful reconnect
830
- if (this.reconnectTimer) {
831
- clearTimeout(this.reconnectTimer);
832
- this.reconnectTimer = null;
833
- }
834
- } catch (error) {
835
- this.log.error({ error: error.message, retryCount: this.retryCount }, 'Reconnect attempt failed');
836
- // scheduleReconnect will be called from the error handler in _attemptConnect
837
- }
838
- }
812
+ // TCP tunnels do NOT support reconnect (removed - was causing issues with active connections)
813
+ // HTTP tunnels have JWT refresh, so they can reconnect safely
814
+ // TCP tunnels exit on WebSocket close to avoid breaking active TCP streams
839
815
 
840
816
  close() {
841
- // CLI-IMG-WSReconnect: Disable reconnects and clear timer
842
- this.shouldReconnect = false;
843
- if (this.reconnectTimer) {
844
- clearTimeout(this.reconnectTimer);
845
- this.reconnectTimer = null;
846
- }
817
+ // TCP tunnels don't have reconnect logic, so no cleanup needed
847
818
 
848
819
  // TCP-S5: Stop PING keepalive
849
820
  this.stopPingKeepalive();