asyx 0.1.2 → 0.2.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.
@@ -0,0 +1,896 @@
1
+ // TCP Tunnel - Pure proxy mode with no JWT validation
2
+ // Mirrors HttpTunnel structure but handles TCP streams instead of HTTP requests
3
+ // TCP-S5: Uses binary tcp-v1 framing protocol
4
+ import WebSocket from 'ws';
5
+ import net from 'net';
6
+ import crypto from 'node:crypto';
7
+ // CLI-REAUTH: Control frame helper for in-band reauth
8
+ import { sendControlAndWaitAck, dispatchControlFrame, clearAllWaiters } from './ws-control.js';
9
+ // TCP-S5: tcp-v1 binary framing
10
+ import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, TcpV1FramingError } from '../tcp-v1/framing.js';
11
+
12
+ export class TcpTunnel {
13
+ constructor({
14
+ relayUrl,
15
+ jwt,
16
+ deviceId,
17
+ requestId,
18
+ localPort,
19
+ leaseId, // E3-S3: Lease ID for TCP relay WebSocket query parameters
20
+ log,
21
+ coordinatorCore,
22
+ coordinatorIngress,
23
+ // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
24
+ isControlPlaneConnected = () => true,
25
+ waitForControlPlane = () => Promise.resolve(),
26
+ getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
27
+ getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
28
+ controlPlaneTimeoutMs = 60000,
29
+ }) {
30
+ this.relayUrl = relayUrl;
31
+ this.jwt = jwt; // Accept JWT as-is (no validation)
32
+ this.deviceId = deviceId;
33
+ this.requestId = requestId;
34
+ this.localPort = localPort;
35
+ this.leaseId = leaseId; // E3-S3: Store leaseId for WebSocket query parameters
36
+ this.log = log;
37
+ this.ws = null;
38
+
39
+ // CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
40
+ this.coordinatorCore = coordinatorCore;
41
+ this.coordinatorIngress = coordinatorIngress;
42
+
43
+ // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
44
+ this.isControlPlaneConnected = isControlPlaneConnected;
45
+ this.waitForControlPlane = waitForControlPlane;
46
+ this.getLastMqttError = getLastMqttError; // QPA-CLI-02: Store helper to get last MQTT error
47
+ this.getForceReconnect = getForceReconnect; // QPA-CLI-03: Store helper to force reconnect
48
+ this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
49
+
50
+ // CRT-Relay-E: Heartbeat properties
51
+ this.heartbeatTimer = null;
52
+ this.lastActivityMs = Date.now();
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
61
+
62
+ // TCP-S5: Active TCP stream connections (keyed by numeric streamId)
63
+ this.activeStreams = new Map(); // streamId (number) -> { localSocket, idleTimer, lastActivity }
64
+ this.nextStreamId = 1; // TCP-S5: Next stream ID to allocate (starts at 1)
65
+
66
+ // TCP-S5: Binary frame buffer for partial frames
67
+ this.frameBuffer = Buffer.alloc(0);
68
+
69
+ // TCP-S5: Protocol violation flag (close tunnel on protocol errors)
70
+ this.protocolViolation = false;
71
+
72
+ // TCP-S4: Idle timeout configuration (15 minutes default, parity with relay)
73
+ this.idleTimeoutMs = parseInt(process.env.ASYX_TCP_IDLE_TIMEOUT_MS || "900000", 10); // 15 minutes
74
+
75
+ // TCP-S5: PING/PONG keepalive configuration (30 seconds default, parity with relay)
76
+ this.pingIntervalMs = parseInt(process.env.ASYX_TCP_PING_INTERVAL_MS || "30000", 10); // 30 seconds
77
+ this.pingTimer = null;
78
+ this.lastPongMs = Date.now();
79
+
80
+ // TCP-S4: TCP keepalive configuration
81
+ this.tcpKeepalive = process.env.ASYX_TCP_KEEPALIVE !== '0'; // Enabled by default
82
+ this.tcpKeepaliveInitialDelay = parseInt(process.env.ASYX_TCP_KEEPALIVE_INITIAL_DELAY_MS || "60000", 10); // 60 seconds
83
+
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
96
+ }
97
+
98
+ async open() {
99
+ await this._attemptConnect();
100
+ }
101
+
102
+ async _attemptConnect() {
103
+ return new Promise((resolve, reject) => {
104
+ // CLI-IMG-WSReconnect: Store headers for reuse during reconnects
105
+ if (!this.headers) {
106
+ this.headers = {
107
+ 'Authorization': `Bearer ${this.jwt}`,
108
+ 'X-Asyx-DeviceId': this.deviceId,
109
+ 'X-Asyx-RequestId': this.requestId
110
+ };
111
+ }
112
+
113
+ // CLI-IMG-WSReconnect: Clean up previous WebSocket if exists
114
+ if (this.ws) {
115
+ this.ws.removeAllListeners();
116
+ this.ws = null;
117
+ }
118
+
119
+ // E3-S3: TCP relay requires leaseId and token as query parameters
120
+ // For TCP tunnels, append query parameters to the WebSocket URL
121
+ let wsUrl = this.relayUrl;
122
+ if (this.relayUrl.includes('/tcp')) {
123
+ const urlObj = new URL(this.relayUrl);
124
+ // Add leaseId query parameter (required by TCP relay)
125
+ if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
126
+ urlObj.searchParams.set('leaseId', this.leaseId);
127
+ }
128
+ // Add token query parameter (required by TCP relay)
129
+ if (this.jwt && !urlObj.searchParams.has('token')) {
130
+ urlObj.searchParams.set('token', this.jwt);
131
+ }
132
+ wsUrl = urlObj.toString();
133
+ }
134
+
135
+ // Connect to relay with TLS (rejectUnauthorized: true by default)
136
+ // TCP-S5: Specify tcp-v1 subprotocol for TCP tunnels
137
+ const wsOptions = {
138
+ headers: this.headers,
139
+ rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
140
+ // TCP-S5: Request tcp-v1 subprotocol
141
+ protocol: 'tcp-v1'
142
+ };
143
+ this.ws = new WebSocket(wsUrl, wsOptions);
144
+
145
+ this.ws.on('open', () => {
146
+ this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - TCP proxy mode active');
147
+
148
+ // CLI-IMG-WSReconnect: Reset retry count on successful connection
149
+ this.retryCount = 0;
150
+
151
+ // TCP-S5: Start PING keepalive timer after WebSocket opens
152
+ // NOTE: Do NOT start legacy JSON heartbeat for TCP - relay only accepts binary tcp-v1 frames
153
+ this.startPingKeepalive();
154
+
155
+ resolve();
156
+ });
157
+
158
+ this.ws.on('message', (data, isBinary) => {
159
+ // CRT-Relay-E: Update activity on any message
160
+ this.lastActivityMs = Date.now();
161
+
162
+ // TCP-S5: All tcp-v1 frames are binary - relay only accepts binary frames
163
+ // Note: ws library may pass Buffer for binary, but isBinary flag should be true
164
+ // If isBinary is false but data is a Buffer, treat it as binary anyway (ws library quirk)
165
+ const isActuallyBinary = isBinary || Buffer.isBuffer(data);
166
+
167
+ if (isActuallyBinary) {
168
+ this.handleBinaryFrame(data);
169
+ return;
170
+ }
171
+
172
+ // TCP-S5: Non-binary (text) frames are NOT supported for TCP tunnels
173
+ // The Go relay WS server only accepts binary tcp-v1 frames; any text frame
174
+ // triggers a framing error and closes the WS, killing the tunnel.
175
+ // Do NOT parse JSON control frames, heartbeats, or reauth for TCP.
176
+ this.log.warn({ size: data.length, isBinary, isBuffer: Buffer.isBuffer(data) }, 'tcp.text_frame_rejected', {
177
+ note: 'TCP tunnel only accepts binary tcp-v1 frames; text frames will cause relay to close connection'
178
+ });
179
+ // Do not process text frames - they will cause protocol violations on the relay
180
+ });
181
+
182
+ this.ws.on('close', (code, reason) => {
183
+ // QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
184
+ const reasonStr = reason?.toString() || '';
185
+ const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
186
+ if (isNormalClose) {
187
+ this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
188
+ } else {
189
+ this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
190
+ }
191
+ // TCP-S5: Stop PING keepalive on close
192
+ this.stopPingKeepalive();
193
+ // TCP-S5: No JSON control frames for TCP - no cleanup needed
194
+ // CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
195
+
196
+ // TCP-S4: Close all active TCP streams on WebSocket close
197
+ this.closeAllStreams();
198
+
199
+ // CLI-IMG-WSReconnect: Schedule reconnect instead of exiting
200
+ this.scheduleReconnect(code, reason);
201
+ });
202
+
203
+ this.ws.on('error', (err) => {
204
+ this.log.error({ err }, 'Tunnel WS error');
205
+ // TCP-S5: Stop PING keepalive on error
206
+ this.stopPingKeepalive();
207
+
208
+ // CLI-IMG-WSReconnect: Handle connection errors with reconnect
209
+ this.scheduleReconnect(null, err.message);
210
+ });
211
+ });
212
+ }
213
+
214
+ // TCP-S5: Handle binary tcp-v1 frames
215
+ handleBinaryFrame(data) {
216
+ // Append new data to frame buffer
217
+ this.frameBuffer = Buffer.concat([this.frameBuffer, Buffer.from(data)]);
218
+
219
+ // Process complete frames from buffer
220
+ while (this.frameBuffer.length >= FRAME_HEADER_SIZE) {
221
+ try {
222
+ const frame = decodeFrame(this.frameBuffer, 0);
223
+
224
+ // Remove consumed bytes from buffer
225
+ this.frameBuffer = this.frameBuffer.subarray(frame.consumed);
226
+
227
+ // Handle protocol violations
228
+ try {
229
+ validateFrame(frame);
230
+ } catch (err) {
231
+ if (err instanceof TcpV1FramingError) {
232
+ this.log.error({
233
+ error: err.message,
234
+ code: err.code,
235
+ frameType: frame.type,
236
+ streamId: frame.streamId,
237
+ payloadSize: frame.payload.length
238
+ }, 'tcp.protocol_violation');
239
+ this.handleProtocolViolation(err);
240
+ return; // Stop processing on protocol violation
241
+ }
242
+ throw err; // Re-throw non-framing errors
243
+ }
244
+
245
+ // Route frame by type
246
+ this.routeFrame(frame);
247
+ } catch (err) {
248
+ if (err instanceof TcpV1FramingError) {
249
+ // Incomplete frame - wait for more data
250
+ if (err.code === 'INCOMPLETE_FRAME') {
251
+ break; // Wait for more data
252
+ }
253
+ // Other framing errors are protocol violations
254
+ this.log.error({
255
+ error: err.message,
256
+ code: err.code
257
+ }, 'tcp.protocol_violation');
258
+ this.handleProtocolViolation(err);
259
+ return;
260
+ }
261
+ // Unexpected error
262
+ this.log.error({ error: err.message }, 'tcp.frame_decode_error');
263
+ this.handleProtocolViolation(new TcpV1FramingError(`Frame decode error: ${err.message}`, 'DECODE_ERROR'));
264
+ return;
265
+ }
266
+ }
267
+ }
268
+
269
+ // TCP-S5: Route frame by type and streamId
270
+ routeFrame(frame) {
271
+ switch (frame.type) {
272
+ case FrameType.STREAM_OPEN:
273
+ this.handleStreamOpen(frame);
274
+ break;
275
+ case FrameType.STREAM_DATA:
276
+ this.handleStreamData(frame);
277
+ break;
278
+ case FrameType.STREAM_CLOSE:
279
+ this.handleStreamClose(frame);
280
+ break;
281
+ case FrameType.STREAM_ERROR:
282
+ this.handleStreamError(frame);
283
+ break;
284
+ case FrameType.PING:
285
+ this.handlePing(frame);
286
+ break;
287
+ case FrameType.PONG:
288
+ this.handlePong(frame);
289
+ break;
290
+ default:
291
+ // Unknown frame type - protocol violation
292
+ this.log.error({ frameType: frame.type }, 'tcp.unknown_frame_type');
293
+ this.handleProtocolViolation(
294
+ new TcpV1FramingError(`Unknown frame type: ${frame.type}`, 'UNKNOWN_FRAME_TYPE')
295
+ );
296
+ }
297
+ }
298
+
299
+ // TCP-S5: Handle protocol violation - close tunnel
300
+ handleProtocolViolation(error) {
301
+ if (this.protocolViolation) {
302
+ return; // Already handling violation
303
+ }
304
+
305
+ this.protocolViolation = true;
306
+ this.log.error({
307
+ error: error.message,
308
+ code: error.code
309
+ }, 'tcp.protocol_violation_closing_tunnel');
310
+
311
+ // Close all streams
312
+ this.closeAllStreams();
313
+
314
+ // Close WebSocket connection
315
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
316
+ this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
317
+ }
318
+
319
+ // Disable reconnects on protocol violation
320
+ this.shouldReconnect = false;
321
+ }
322
+
323
+ // TCP-S5: Handle STREAM_OPEN frame
324
+ handleStreamOpen(frame) {
325
+ const streamId = frame.streamId;
326
+
327
+ if (this.activeStreams.has(streamId)) {
328
+ this.log.warn({ streamId }, 'tcp.stream.open.duplicate');
329
+ // Close existing stream and open new one
330
+ this.closeStream(streamId);
331
+ }
332
+
333
+ this.log.info({ streamId }, 'tcp.stream.open');
334
+
335
+ // Open local TCP socket to 127.0.0.1:localPort
336
+ const localSocket = net.createConnection({
337
+ host: '127.0.0.1',
338
+ port: this.localPort,
339
+ keepAlive: this.tcpKeepalive,
340
+ keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
341
+ });
342
+
343
+ // TCP-S5: Set up idle timeout for this stream (parity with relay)
344
+ const idleTimer = setTimeout(() => {
345
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
346
+ this.closeStream(streamId);
347
+ }, this.idleTimeoutMs);
348
+
349
+ // Track stream activity
350
+ const lastActivity = Date.now();
351
+
352
+ // Handle local socket connection
353
+ localSocket.on('connect', () => {
354
+ this.log.debug({ streamId }, 'tcp.stream.local_connected');
355
+ });
356
+
357
+ // Pipe data from local socket to relay (using tcp-v1 framing)
358
+ localSocket.on('data', (data) => {
359
+ // Reset idle timer on activity
360
+ const stream = this.activeStreams.get(streamId);
361
+ if (stream && stream.idleTimer) {
362
+ clearTimeout(stream.idleTimer);
363
+ stream.idleTimer = setTimeout(() => {
364
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
365
+ this.closeStream(streamId);
366
+ }, this.idleTimeoutMs);
367
+ stream.lastActivity = Date.now();
368
+ }
369
+
370
+ // Send data to relay using tcp-v1 STREAM_DATA frame
371
+ if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
372
+ try {
373
+ // Split large payloads into multiple frames (max 64 KiB per frame)
374
+ const maxChunkSize = 64 * 1024;
375
+ let offset = 0;
376
+ while (offset < data.length) {
377
+ const chunk = data.subarray(offset, Math.min(offset + maxChunkSize, data.length));
378
+ const frame = encodeFrame({
379
+ type: FrameType.STREAM_DATA,
380
+ streamId: streamId,
381
+ payload: chunk
382
+ });
383
+ this.ws.send(frame, { binary: true });
384
+ offset += chunk.length;
385
+ }
386
+ } catch (err) {
387
+ if (err instanceof TcpV1FramingError) {
388
+ this.log.error({ streamId, error: err.message }, 'tcp.frame_encode_error');
389
+ this.handleProtocolViolation(err);
390
+ } else {
391
+ this.log.error({ streamId, error: err.message }, 'tcp.send_error');
392
+ }
393
+ }
394
+ }
395
+ });
396
+
397
+ // Handle local socket errors
398
+ localSocket.on('error', (err) => {
399
+ this.log.error({ streamId, error: err.message }, 'tcp.stream.local_error');
400
+ if (err.code === 'ECONNREFUSED') {
401
+ 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
+ }
414
+ }
415
+ }
416
+ this.closeStream(streamId);
417
+ });
418
+
419
+ // Handle local socket close
420
+ localSocket.on('close', () => {
421
+ this.log.debug({ streamId }, 'tcp.stream.local_closed');
422
+ // Send STREAM_CLOSE to relay
423
+ if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
424
+ try {
425
+ const closeFrame = encodeFrame({
426
+ type: FrameType.STREAM_CLOSE,
427
+ streamId: streamId,
428
+ payload: Buffer.alloc(0)
429
+ });
430
+ this.ws.send(closeFrame, { binary: true });
431
+ } catch (frameErr) {
432
+ this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
433
+ }
434
+ }
435
+ this.closeStream(streamId);
436
+ });
437
+
438
+ // Store stream state
439
+ this.activeStreams.set(streamId, {
440
+ localSocket,
441
+ idleTimer,
442
+ lastActivity
443
+ });
444
+ }
445
+
446
+ // TCP-S5: Handle STREAM_DATA frame (route by streamId)
447
+ handleStreamData(frame) {
448
+ const streamId = frame.streamId;
449
+
450
+ if (streamId === 0) {
451
+ this.log.error({ streamId }, 'tcp.stream_data.invalid_stream_id');
452
+ this.handleProtocolViolation(
453
+ new TcpV1FramingError('STREAM_DATA frame has invalid streamId (0)', 'INVALID_STREAM_ID')
454
+ );
455
+ return;
456
+ }
457
+
458
+ const stream = this.activeStreams.get(streamId);
459
+ if (!stream) {
460
+ this.log.warn({ streamId }, 'tcp.stream_data.unknown_stream');
461
+ return;
462
+ }
463
+
464
+ // Update activity
465
+ stream.lastActivity = Date.now();
466
+ this.lastActivityMs = Date.now();
467
+
468
+ // Reset idle timer
469
+ if (stream.idleTimer) {
470
+ clearTimeout(stream.idleTimer);
471
+ stream.idleTimer = setTimeout(() => {
472
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
473
+ this.closeStream(streamId);
474
+ }, this.idleTimeoutMs);
475
+ }
476
+
477
+ // Write data to local socket
478
+ if (stream.localSocket && !stream.localSocket.destroyed) {
479
+ stream.localSocket.write(frame.payload);
480
+ }
481
+ }
482
+
483
+ // TCP-S5: Handle STREAM_CLOSE frame
484
+ handleStreamClose(frame) {
485
+ const streamId = frame.streamId;
486
+
487
+ if (streamId === 0) {
488
+ this.log.error({ streamId }, 'tcp.stream_close.invalid_stream_id');
489
+ this.handleProtocolViolation(
490
+ new TcpV1FramingError('STREAM_CLOSE frame has invalid streamId (0)', 'INVALID_STREAM_ID')
491
+ );
492
+ return;
493
+ }
494
+
495
+ this.log.debug({ streamId }, 'tcp.stream.relay_closed');
496
+ this.closeStream(streamId);
497
+ }
498
+
499
+ // TCP-S5: Handle STREAM_ERROR frame
500
+ handleStreamError(frame) {
501
+ const streamId = frame.streamId;
502
+ const errorMsg = frame.payload.toString('utf8');
503
+
504
+ this.log.error({ streamId, error: errorMsg }, 'tcp.stream.relay_error');
505
+ this.closeStream(streamId);
506
+ }
507
+
508
+ // TCP-S5: Handle PING frame (respond with PONG)
509
+ handlePing(frame) {
510
+ this.lastActivityMs = Date.now();
511
+
512
+ if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
513
+ try {
514
+ const pongFrame = encodeFrame({
515
+ type: FrameType.PONG,
516
+ streamId: 0,
517
+ payload: frame.payload // Echo ping payload in pong
518
+ });
519
+ this.ws.send(pongFrame, { binary: true });
520
+ } catch (err) {
521
+ this.log.error({ error: err.message }, 'tcp.pong.encode_error');
522
+ }
523
+ }
524
+ }
525
+
526
+ // TCP-S5: Handle PONG frame (update lastPongMs)
527
+ handlePong(frame) {
528
+ this.lastPongMs = Date.now();
529
+ this.lastActivityMs = Date.now();
530
+ }
531
+
532
+ // TCP-S4: Handle TCP stream open frame from relay (LEGACY - DEPRECATED)
533
+ // TCP-S5: This method should NOT be called - binary tcp-v1 frames use handleStreamOpen instead
534
+ // If somehow called, it will attempt to send JSON frames which will cause protocol violations
535
+ handleTcpStream(msg) {
536
+ // TCP-S5: Legacy JSON frame handler - should not be used with tcp-v1 binary framing
537
+ this.log.warn('tcp.legacy_json_handler_called', {
538
+ note: 'handleTcpStream should not be called with tcp-v1 binary framing - use handleStreamOpen instead'
539
+ });
540
+ // Extract stream ID and other metadata
541
+ const streamId = msg.streamId || msg.sid || crypto.randomUUID();
542
+ const leaseId = msg.leaseId || this.requestId; // Fallback to requestId if leaseId not provided
543
+
544
+ this.log.info({ streamId, leaseId }, 'tcp.stream.open');
545
+
546
+ // Open local TCP socket to 127.0.0.1:localPort
547
+ const localSocket = net.createConnection({
548
+ host: '127.0.0.1',
549
+ port: this.localPort,
550
+ keepAlive: this.tcpKeepalive,
551
+ keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
552
+ });
553
+
554
+ // TCP-S4: Set up idle timeout for this stream
555
+ const idleTimer = setTimeout(() => {
556
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
557
+ this.closeStream(streamId);
558
+ }, this.idleTimeoutMs);
559
+
560
+ // Track stream activity to reset idle timer
561
+ let lastStreamActivity = Date.now();
562
+
563
+ // Handle local socket connection
564
+ localSocket.on('connect', () => {
565
+ this.log.debug({ streamId }, 'tcp.stream.local_connected');
566
+ // TCP-S5: Do NOT send JSON frames - relay only accepts binary tcp-v1 frames
567
+ // Stream open acknowledgment is implicit in tcp-v1 protocol (no ack frame needed)
568
+ this.log.debug({ streamId }, 'tcp.stream.local_connected');
569
+ });
570
+
571
+ // Pipe data from local socket to relay
572
+ localSocket.on('data', (data) => {
573
+ lastStreamActivity = Date.now();
574
+ // Reset idle timer on activity
575
+ if (idleTimer) {
576
+ clearTimeout(idleTimer);
577
+ const newTimer = setTimeout(() => {
578
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
579
+ this.closeStream(streamId);
580
+ }, this.idleTimeoutMs);
581
+ this.activeStreams.set(streamId, {
582
+ ...this.activeStreams.get(streamId),
583
+ idleTimer: newTimer
584
+ });
585
+ }
586
+
587
+ // TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_DATA frames instead
588
+ // This legacy handler should not be called with tcp-v1 binary framing
589
+ this.log.warn('tcp.legacy_json_data_send_blocked', {
590
+ streamId,
591
+ note: 'Legacy JSON data send blocked - use binary tcp-v1 STREAM_DATA frames instead'
592
+ });
593
+ });
594
+
595
+ // Handle local socket errors
596
+ localSocket.on('error', (err) => {
597
+ this.log.error({ streamId, error: err.message }, 'tcp.stream.local_error');
598
+ if (err.code === 'ECONNREFUSED') {
599
+ this.log.error({ port: this.localPort }, 'Local TCP service refused connection');
600
+ // TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_ERROR frames instead
601
+ // This legacy handler should not be called with tcp-v1 binary framing
602
+ this.log.warn('tcp.legacy_json_error_send_blocked', {
603
+ streamId,
604
+ error: 'ECONNREFUSED',
605
+ note: 'Legacy JSON error send blocked - use binary tcp-v1 STREAM_ERROR frames instead'
606
+ });
607
+ this.closeStream(streamId);
608
+ }
609
+ });
610
+
611
+ // Handle local socket close
612
+ localSocket.on('close', () => {
613
+ this.log.debug({ streamId }, 'tcp.stream.local_closed');
614
+ // TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_CLOSE frames instead
615
+ // This legacy handler should not be called with tcp-v1 binary framing
616
+ this.log.warn('tcp.legacy_json_close_send_blocked', {
617
+ streamId,
618
+ note: 'Legacy JSON close send blocked - use binary tcp-v1 STREAM_CLOSE frames instead'
619
+ });
620
+ this.closeStream(streamId);
621
+ });
622
+
623
+ // Store stream state
624
+ this.activeStreams.set(streamId, {
625
+ localSocket,
626
+ relayStream: null, // Will be set when we receive data from relay
627
+ idleTimer,
628
+ leaseId,
629
+ lastActivity: lastStreamActivity
630
+ });
631
+ }
632
+
633
+ // TCP-S4: Handle TCP data frame from relay
634
+ handleTcpData(msg) {
635
+ const streamId = msg.streamId || msg.sid;
636
+ if (!streamId) {
637
+ this.log.warn('tcp.data.missing_stream_id');
638
+ return;
639
+ }
640
+
641
+ const stream = this.activeStreams.get(streamId);
642
+ if (!stream) {
643
+ this.log.warn({ streamId }, 'tcp.data.unknown_stream');
644
+ return;
645
+ }
646
+
647
+ // Update activity
648
+ stream.lastActivity = Date.now();
649
+ this.lastActivityMs = Date.now();
650
+
651
+ // Reset idle timer
652
+ if (stream.idleTimer) {
653
+ clearTimeout(stream.idleTimer);
654
+ const newTimer = setTimeout(() => {
655
+ this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
656
+ this.closeStream(streamId);
657
+ }, this.idleTimeoutMs);
658
+ stream.idleTimer = newTimer;
659
+ }
660
+
661
+ // Decode data and write to local socket
662
+ try {
663
+ const data = Buffer.from(msg.data, 'base64');
664
+ if (stream.localSocket && !stream.localSocket.destroyed) {
665
+ stream.localSocket.write(data);
666
+ }
667
+ } catch (e) {
668
+ this.log.error({ streamId, error: e.message }, 'tcp.data.decode_error');
669
+ }
670
+ }
671
+
672
+ // TCP-S5: Start PING keepalive timer (parity with relay)
673
+ startPingKeepalive() {
674
+ if (this.pingIntervalMs <= 0) {
675
+ this.log.debug('PING keepalive disabled (ASYX_TCP_PING_INTERVAL_MS <= 0)');
676
+ return;
677
+ }
678
+
679
+ this.pingTimer = setInterval(() => {
680
+ this.sendPing();
681
+ }, this.pingIntervalMs);
682
+
683
+ this.log.debug({ interval: this.pingIntervalMs }, 'tcp.ping.keepalive.started');
684
+ }
685
+
686
+ // TCP-S5: Stop PING keepalive timer
687
+ stopPingKeepalive() {
688
+ if (this.pingTimer) {
689
+ clearInterval(this.pingTimer);
690
+ this.pingTimer = null;
691
+ this.log.debug('tcp.ping.keepalive.stopped');
692
+ }
693
+ }
694
+
695
+ // TCP-S5: Send PING frame
696
+ sendPing() {
697
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.protocolViolation) {
698
+ return;
699
+ }
700
+
701
+ try {
702
+ const pingFrame = encodeFrame({
703
+ type: FrameType.PING,
704
+ streamId: 0,
705
+ payload: Buffer.from(Date.now().toString()) // Include timestamp for debugging
706
+ });
707
+ this.ws.send(pingFrame, { binary: true });
708
+ } catch (err) {
709
+ this.log.error({ error: err.message }, 'tcp.ping.encode_error');
710
+ }
711
+ }
712
+
713
+ // TCP-S4: Handle TCP stream close frame from relay
714
+ handleTcpClose(msg) {
715
+ const streamId = msg.streamId || msg.sid;
716
+ if (!streamId) {
717
+ this.log.warn('tcp.close.missing_stream_id');
718
+ return;
719
+ }
720
+
721
+ this.log.debug({ streamId }, 'tcp.stream.relay_closed');
722
+ this.closeStream(streamId);
723
+ }
724
+
725
+ // TCP-S4: Close a specific TCP stream
726
+ closeStream(streamId) {
727
+ const stream = this.activeStreams.get(streamId);
728
+ if (!stream) {
729
+ return;
730
+ }
731
+
732
+ // Clear idle timer
733
+ if (stream.idleTimer) {
734
+ clearTimeout(stream.idleTimer);
735
+ }
736
+
737
+ // Close local socket
738
+ if (stream.localSocket && !stream.localSocket.destroyed) {
739
+ stream.localSocket.destroy();
740
+ }
741
+
742
+ // Remove from active streams
743
+ this.activeStreams.delete(streamId);
744
+ this.log.debug({ streamId }, 'tcp.stream.closed');
745
+ }
746
+
747
+ // TCP-S4: Close all active TCP streams
748
+ closeAllStreams() {
749
+ const streamIds = Array.from(this.activeStreams.keys());
750
+ for (const streamId of streamIds) {
751
+ this.closeStream(streamId);
752
+ }
753
+ }
754
+
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
+ }
839
+
840
+ 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
+ }
847
+
848
+ // TCP-S5: Stop PING keepalive
849
+ this.stopPingKeepalive();
850
+
851
+ // TCP-S4: Close all active TCP streams
852
+ this.closeAllStreams();
853
+
854
+ // TCP-S5: No JSON control frames for TCP - no cleanup needed
855
+ // CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
856
+
857
+ // TCP-S5: Stop PING keepalive before closing
858
+ this.stopPingKeepalive();
859
+ if (this.ws) {
860
+ this.ws.close();
861
+ }
862
+ }
863
+
864
+ // TCP-S5: Legacy JSON heartbeat methods DISABLED for TCP tunnels
865
+ // TCP tunnels use binary tcp-v1 PING/PONG keepalive instead (see startPingKeepalive/sendPing)
866
+ // These methods are kept for potential HTTP tunnel compatibility but are NOT called for TCP
867
+ // and will NOT send JSON frames on TCP WebSocket connections.
868
+
869
+ getHeartbeatInterval() {
870
+ // TCP-S5: Always return Infinity for TCP to prevent JSON heartbeat
871
+ return Infinity;
872
+ }
873
+
874
+ startHeartbeat() {
875
+ // TCP-S5: Disabled for TCP tunnels - do not send JSON heartbeats
876
+ // Use tcp-v1 PING/PONG keepalive instead (startPingKeepalive)
877
+ this.log.debug('Legacy JSON heartbeat disabled for TCP tunnel (use tcp-v1 PING/PONG)');
878
+ return;
879
+ }
880
+
881
+ sendHeartbeat() {
882
+ // TCP-S5: Disabled for TCP tunnels - do not send JSON heartbeats
883
+ // Use tcp-v1 PING/PONG keepalive instead (sendPing)
884
+ // This method will NOT send JSON frames on TCP WebSocket connections
885
+ return;
886
+ }
887
+
888
+ stopHeartbeat() {
889
+ // TCP-S5: No-op for TCP tunnels (heartbeat not started)
890
+ if (this.heartbeatTimer) {
891
+ clearInterval(this.heartbeatTimer);
892
+ this.heartbeatTimer = null;
893
+ }
894
+ }
895
+ }
896
+