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