asyx 0.2.2 → 0.2.4

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
@@ -87,7 +87,7 @@ That's it! No firewall configuration, no port forwarding, no DNS setup. The `--m
87
87
  ```
88
88
  Removes local device material; re-run `asyx setup` afterwards to restore access.
89
89
 
90
- ## What's New in v0.2.2
90
+ ## What's New in v0.2.3
91
91
 
92
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.
93
93
  - **SRV record support**: Minecraft clients automatically discover the correct port via DNS SRV records—players just enter the hostname.
@@ -153,7 +153,7 @@ HTTP tunnels support per-guest authentication via Asyx Quickpass security groups
153
153
 
154
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:
155
155
 
156
- **Minecraft Tunnels (v0.2.2+):**
156
+ **Minecraft Tunnels (v0.2.3+):**
157
157
 
158
158
  The `--minecraft` verb makes sharing your Minecraft server incredibly simple:
159
159
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Asyx Command Line Interface",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -93,7 +93,7 @@ export default async function tunnel(args = []) {
93
93
  process.stdout.write(` asyx tunnel connect Connect to control plane (TLS 8883)\n`);
94
94
  process.stdout.write(` asyx tunnel --http --port <n> Create HTTP tunnel on local port <n>\n`);
95
95
  process.stdout.write(` asyx tunnel --http --port <n> --secgroup <slug> Create HTTP tunnel with QuickPass security group\n`);
96
- process.stdout.write(` asyx tunnel --tcp --port <n> Create TCP tunnel on local port <n> (localhost only)\n`);
96
+ process.stdout.write(` asyx tunnel --tcp --port <n> [--external-port <p>] Create TCP tunnel on local port <n> (localhost only)\n`);
97
97
  process.stdout.write(` asyx tunnel --minecraft [--port 25565] [--name <svc>] Create Minecraft TCP tunnel (expands to --tcp --port 25565 --kind minecraft)\n`);
98
98
  process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
99
99
  process.stdout.write(` asyx tunnel --help Show this help\n`);
@@ -157,7 +157,7 @@ export default async function tunnel(args = []) {
157
157
  process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
158
158
  process.exit(2);
159
159
  }
160
- return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind);
160
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
161
161
  }
162
162
 
163
163
  logger.error("cli.args.unknown", { args: args.join(' ') });
@@ -213,6 +213,22 @@ function parseArgs(args) {
213
213
  process.stderr.write("Error: --secgroup requires a slug\n");
214
214
  process.exit(2);
215
215
  }
216
+ } else if (arg === '--external-port' || arg === '--ext-port') {
217
+ // TPB-03B: Parse --external-port flag (alias --ext-port)
218
+ if (i + 1 < args.length) {
219
+ const externalPort = parseInt(args[i + 1], 10);
220
+ if (isNaN(externalPort) || externalPort < 1 || externalPort > 65535) {
221
+ logger.error("cli.args.external_port_invalid", { value: args[i + 1] });
222
+ process.stderr.write(`Error: Invalid external port number: ${args[i + 1]}\n`);
223
+ process.exit(2);
224
+ }
225
+ parsed.externalPort = externalPort;
226
+ i++; // Skip next argument as it's the external port value
227
+ } else {
228
+ logger.error("cli.args.external_port_missing", {});
229
+ process.stderr.write("Error: --external-port requires a port number\n");
230
+ process.exit(2);
231
+ }
216
232
  } else if (arg === '--help' || arg === '-h') {
217
233
  parsed.help = true;
218
234
  }
@@ -757,11 +773,8 @@ async function httpTunnel(localPort, secGroupSlug) {
757
773
  // Update jwtMeta for HttpTunnel
758
774
  tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
759
775
 
760
- // Record refresh timestamp and delta metrics
761
- const { recordRefresh } = await import('../state/assignment.js');
762
- const deltaMs = recordRefresh(Date.now());
763
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
764
- logger.debug('jwt.refresh.delta', { deltaMs });
776
+ // Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
777
+ // to avoid double-counting when refresh happens via in-band reauth
765
778
 
766
779
  // Try in-band reauth if WebSocket is open
767
780
  if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
@@ -1149,8 +1162,10 @@ function isLocalhostTarget(target) {
1149
1162
  * Reuses existing MQTT control-plane infrastructure.
1150
1163
  * @param {number} localPort - Local port number
1151
1164
  * @param {string} [serviceName] - Optional service name
1165
+ * @param {string} [kind] - Optional service kind
1166
+ * @param {number} [requestedExternalPort] - Optional requested external port (TPB-03B)
1152
1167
  */
1153
- async function tcpTunnel(localPort, serviceName, kind = null) {
1168
+ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
1154
1169
  logger.info('cli.tcp.start', { localPort, serviceName });
1155
1170
  process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1156
1171
 
@@ -1361,6 +1376,7 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1361
1376
 
1362
1377
  // TCP-S2: Include optional opts.name if service name provided
1363
1378
  // E3-S8: Include opts.kind if provided
1379
+ // TPB-03B: Include requestedExternalPort if provided
1364
1380
  openPayload.opts = {
1365
1381
  preferredPort: null // Can be wired to a flag later if needed
1366
1382
  };
@@ -1372,6 +1388,11 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1372
1388
  if (kind) {
1373
1389
  openPayload.opts.kind = kind;
1374
1390
  }
1391
+
1392
+ // TPB-03B: Include requestedExternalPort in opts (null if omitted)
1393
+ if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
1394
+ openPayload.opts.requestedExternalPort = requestedExternalPort;
1395
+ }
1375
1396
 
1376
1397
  // Publish the open request
1377
1398
  await core.publish({
@@ -1474,8 +1495,45 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1474
1495
 
1475
1496
  } catch (error) {
1476
1497
  // TCP-S3: Handle Coordinator error codes distinctly
1498
+ // TPB-03B: Handle new port block error codes
1477
1499
  const errorCode = error.code || error.reason || error.data?.reason;
1478
1500
 
1501
+ // TPB-03B: TCP_PORT_OUT_OF_BLOCK
1502
+ if (errorCode === 'TCP_PORT_OUT_OF_BLOCK' || errorCode === 'tcp_port_out_of_block') {
1503
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
1504
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
1505
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
1506
+ logger.error("cli.tcp.error.port_out_of_block", {
1507
+ error: error.message,
1508
+ requestedPort,
1509
+ blockStart,
1510
+ blockEnd
1511
+ });
1512
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
1513
+ try { await core.end(); } catch {}
1514
+ process.exit(1);
1515
+ }
1516
+
1517
+ // TPB-03B: TCP_PORT_ALREADY_IN_USE
1518
+ if (errorCode === 'TCP_PORT_ALREADY_IN_USE' || errorCode === 'tcp_port_already_in_use') {
1519
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
1520
+ logger.error("cli.tcp.error.port_already_in_use", { error: error.message, requestedPort });
1521
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
1522
+ try { await core.end(); } catch {}
1523
+ process.exit(1);
1524
+ }
1525
+
1526
+ // TPB-03B: TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT
1527
+ if (errorCode === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || errorCode === 'tcp_port_block_exhausted_for_tenant' ||
1528
+ errorCode === 'TCP_PORT_BLOCK_EXHAUSTED' || errorCode === 'tcp_port_block_exhausted') {
1529
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
1530
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
1531
+ logger.error("cli.tcp.error.block_exhausted", { error: error.message, blockStart, blockEnd });
1532
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
1533
+ try { await core.end(); } catch {}
1534
+ process.exit(1);
1535
+ }
1536
+
1479
1537
  if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
1480
1538
  logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
1481
1539
  process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
@@ -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
@@ -156,6 +167,29 @@ const registry = {
156
167
  }
157
168
 
158
169
  // TCP-S3: Handle TCP-specific error codes
170
+ // TPB-03B: Handle new port block error codes
171
+ if (d.reason === 'TCP_PORT_OUT_OF_BLOCK' || d.reason === 'tcp_port_out_of_block') {
172
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
173
+ const blockStart = d.blockStart || 'A';
174
+ const blockEnd = d.blockEnd || 'B';
175
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
176
+ process.exit(1);
177
+ }
178
+
179
+ if (d.reason === 'TCP_PORT_ALREADY_IN_USE' || d.reason === 'tcp_port_already_in_use') {
180
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
181
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
182
+ process.exit(1);
183
+ }
184
+
185
+ if (d.reason === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || d.reason === 'tcp_port_block_exhausted_for_tenant' ||
186
+ d.reason === 'TCP_PORT_BLOCK_EXHAUSTED' || d.reason === 'tcp_port_block_exhausted') {
187
+ const blockStart = d.blockStart || 'A';
188
+ const blockEnd = d.blockEnd || 'B';
189
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
190
+ process.exit(1);
191
+ }
192
+
159
193
  if (d.reason === 'TCP_PORT_CAPACITY_EXHAUSTED' || d.reason === 'tcp_port_capacity_exhausted') {
160
194
  process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
161
195
  process.exit(1);
@@ -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
@@ -330,7 +325,7 @@ export class TcpTunnel {
330
325
  this.closeStream(streamId);
331
326
  }
332
327
 
333
- this.log.info({ streamId }, 'tcp.stream.open');
328
+ this.log.info({ streamId, localPort: this.localPort }, 'tcp.stream.open');
334
329
 
335
330
  // Open local TCP socket to 127.0.0.1:localPort
336
331
  const localSocket = net.createConnection({
@@ -340,6 +335,9 @@ export class TcpTunnel {
340
335
  keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
341
336
  });
342
337
 
338
+ // Log when connection attempt starts
339
+ this.log.debug({ streamId, localPort: this.localPort }, 'tcp.stream.local_connecting');
340
+
343
341
  // TCP-S5: Set up idle timeout for this stream (parity with relay)
344
342
  const idleTimer = setTimeout(() => {
345
343
  this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
@@ -352,13 +350,42 @@ export class TcpTunnel {
352
350
  // Handle local socket connection
353
351
  localSocket.on('connect', () => {
354
352
  this.log.debug({ streamId }, 'tcp.stream.local_connected');
353
+
354
+ // Update stream state to mark socket as connected
355
+ const stream = this.activeStreams.get(streamId);
356
+ if (stream) {
357
+ stream.socketConnected = true;
358
+ }
359
+
360
+ // Flush any buffered STREAM_DATA frames from stream.dataBuffer
361
+ if (stream && stream.dataBuffer && stream.dataBuffer.length > 0) {
362
+ this.log.debug({ streamId, bufferedCount: stream.dataBuffer.length }, 'tcp.stream.flushing_buffered_data');
363
+ if (stream.localSocket && !stream.localSocket.destroyed) {
364
+ const buf = stream.dataBuffer;
365
+ while (buf.length > 0) {
366
+ const chunk = buf.shift();
367
+ const written = stream.localSocket.write(chunk);
368
+ if (!written) {
369
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure_on_flush');
370
+ }
371
+ }
372
+ }
373
+ stream.dataBuffer = []; // Clear buffer after flush
374
+ }
355
375
  });
356
376
 
357
377
  // Pipe data from local socket to relay (using tcp-v1 framing)
358
378
  localSocket.on('data', (data) => {
359
- // Reset idle timer on activity
379
+ // Check if stream still exists (may have been closed)
360
380
  const stream = this.activeStreams.get(streamId);
361
- if (stream && stream.idleTimer) {
381
+ if (!stream) {
382
+ // Stream was closed, ignore data
383
+ this.log.debug({ streamId }, 'tcp.stream.local_data.ignored_stream_closed');
384
+ return;
385
+ }
386
+
387
+ // Reset idle timer on activity
388
+ if (stream.idleTimer) {
362
389
  clearTimeout(stream.idleTimer);
363
390
  stream.idleTimer = setTimeout(() => {
364
391
  this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
@@ -396,21 +423,21 @@ export class TcpTunnel {
396
423
 
397
424
  // Handle local socket errors
398
425
  localSocket.on('error', (err) => {
399
- this.log.error({ streamId, error: err.message }, 'tcp.stream.local_error');
426
+ this.log.error({ streamId, error: err.message, code: err.code, localPort: this.localPort }, 'tcp.stream.local_error');
400
427
  if (err.code === 'ECONNREFUSED') {
401
428
  this.log.error({ port: this.localPort }, 'Local TCP service refused connection');
402
- // Send STREAM_ERROR to relay
403
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
404
- try {
405
- const errorFrame = encodeFrame({
406
- type: FrameType.STREAM_ERROR,
407
- streamId: streamId,
408
- payload: Buffer.from(`ECONNREFUSED: ${err.message}`)
409
- });
410
- this.ws.send(errorFrame, { binary: true });
411
- } catch (frameErr) {
412
- this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
413
- }
429
+ }
430
+ // Send STREAM_ERROR to relay for all errors so it knows the connection failed
431
+ if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
432
+ try {
433
+ const errorFrame = encodeFrame({
434
+ type: FrameType.STREAM_ERROR,
435
+ streamId: streamId,
436
+ payload: Buffer.from(`${err.code || 'ERROR'}: ${err.message}`)
437
+ });
438
+ this.ws.send(errorFrame, { binary: true });
439
+ } catch (frameErr) {
440
+ this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
414
441
  }
415
442
  }
416
443
  this.closeStream(streamId);
@@ -435,11 +462,13 @@ export class TcpTunnel {
435
462
  this.closeStream(streamId);
436
463
  });
437
464
 
438
- // Store stream state
465
+ // Store stream state (include dataBuffer and socketConnected for handleStreamData)
439
466
  this.activeStreams.set(streamId, {
440
467
  localSocket,
441
468
  idleTimer,
442
- lastActivity
469
+ lastActivity,
470
+ dataBuffer: [], // Buffer for data arriving before socket connects
471
+ socketConnected: false // Will be set to true in 'connect' handler
443
472
  });
444
473
  }
445
474
 
@@ -474,9 +503,34 @@ export class TcpTunnel {
474
503
  }, this.idleTimeoutMs);
475
504
  }
476
505
 
477
- // Write data to local socket
506
+ // Write data to local socket (buffer if not connected yet)
478
507
  if (stream.localSocket && !stream.localSocket.destroyed) {
479
- stream.localSocket.write(frame.payload);
508
+ const isConnected = stream.localSocket.readyState === 'open';
509
+
510
+ if (!isConnected) {
511
+ // Buffer data until socket is connected (prevents data loss)
512
+ if (stream.dataBuffer) {
513
+ stream.dataBuffer.push(frame.payload);
514
+ this.log.debug({
515
+ streamId,
516
+ bufferedSize: stream.dataBuffer.length,
517
+ readyState: stream.localSocket.readyState
518
+ }, 'tcp.stream_data.buffered_pending_connect');
519
+ } else {
520
+ this.log.warn({ streamId, readyState: stream.localSocket.readyState }, 'tcp.stream_data.local_socket_not_ready');
521
+ }
522
+ return;
523
+ }
524
+
525
+ const written = stream.localSocket.write(frame.payload);
526
+ if (!written) {
527
+ // Backpressure - socket buffer is full
528
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure');
529
+ // The socket will emit 'drain' when ready, but for now we'll continue
530
+ // In the future, we might want to pause reading from relay
531
+ }
532
+ } else {
533
+ this.log.warn({ streamId }, 'tcp.stream_data.local_socket_unavailable');
480
534
  }
481
535
  }
482
536
 
@@ -752,98 +806,12 @@ export class TcpTunnel {
752
806
  }
753
807
  }
754
808
 
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
- }
809
+ // TCP tunnels do NOT support reconnect (removed - was causing issues with active connections)
810
+ // HTTP tunnels have JWT refresh, so they can reconnect safely
811
+ // TCP tunnels exit on WebSocket close to avoid breaking active TCP streams
839
812
 
840
813
  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
- }
814
+ // TCP tunnels don't have reconnect logic, so no cleanup needed
847
815
 
848
816
  // TCP-S5: Stop PING keepalive
849
817
  this.stopPingKeepalive();