asyx 0.5.9 → 0.6.0

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