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.
- package/README.md +103 -17
- package/SECURITY.md +5 -3
- package/package.json +15 -22
- package/src/commands/name.js +23 -0
- package/src/commands/reject-messages.js +54 -0
- package/src/commands/setup.js +98 -102
- package/src/commands/tunnel.js +304 -2316
- package/src/lib/naming.js +81 -0
- package/src/main.js +24 -6
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
- package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
- package/vendor/tunnel-core/dist/errors.d.ts +49 -0
- package/vendor/tunnel-core/dist/errors.js +53 -0
- package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
- package/vendor/tunnel-core/dist/flows/http.js +585 -0
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
- package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
- package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
- package/vendor/tunnel-core/dist/flows/udp.js +376 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
- package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
- package/vendor/tunnel-core/dist/lib/logger.js +58 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
- package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
- package/vendor/tunnel-core/dist/lifecycle.js +29 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
- package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
- package/vendor/tunnel-core/dist/state/assignment.js +322 -0
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
- package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
- package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
- package/vendor/tunnel-core/dist/types.d.ts +24 -0
- package/vendor/tunnel-core/dist/types.js +2 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
- package/vendor/tunnel-core/package.json +34 -0
- package/src/control-plane/MqttControlPlaneClient.js +0 -1196
- package/src/control-plane/MqttControlPlaneTransport.js +0 -150
- package/src/lib/fingerprint.js +0 -115
- package/src/lib/jwt-verifier.js +0 -260
- package/src/lib/logger.js +0 -62
- package/src/mqtt/awaiter-map.js +0 -247
- package/src/mqtt/events/handlers.js +0 -300
- package/src/mqtt/events/index.js +0 -222
- package/src/mqtt/events/schemas.js +0 -58
- package/src/mqtt/ingress.js +0 -182
- package/src/state/assignment.js +0 -333
- package/src/tcp-v1/framing.js +0 -203
- package/src/tunnel/http-tunnel.js +0 -1694
- package/src/tunnel/tcp-tunnel.js +0 -862
- package/src/tunnel/udp-tunnel.js +0 -708
- package/src/tunnel/ws-control.js +0 -135
- package/src/udp-v1/framing.js +0 -203
package/src/tunnel/tcp-tunnel.js
DELETED
|
@@ -1,862 +0,0 @@
|
|
|
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
|
-
// Coordinator connection (not used for TCP - TCP tunnels don't support JWT refresh/reconnect)
|
|
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
|
-
// 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
|
|
57
|
-
|
|
58
|
-
// TCP-S5: Active TCP stream connections (keyed by numeric streamId)
|
|
59
|
-
this.activeStreams = new Map(); // streamId (number) -> { localSocket, idleTimer, lastActivity }
|
|
60
|
-
this.nextStreamId = 1; // TCP-S5: Next stream ID to allocate (starts at 1)
|
|
61
|
-
|
|
62
|
-
// TCP-S5: Binary frame buffer for partial frames
|
|
63
|
-
this.frameBuffer = Buffer.alloc(0);
|
|
64
|
-
|
|
65
|
-
// TCP-S5: Protocol violation flag (close tunnel on protocol errors)
|
|
66
|
-
this.protocolViolation = false;
|
|
67
|
-
|
|
68
|
-
// TCP-S4: Idle timeout configuration (15 minutes default, parity with relay)
|
|
69
|
-
this.idleTimeoutMs = parseInt(process.env.ASYX_TCP_IDLE_TIMEOUT_MS || "900000", 10); // 15 minutes
|
|
70
|
-
|
|
71
|
-
// TCP-S5: PING/PONG keepalive configuration (30 seconds default, parity with relay)
|
|
72
|
-
this.pingIntervalMs = parseInt(process.env.ASYX_TCP_PING_INTERVAL_MS || "30000", 10); // 30 seconds
|
|
73
|
-
this.pingTimer = null;
|
|
74
|
-
this.lastPongMs = Date.now();
|
|
75
|
-
|
|
76
|
-
// TCP-S4: TCP keepalive configuration
|
|
77
|
-
this.tcpKeepalive = process.env.ASYX_TCP_KEEPALIVE !== '0'; // Enabled by default
|
|
78
|
-
this.tcpKeepaliveInitialDelay = parseInt(process.env.ASYX_TCP_KEEPALIVE_INITIAL_DELAY_MS || "60000", 10); // 60 seconds
|
|
79
|
-
|
|
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
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async open() {
|
|
85
|
-
await this._attemptConnect();
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async _attemptConnect() {
|
|
89
|
-
return new Promise((resolve, reject) => {
|
|
90
|
-
// Store headers for WebSocket connection
|
|
91
|
-
if (!this.headers) {
|
|
92
|
-
this.headers = {
|
|
93
|
-
'Authorization': `Bearer ${this.jwt}`,
|
|
94
|
-
'X-Asyx-DeviceId': this.deviceId,
|
|
95
|
-
'X-Asyx-RequestId': this.requestId
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Clean up previous WebSocket if exists
|
|
100
|
-
if (this.ws) {
|
|
101
|
-
this.ws.removeAllListeners();
|
|
102
|
-
this.ws = null;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// E3-S3: TCP relay requires leaseId and token as query parameters
|
|
106
|
-
// For TCP tunnels, append query parameters to the WebSocket URL
|
|
107
|
-
let wsUrl = this.relayUrl;
|
|
108
|
-
if (this.relayUrl.includes('/tcp')) {
|
|
109
|
-
const urlObj = new URL(this.relayUrl);
|
|
110
|
-
// Add leaseId query parameter (required by TCP relay)
|
|
111
|
-
if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
|
|
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;
|
|
117
|
-
}
|
|
118
|
-
urlObj.searchParams.delete('token');
|
|
119
|
-
if (!this.jwt) {
|
|
120
|
-
this.log.error('tcp.ws.missing_jwt', { relayUrl: this.relayUrl, hasLeaseId: !!this.leaseId });
|
|
121
|
-
reject(new Error('Missing JWT for TCP tunnel'));
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
wsUrl = urlObj.toString();
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// Connect to relay with TLS (rejectUnauthorized: true by default)
|
|
128
|
-
// TCP-S5: Specify tcp-v1 subprotocol for TCP tunnels
|
|
129
|
-
const wsOptions = {
|
|
130
|
-
headers: this.headers,
|
|
131
|
-
rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
|
|
132
|
-
// TCP-S5: Request tcp-v1 subprotocol
|
|
133
|
-
protocol: 'tcp-v1'
|
|
134
|
-
};
|
|
135
|
-
this.ws = new WebSocket(wsUrl, wsOptions);
|
|
136
|
-
|
|
137
|
-
this.ws.on('open', () => {
|
|
138
|
-
this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - TCP proxy mode active');
|
|
139
|
-
|
|
140
|
-
// Connection successful
|
|
141
|
-
|
|
142
|
-
// TCP-S5: Start PING keepalive timer after WebSocket opens
|
|
143
|
-
// NOTE: Do NOT start legacy JSON heartbeat for TCP - relay only accepts binary tcp-v1 frames
|
|
144
|
-
this.startPingKeepalive();
|
|
145
|
-
|
|
146
|
-
resolve();
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
this.ws.on('message', (data, isBinary) => {
|
|
150
|
-
// CRT-Relay-E: Update activity on any message
|
|
151
|
-
this.lastActivityMs = Date.now();
|
|
152
|
-
|
|
153
|
-
// TCP-S5: All tcp-v1 frames are binary - relay only accepts binary frames
|
|
154
|
-
// Note: ws library may pass Buffer for binary, but isBinary flag should be true
|
|
155
|
-
// If isBinary is false but data is a Buffer, treat it as binary anyway (ws library quirk)
|
|
156
|
-
const isActuallyBinary = isBinary || Buffer.isBuffer(data);
|
|
157
|
-
|
|
158
|
-
if (isActuallyBinary) {
|
|
159
|
-
this.handleBinaryFrame(data);
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// TCP-S5: Non-binary (text) frames are NOT supported for TCP tunnels
|
|
164
|
-
// The Go relay WS server only accepts binary tcp-v1 frames; any text frame
|
|
165
|
-
// triggers a framing error and closes the WS, killing the tunnel.
|
|
166
|
-
// Do NOT parse JSON control frames, heartbeats, or reauth for TCP.
|
|
167
|
-
this.log.warn({ size: data.length, isBinary, isBuffer: Buffer.isBuffer(data) }, 'tcp.text_frame_rejected', {
|
|
168
|
-
note: 'TCP tunnel only accepts binary tcp-v1 frames; text frames will cause relay to close connection'
|
|
169
|
-
});
|
|
170
|
-
// Do not process text frames - they will cause protocol violations on the relay
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
this.ws.on('close', (code, reason) => {
|
|
174
|
-
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
175
|
-
const reasonStr = reason?.toString() || '';
|
|
176
|
-
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
177
|
-
if (isNormalClose) {
|
|
178
|
-
this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
179
|
-
} else {
|
|
180
|
-
this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
181
|
-
}
|
|
182
|
-
// TCP-S5: Stop PING keepalive on close
|
|
183
|
-
this.stopPingKeepalive();
|
|
184
|
-
// TCP-S5: No JSON control frames for TCP - no cleanup needed
|
|
185
|
-
// CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
|
|
186
|
-
|
|
187
|
-
// TCP-S4: Close all active TCP streams on WebSocket close
|
|
188
|
-
this.closeAllStreams();
|
|
189
|
-
|
|
190
|
-
// TCP tunnels exit on WebSocket close (unlike HTTP tunnels which have JWT refresh)
|
|
191
|
-
// Reconnecting would break active TCP connections and create new leaseId conflicts
|
|
192
|
-
this.log.info('TCP tunnel exiting due to WebSocket close');
|
|
193
|
-
process.exit(1);
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
this.ws.on('error', (err) => {
|
|
197
|
-
this.log.error({ err }, 'Tunnel WS error');
|
|
198
|
-
// TCP-S5: Stop PING keepalive on error
|
|
199
|
-
this.stopPingKeepalive();
|
|
200
|
-
|
|
201
|
-
// TCP tunnels exit on WebSocket error (unlike HTTP tunnels which have JWT refresh)
|
|
202
|
-
this.log.info('TCP tunnel exiting due to WebSocket error');
|
|
203
|
-
process.exit(1);
|
|
204
|
-
});
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// TCP-S5: Handle binary tcp-v1 frames
|
|
209
|
-
handleBinaryFrame(data) {
|
|
210
|
-
// Append new data to frame buffer
|
|
211
|
-
this.frameBuffer = Buffer.concat([this.frameBuffer, Buffer.from(data)]);
|
|
212
|
-
|
|
213
|
-
// Process complete frames from buffer
|
|
214
|
-
while (this.frameBuffer.length >= FRAME_HEADER_SIZE) {
|
|
215
|
-
try {
|
|
216
|
-
const frame = decodeFrame(this.frameBuffer, 0);
|
|
217
|
-
|
|
218
|
-
// Remove consumed bytes from buffer
|
|
219
|
-
this.frameBuffer = this.frameBuffer.subarray(frame.consumed);
|
|
220
|
-
|
|
221
|
-
// Handle protocol violations
|
|
222
|
-
try {
|
|
223
|
-
validateFrame(frame);
|
|
224
|
-
} catch (err) {
|
|
225
|
-
if (err instanceof TcpV1FramingError) {
|
|
226
|
-
this.log.error({
|
|
227
|
-
error: err.message,
|
|
228
|
-
code: err.code,
|
|
229
|
-
frameType: frame.type,
|
|
230
|
-
streamId: frame.streamId,
|
|
231
|
-
payloadSize: frame.payload.length
|
|
232
|
-
}, 'tcp.protocol_violation');
|
|
233
|
-
this.handleProtocolViolation(err);
|
|
234
|
-
return; // Stop processing on protocol violation
|
|
235
|
-
}
|
|
236
|
-
throw err; // Re-throw non-framing errors
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// Route frame by type
|
|
240
|
-
this.routeFrame(frame);
|
|
241
|
-
} catch (err) {
|
|
242
|
-
if (err instanceof TcpV1FramingError) {
|
|
243
|
-
// Incomplete frame - wait for more data
|
|
244
|
-
if (err.code === 'INCOMPLETE_FRAME') {
|
|
245
|
-
break; // Wait for more data
|
|
246
|
-
}
|
|
247
|
-
// Other framing errors are protocol violations
|
|
248
|
-
this.log.error({
|
|
249
|
-
error: err.message,
|
|
250
|
-
code: err.code
|
|
251
|
-
}, 'tcp.protocol_violation');
|
|
252
|
-
this.handleProtocolViolation(err);
|
|
253
|
-
return;
|
|
254
|
-
}
|
|
255
|
-
// Unexpected error
|
|
256
|
-
this.log.error({ error: err.message }, 'tcp.frame_decode_error');
|
|
257
|
-
this.handleProtocolViolation(new TcpV1FramingError(`Frame decode error: ${err.message}`, 'DECODE_ERROR'));
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// TCP-S5: Route frame by type and streamId
|
|
264
|
-
routeFrame(frame) {
|
|
265
|
-
switch (frame.type) {
|
|
266
|
-
case FrameType.STREAM_OPEN:
|
|
267
|
-
this.handleStreamOpen(frame);
|
|
268
|
-
break;
|
|
269
|
-
case FrameType.STREAM_DATA:
|
|
270
|
-
this.handleStreamData(frame);
|
|
271
|
-
break;
|
|
272
|
-
case FrameType.STREAM_CLOSE:
|
|
273
|
-
this.handleStreamClose(frame);
|
|
274
|
-
break;
|
|
275
|
-
case FrameType.STREAM_ERROR:
|
|
276
|
-
this.handleStreamError(frame);
|
|
277
|
-
break;
|
|
278
|
-
case FrameType.PING:
|
|
279
|
-
this.handlePing(frame);
|
|
280
|
-
break;
|
|
281
|
-
case FrameType.PONG:
|
|
282
|
-
this.handlePong(frame);
|
|
283
|
-
break;
|
|
284
|
-
default:
|
|
285
|
-
// Unknown frame type - protocol violation
|
|
286
|
-
this.log.error({ frameType: frame.type }, 'tcp.unknown_frame_type');
|
|
287
|
-
this.handleProtocolViolation(
|
|
288
|
-
new TcpV1FramingError(`Unknown frame type: ${frame.type}`, 'UNKNOWN_FRAME_TYPE')
|
|
289
|
-
);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// TCP-S5: Handle protocol violation - close tunnel
|
|
294
|
-
handleProtocolViolation(error) {
|
|
295
|
-
if (this.protocolViolation) {
|
|
296
|
-
return; // Already handling violation
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
this.protocolViolation = true;
|
|
300
|
-
this.log.error({
|
|
301
|
-
error: error.message,
|
|
302
|
-
code: error.code
|
|
303
|
-
}, 'tcp.protocol_violation_closing_tunnel');
|
|
304
|
-
|
|
305
|
-
// Close all streams
|
|
306
|
-
this.closeAllStreams();
|
|
307
|
-
|
|
308
|
-
// Close WebSocket connection
|
|
309
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
310
|
-
this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// Protocol violation - exit (TCP tunnels don't support reconnect)
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// TCP-S5: Handle STREAM_OPEN frame
|
|
317
|
-
handleStreamOpen(frame) {
|
|
318
|
-
const streamId = frame.streamId;
|
|
319
|
-
|
|
320
|
-
if (this.activeStreams.has(streamId)) {
|
|
321
|
-
this.log.warn({ streamId }, 'tcp.stream.open.duplicate');
|
|
322
|
-
// Close existing stream and open new one
|
|
323
|
-
this.closeStream(streamId);
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
this.log.info({ streamId, localPort: this.localPort }, 'tcp.stream.open');
|
|
327
|
-
|
|
328
|
-
// Open local TCP socket to 127.0.0.1:localPort
|
|
329
|
-
const localSocket = net.createConnection({
|
|
330
|
-
host: '127.0.0.1',
|
|
331
|
-
port: this.localPort,
|
|
332
|
-
keepAlive: this.tcpKeepalive,
|
|
333
|
-
keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
|
|
334
|
-
});
|
|
335
|
-
|
|
336
|
-
// Log when connection attempt starts
|
|
337
|
-
this.log.debug({ streamId, localPort: this.localPort }, 'tcp.stream.local_connecting');
|
|
338
|
-
|
|
339
|
-
// TCP-S5: Set up idle timeout for this stream (parity with relay)
|
|
340
|
-
const idleTimer = setTimeout(() => {
|
|
341
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
342
|
-
this.closeStream(streamId);
|
|
343
|
-
}, this.idleTimeoutMs);
|
|
344
|
-
|
|
345
|
-
// Track stream activity
|
|
346
|
-
const lastActivity = Date.now();
|
|
347
|
-
|
|
348
|
-
// Handle local socket connection
|
|
349
|
-
localSocket.on('connect', () => {
|
|
350
|
-
this.log.debug({ streamId }, 'tcp.stream.local_connected');
|
|
351
|
-
|
|
352
|
-
// Update stream state to mark socket as connected
|
|
353
|
-
const stream = this.activeStreams.get(streamId);
|
|
354
|
-
if (stream) {
|
|
355
|
-
stream.socketConnected = true;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
// Flush any buffered STREAM_DATA frames from stream.dataBuffer
|
|
359
|
-
if (stream && stream.dataBuffer && stream.dataBuffer.length > 0) {
|
|
360
|
-
this.log.debug({ streamId, bufferedCount: stream.dataBuffer.length }, 'tcp.stream.flushing_buffered_data');
|
|
361
|
-
if (stream.localSocket && !stream.localSocket.destroyed) {
|
|
362
|
-
const buf = stream.dataBuffer;
|
|
363
|
-
while (buf.length > 0) {
|
|
364
|
-
const chunk = buf.shift();
|
|
365
|
-
const written = stream.localSocket.write(chunk);
|
|
366
|
-
if (!written) {
|
|
367
|
-
this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure_on_flush');
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
stream.dataBuffer = []; // Clear buffer after flush
|
|
372
|
-
}
|
|
373
|
-
});
|
|
374
|
-
|
|
375
|
-
// Pipe data from local socket to relay (using tcp-v1 framing)
|
|
376
|
-
localSocket.on('data', (data) => {
|
|
377
|
-
// Check if stream still exists (may have been closed)
|
|
378
|
-
const stream = this.activeStreams.get(streamId);
|
|
379
|
-
if (!stream) {
|
|
380
|
-
// Stream was closed, ignore data
|
|
381
|
-
this.log.debug({ streamId }, 'tcp.stream.local_data.ignored_stream_closed');
|
|
382
|
-
return;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
// Reset idle timer on activity
|
|
386
|
-
if (stream.idleTimer) {
|
|
387
|
-
clearTimeout(stream.idleTimer);
|
|
388
|
-
stream.idleTimer = setTimeout(() => {
|
|
389
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
390
|
-
this.closeStream(streamId);
|
|
391
|
-
}, this.idleTimeoutMs);
|
|
392
|
-
stream.lastActivity = Date.now();
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// Send data to relay using tcp-v1 STREAM_DATA frame
|
|
396
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
397
|
-
try {
|
|
398
|
-
// Split large payloads into multiple frames (max 64 KiB per frame)
|
|
399
|
-
const maxChunkSize = 64 * 1024;
|
|
400
|
-
let offset = 0;
|
|
401
|
-
while (offset < data.length) {
|
|
402
|
-
const chunk = data.subarray(offset, Math.min(offset + maxChunkSize, data.length));
|
|
403
|
-
const frame = encodeFrame({
|
|
404
|
-
type: FrameType.STREAM_DATA,
|
|
405
|
-
streamId: streamId,
|
|
406
|
-
payload: chunk
|
|
407
|
-
});
|
|
408
|
-
this.ws.send(frame, { binary: true });
|
|
409
|
-
offset += chunk.length;
|
|
410
|
-
}
|
|
411
|
-
} catch (err) {
|
|
412
|
-
if (err instanceof TcpV1FramingError) {
|
|
413
|
-
this.log.error({ streamId, error: err.message }, 'tcp.frame_encode_error');
|
|
414
|
-
this.handleProtocolViolation(err);
|
|
415
|
-
} else {
|
|
416
|
-
this.log.error({ streamId, error: err.message }, 'tcp.send_error');
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
});
|
|
421
|
-
|
|
422
|
-
// Handle local socket errors
|
|
423
|
-
localSocket.on('error', (err) => {
|
|
424
|
-
this.log.error({ streamId, error: err.message, code: err.code, localPort: this.localPort }, 'tcp.stream.local_error');
|
|
425
|
-
if (err.code === 'ECONNREFUSED') {
|
|
426
|
-
this.log.error({ port: this.localPort }, 'Local TCP service refused connection');
|
|
427
|
-
}
|
|
428
|
-
// Send STREAM_ERROR to relay for all errors so it knows the connection failed
|
|
429
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
430
|
-
try {
|
|
431
|
-
const errorFrame = encodeFrame({
|
|
432
|
-
type: FrameType.STREAM_ERROR,
|
|
433
|
-
streamId: streamId,
|
|
434
|
-
payload: Buffer.from(`${err.code || 'ERROR'}: ${err.message}`)
|
|
435
|
-
});
|
|
436
|
-
this.ws.send(errorFrame, { binary: true });
|
|
437
|
-
} catch (frameErr) {
|
|
438
|
-
this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
this.closeStream(streamId);
|
|
442
|
-
});
|
|
443
|
-
|
|
444
|
-
// Handle local socket close
|
|
445
|
-
localSocket.on('close', () => {
|
|
446
|
-
this.log.debug({ streamId }, 'tcp.stream.local_closed');
|
|
447
|
-
// Send STREAM_CLOSE to relay
|
|
448
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
449
|
-
try {
|
|
450
|
-
const closeFrame = encodeFrame({
|
|
451
|
-
type: FrameType.STREAM_CLOSE,
|
|
452
|
-
streamId: streamId,
|
|
453
|
-
payload: Buffer.alloc(0)
|
|
454
|
-
});
|
|
455
|
-
this.ws.send(closeFrame, { binary: true });
|
|
456
|
-
} catch (frameErr) {
|
|
457
|
-
this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
this.closeStream(streamId);
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
// Store stream state (include dataBuffer and socketConnected for handleStreamData)
|
|
464
|
-
this.activeStreams.set(streamId, {
|
|
465
|
-
localSocket,
|
|
466
|
-
idleTimer,
|
|
467
|
-
lastActivity,
|
|
468
|
-
dataBuffer: [], // Buffer for data arriving before socket connects
|
|
469
|
-
socketConnected: false // Will be set to true in 'connect' handler
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// TCP-S5: Handle STREAM_DATA frame (route by streamId)
|
|
474
|
-
handleStreamData(frame) {
|
|
475
|
-
const streamId = frame.streamId;
|
|
476
|
-
|
|
477
|
-
if (streamId === 0) {
|
|
478
|
-
this.log.error({ streamId }, 'tcp.stream_data.invalid_stream_id');
|
|
479
|
-
this.handleProtocolViolation(
|
|
480
|
-
new TcpV1FramingError('STREAM_DATA frame has invalid streamId (0)', 'INVALID_STREAM_ID')
|
|
481
|
-
);
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
const stream = this.activeStreams.get(streamId);
|
|
486
|
-
if (!stream) {
|
|
487
|
-
this.log.warn({ streamId }, 'tcp.stream_data.unknown_stream');
|
|
488
|
-
return;
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
// Update activity
|
|
492
|
-
stream.lastActivity = Date.now();
|
|
493
|
-
this.lastActivityMs = Date.now();
|
|
494
|
-
|
|
495
|
-
// Reset idle timer
|
|
496
|
-
if (stream.idleTimer) {
|
|
497
|
-
clearTimeout(stream.idleTimer);
|
|
498
|
-
stream.idleTimer = setTimeout(() => {
|
|
499
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
500
|
-
this.closeStream(streamId);
|
|
501
|
-
}, this.idleTimeoutMs);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
// Write data to local socket (buffer if not connected yet)
|
|
505
|
-
if (stream.localSocket && !stream.localSocket.destroyed) {
|
|
506
|
-
const isConnected = stream.localSocket.readyState === 'open';
|
|
507
|
-
|
|
508
|
-
if (!isConnected) {
|
|
509
|
-
// Buffer data until socket is connected (prevents data loss)
|
|
510
|
-
if (stream.dataBuffer) {
|
|
511
|
-
stream.dataBuffer.push(frame.payload);
|
|
512
|
-
this.log.debug({
|
|
513
|
-
streamId,
|
|
514
|
-
bufferedSize: stream.dataBuffer.length,
|
|
515
|
-
readyState: stream.localSocket.readyState
|
|
516
|
-
}, 'tcp.stream_data.buffered_pending_connect');
|
|
517
|
-
} else {
|
|
518
|
-
this.log.warn({ streamId, readyState: stream.localSocket.readyState }, 'tcp.stream_data.local_socket_not_ready');
|
|
519
|
-
}
|
|
520
|
-
return;
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
const written = stream.localSocket.write(frame.payload);
|
|
524
|
-
if (!written) {
|
|
525
|
-
// Backpressure - socket buffer is full
|
|
526
|
-
this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure');
|
|
527
|
-
// The socket will emit 'drain' when ready, but for now we'll continue
|
|
528
|
-
// In the future, we might want to pause reading from relay
|
|
529
|
-
}
|
|
530
|
-
} else {
|
|
531
|
-
this.log.warn({ streamId }, 'tcp.stream_data.local_socket_unavailable');
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// TCP-S5: Handle STREAM_CLOSE frame
|
|
536
|
-
handleStreamClose(frame) {
|
|
537
|
-
const streamId = frame.streamId;
|
|
538
|
-
|
|
539
|
-
if (streamId === 0) {
|
|
540
|
-
this.log.error({ streamId }, 'tcp.stream_close.invalid_stream_id');
|
|
541
|
-
this.handleProtocolViolation(
|
|
542
|
-
new TcpV1FramingError('STREAM_CLOSE frame has invalid streamId (0)', 'INVALID_STREAM_ID')
|
|
543
|
-
);
|
|
544
|
-
return;
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
this.log.debug({ streamId }, 'tcp.stream.relay_closed');
|
|
548
|
-
this.closeStream(streamId);
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// TCP-S5: Handle STREAM_ERROR frame
|
|
552
|
-
handleStreamError(frame) {
|
|
553
|
-
const streamId = frame.streamId;
|
|
554
|
-
const errorMsg = frame.payload.toString('utf8');
|
|
555
|
-
|
|
556
|
-
this.log.error({ streamId, error: errorMsg }, 'tcp.stream.relay_error');
|
|
557
|
-
this.closeStream(streamId);
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
// TCP-S5: Handle PING frame (respond with PONG)
|
|
561
|
-
handlePing(frame) {
|
|
562
|
-
this.lastActivityMs = Date.now();
|
|
563
|
-
|
|
564
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
|
|
565
|
-
try {
|
|
566
|
-
const pongFrame = encodeFrame({
|
|
567
|
-
type: FrameType.PONG,
|
|
568
|
-
streamId: 0,
|
|
569
|
-
payload: frame.payload // Echo ping payload in pong
|
|
570
|
-
});
|
|
571
|
-
this.ws.send(pongFrame, { binary: true });
|
|
572
|
-
} catch (err) {
|
|
573
|
-
this.log.error({ error: err.message }, 'tcp.pong.encode_error');
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// TCP-S5: Handle PONG frame (update lastPongMs)
|
|
579
|
-
handlePong(frame) {
|
|
580
|
-
this.lastPongMs = Date.now();
|
|
581
|
-
this.lastActivityMs = Date.now();
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// TCP-S4: Handle TCP stream open frame from relay (LEGACY - DEPRECATED)
|
|
585
|
-
// TCP-S5: This method should NOT be called - binary tcp-v1 frames use handleStreamOpen instead
|
|
586
|
-
// If somehow called, it will attempt to send JSON frames which will cause protocol violations
|
|
587
|
-
handleTcpStream(msg) {
|
|
588
|
-
// TCP-S5: Legacy JSON frame handler - should not be used with tcp-v1 binary framing
|
|
589
|
-
this.log.warn('tcp.legacy_json_handler_called', {
|
|
590
|
-
note: 'handleTcpStream should not be called with tcp-v1 binary framing - use handleStreamOpen instead'
|
|
591
|
-
});
|
|
592
|
-
// Extract stream ID and other metadata
|
|
593
|
-
const streamId = msg.streamId || msg.sid || crypto.randomUUID();
|
|
594
|
-
const leaseId = msg.leaseId || this.requestId; // Fallback to requestId if leaseId not provided
|
|
595
|
-
|
|
596
|
-
this.log.info({ streamId, leaseId }, 'tcp.stream.open');
|
|
597
|
-
|
|
598
|
-
// Open local TCP socket to 127.0.0.1:localPort
|
|
599
|
-
const localSocket = net.createConnection({
|
|
600
|
-
host: '127.0.0.1',
|
|
601
|
-
port: this.localPort,
|
|
602
|
-
keepAlive: this.tcpKeepalive,
|
|
603
|
-
keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
|
|
604
|
-
});
|
|
605
|
-
|
|
606
|
-
// TCP-S4: Set up idle timeout for this stream
|
|
607
|
-
const idleTimer = setTimeout(() => {
|
|
608
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
609
|
-
this.closeStream(streamId);
|
|
610
|
-
}, this.idleTimeoutMs);
|
|
611
|
-
|
|
612
|
-
// Track stream activity to reset idle timer
|
|
613
|
-
let lastStreamActivity = Date.now();
|
|
614
|
-
|
|
615
|
-
// Handle local socket connection
|
|
616
|
-
localSocket.on('connect', () => {
|
|
617
|
-
this.log.debug({ streamId }, 'tcp.stream.local_connected');
|
|
618
|
-
// TCP-S5: Do NOT send JSON frames - relay only accepts binary tcp-v1 frames
|
|
619
|
-
// Stream open acknowledgment is implicit in tcp-v1 protocol (no ack frame needed)
|
|
620
|
-
this.log.debug({ streamId }, 'tcp.stream.local_connected');
|
|
621
|
-
});
|
|
622
|
-
|
|
623
|
-
// Pipe data from local socket to relay
|
|
624
|
-
localSocket.on('data', (data) => {
|
|
625
|
-
lastStreamActivity = Date.now();
|
|
626
|
-
// Reset idle timer on activity
|
|
627
|
-
if (idleTimer) {
|
|
628
|
-
clearTimeout(idleTimer);
|
|
629
|
-
const newTimer = setTimeout(() => {
|
|
630
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
631
|
-
this.closeStream(streamId);
|
|
632
|
-
}, this.idleTimeoutMs);
|
|
633
|
-
this.activeStreams.set(streamId, {
|
|
634
|
-
...this.activeStreams.get(streamId),
|
|
635
|
-
idleTimer: newTimer
|
|
636
|
-
});
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
// TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_DATA frames instead
|
|
640
|
-
// This legacy handler should not be called with tcp-v1 binary framing
|
|
641
|
-
this.log.warn('tcp.legacy_json_data_send_blocked', {
|
|
642
|
-
streamId,
|
|
643
|
-
note: 'Legacy JSON data send blocked - use binary tcp-v1 STREAM_DATA frames instead'
|
|
644
|
-
});
|
|
645
|
-
});
|
|
646
|
-
|
|
647
|
-
// Handle local socket errors
|
|
648
|
-
localSocket.on('error', (err) => {
|
|
649
|
-
this.log.error({ streamId, error: err.message }, 'tcp.stream.local_error');
|
|
650
|
-
if (err.code === 'ECONNREFUSED') {
|
|
651
|
-
this.log.error({ port: this.localPort }, 'Local TCP service refused connection');
|
|
652
|
-
// TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_ERROR frames instead
|
|
653
|
-
// This legacy handler should not be called with tcp-v1 binary framing
|
|
654
|
-
this.log.warn('tcp.legacy_json_error_send_blocked', {
|
|
655
|
-
streamId,
|
|
656
|
-
error: 'ECONNREFUSED',
|
|
657
|
-
note: 'Legacy JSON error send blocked - use binary tcp-v1 STREAM_ERROR frames instead'
|
|
658
|
-
});
|
|
659
|
-
this.closeStream(streamId);
|
|
660
|
-
}
|
|
661
|
-
});
|
|
662
|
-
|
|
663
|
-
// Handle local socket close
|
|
664
|
-
localSocket.on('close', () => {
|
|
665
|
-
this.log.debug({ streamId }, 'tcp.stream.local_closed');
|
|
666
|
-
// TCP-S5: Do NOT send JSON frames - use binary tcp-v1 STREAM_CLOSE frames instead
|
|
667
|
-
// This legacy handler should not be called with tcp-v1 binary framing
|
|
668
|
-
this.log.warn('tcp.legacy_json_close_send_blocked', {
|
|
669
|
-
streamId,
|
|
670
|
-
note: 'Legacy JSON close send blocked - use binary tcp-v1 STREAM_CLOSE frames instead'
|
|
671
|
-
});
|
|
672
|
-
this.closeStream(streamId);
|
|
673
|
-
});
|
|
674
|
-
|
|
675
|
-
// Store stream state
|
|
676
|
-
this.activeStreams.set(streamId, {
|
|
677
|
-
localSocket,
|
|
678
|
-
relayStream: null, // Will be set when we receive data from relay
|
|
679
|
-
idleTimer,
|
|
680
|
-
leaseId,
|
|
681
|
-
lastActivity: lastStreamActivity
|
|
682
|
-
});
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
// TCP-S4: Handle TCP data frame from relay
|
|
686
|
-
handleTcpData(msg) {
|
|
687
|
-
const streamId = msg.streamId || msg.sid;
|
|
688
|
-
if (!streamId) {
|
|
689
|
-
this.log.warn('tcp.data.missing_stream_id');
|
|
690
|
-
return;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
const stream = this.activeStreams.get(streamId);
|
|
694
|
-
if (!stream) {
|
|
695
|
-
this.log.warn({ streamId }, 'tcp.data.unknown_stream');
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
// Update activity
|
|
700
|
-
stream.lastActivity = Date.now();
|
|
701
|
-
this.lastActivityMs = Date.now();
|
|
702
|
-
|
|
703
|
-
// Reset idle timer
|
|
704
|
-
if (stream.idleTimer) {
|
|
705
|
-
clearTimeout(stream.idleTimer);
|
|
706
|
-
const newTimer = setTimeout(() => {
|
|
707
|
-
this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
|
|
708
|
-
this.closeStream(streamId);
|
|
709
|
-
}, this.idleTimeoutMs);
|
|
710
|
-
stream.idleTimer = newTimer;
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// Decode data and write to local socket
|
|
714
|
-
try {
|
|
715
|
-
const data = Buffer.from(msg.data, 'base64');
|
|
716
|
-
if (stream.localSocket && !stream.localSocket.destroyed) {
|
|
717
|
-
stream.localSocket.write(data);
|
|
718
|
-
}
|
|
719
|
-
} catch (e) {
|
|
720
|
-
this.log.error({ streamId, error: e.message }, 'tcp.data.decode_error');
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
// TCP-S5: Start PING keepalive timer (parity with relay)
|
|
725
|
-
startPingKeepalive() {
|
|
726
|
-
if (this.pingIntervalMs <= 0) {
|
|
727
|
-
this.log.debug('PING keepalive disabled (ASYX_TCP_PING_INTERVAL_MS <= 0)');
|
|
728
|
-
return;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
this.pingTimer = setInterval(() => {
|
|
732
|
-
this.sendPing();
|
|
733
|
-
}, this.pingIntervalMs);
|
|
734
|
-
|
|
735
|
-
this.log.debug({ interval: this.pingIntervalMs }, 'tcp.ping.keepalive.started');
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
// TCP-S5: Stop PING keepalive timer
|
|
739
|
-
stopPingKeepalive() {
|
|
740
|
-
if (this.pingTimer) {
|
|
741
|
-
clearInterval(this.pingTimer);
|
|
742
|
-
this.pingTimer = null;
|
|
743
|
-
this.log.debug('tcp.ping.keepalive.stopped');
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
// TCP-S5: Send PING frame
|
|
748
|
-
sendPing() {
|
|
749
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.protocolViolation) {
|
|
750
|
-
return;
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
try {
|
|
754
|
-
const pingFrame = encodeFrame({
|
|
755
|
-
type: FrameType.PING,
|
|
756
|
-
streamId: 0,
|
|
757
|
-
payload: Buffer.from(Date.now().toString()) // Include timestamp for debugging
|
|
758
|
-
});
|
|
759
|
-
this.ws.send(pingFrame, { binary: true });
|
|
760
|
-
} catch (err) {
|
|
761
|
-
this.log.error({ error: err.message }, 'tcp.ping.encode_error');
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
// TCP-S4: Handle TCP stream close frame from relay
|
|
766
|
-
handleTcpClose(msg) {
|
|
767
|
-
const streamId = msg.streamId || msg.sid;
|
|
768
|
-
if (!streamId) {
|
|
769
|
-
this.log.warn('tcp.close.missing_stream_id');
|
|
770
|
-
return;
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
this.log.debug({ streamId }, 'tcp.stream.relay_closed');
|
|
774
|
-
this.closeStream(streamId);
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
// TCP-S4: Close a specific TCP stream
|
|
778
|
-
closeStream(streamId) {
|
|
779
|
-
const stream = this.activeStreams.get(streamId);
|
|
780
|
-
if (!stream) {
|
|
781
|
-
return;
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
// Clear idle timer
|
|
785
|
-
if (stream.idleTimer) {
|
|
786
|
-
clearTimeout(stream.idleTimer);
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
// Close local socket
|
|
790
|
-
if (stream.localSocket && !stream.localSocket.destroyed) {
|
|
791
|
-
stream.localSocket.destroy();
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
// Remove from active streams
|
|
795
|
-
this.activeStreams.delete(streamId);
|
|
796
|
-
this.log.debug({ streamId }, 'tcp.stream.closed');
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
// TCP-S4: Close all active TCP streams
|
|
800
|
-
closeAllStreams() {
|
|
801
|
-
const streamIds = Array.from(this.activeStreams.keys());
|
|
802
|
-
for (const streamId of streamIds) {
|
|
803
|
-
this.closeStream(streamId);
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
// TCP tunnels do NOT support reconnect (removed - was causing issues with active connections)
|
|
808
|
-
// HTTP tunnels have JWT refresh, so they can reconnect safely
|
|
809
|
-
// TCP tunnels exit on WebSocket close to avoid breaking active TCP streams
|
|
810
|
-
|
|
811
|
-
close() {
|
|
812
|
-
// TCP tunnels don't have reconnect logic, so no cleanup needed
|
|
813
|
-
|
|
814
|
-
// TCP-S5: Stop PING keepalive
|
|
815
|
-
this.stopPingKeepalive();
|
|
816
|
-
|
|
817
|
-
// TCP-S4: Close all active TCP streams
|
|
818
|
-
this.closeAllStreams();
|
|
819
|
-
|
|
820
|
-
// TCP-S5: No JSON control frames for TCP - no cleanup needed
|
|
821
|
-
// CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
|
|
822
|
-
|
|
823
|
-
// TCP-S5: Stop PING keepalive before closing
|
|
824
|
-
this.stopPingKeepalive();
|
|
825
|
-
if (this.ws) {
|
|
826
|
-
this.ws.close();
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
// TCP-S5: Legacy JSON heartbeat methods DISABLED for TCP tunnels
|
|
831
|
-
// TCP tunnels use binary tcp-v1 PING/PONG keepalive instead (see startPingKeepalive/sendPing)
|
|
832
|
-
// These methods are kept for potential HTTP tunnel compatibility but are NOT called for TCP
|
|
833
|
-
// and will NOT send JSON frames on TCP WebSocket connections.
|
|
834
|
-
|
|
835
|
-
getHeartbeatInterval() {
|
|
836
|
-
// TCP-S5: Always return Infinity for TCP to prevent JSON heartbeat
|
|
837
|
-
return Infinity;
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
startHeartbeat() {
|
|
841
|
-
// TCP-S5: Disabled for TCP tunnels - do not send JSON heartbeats
|
|
842
|
-
// Use tcp-v1 PING/PONG keepalive instead (startPingKeepalive)
|
|
843
|
-
this.log.debug('Legacy JSON heartbeat disabled for TCP tunnel (use tcp-v1 PING/PONG)');
|
|
844
|
-
return;
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
sendHeartbeat() {
|
|
848
|
-
// TCP-S5: Disabled for TCP tunnels - do not send JSON heartbeats
|
|
849
|
-
// Use tcp-v1 PING/PONG keepalive instead (sendPing)
|
|
850
|
-
// This method will NOT send JSON frames on TCP WebSocket connections
|
|
851
|
-
return;
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
stopHeartbeat() {
|
|
855
|
-
// TCP-S5: No-op for TCP tunnels (heartbeat not started)
|
|
856
|
-
if (this.heartbeatTimer) {
|
|
857
|
-
clearInterval(this.heartbeatTimer);
|
|
858
|
-
this.heartbeatTimer = null;
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
|