asyx 0.5.9 → 0.6.1

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