asyx 0.5.7 → 0.5.9

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.
@@ -2,6 +2,7 @@
2
2
  // Mirrors HttpTunnel structure but handles TCP streams instead of HTTP requests
3
3
  // TCP-S5: Uses binary tcp-v1 framing protocol
4
4
  import WebSocket from 'ws';
5
+ import { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
5
6
  import net from 'net';
6
7
  import crypto from 'node:crypto';
7
8
  // CLI-REAUTH: Control frame helper for in-band reauth
@@ -26,9 +27,19 @@ export class TcpTunnel {
26
27
  getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
27
28
  getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
28
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),
29
35
  }) {
30
36
  this.relayUrl = relayUrl;
31
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;
32
43
  this.deviceId = deviceId;
33
44
  this.requestId = requestId;
34
45
  this.localPort = localPort;
@@ -36,7 +47,7 @@ export class TcpTunnel {
36
47
  this.log = log;
37
48
  this.ws = null;
38
49
 
39
- // Coordinator connection (not used for TCP - TCP tunnels don't support JWT refresh/reconnect)
50
+ // Coordinator connection
40
51
  this.coordinatorCore = coordinatorCore;
41
52
  this.coordinatorIngress = coordinatorIngress;
42
53
 
@@ -51,9 +62,34 @@ export class TcpTunnel {
51
62
  this.heartbeatTimer = null;
52
63
  this.lastActivityMs = Date.now();
53
64
 
54
- // TCP tunnels do NOT support reconnect (unlike HTTP tunnels which have JWT refresh)
55
- // TCP tunnels exit on WebSocket close to avoid breaking active connections
56
- this.headers = null; // Store headers for WebSocket connection
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
+ });
57
93
 
58
94
  // TCP-S5: Active TCP stream connections (keyed by numeric streamId)
59
95
  this.activeStreams = new Map(); // streamId (number) -> { localSocket, idleTimer, lastActivity }
@@ -77,8 +113,6 @@ export class TcpTunnel {
77
113
  this.tcpKeepalive = process.env.ASYX_TCP_KEEPALIVE !== '0'; // Enabled by default
78
114
  this.tcpKeepaliveInitialDelay = parseInt(process.env.ASYX_TCP_KEEPALIVE_INITIAL_DELAY_MS || "60000", 10); // 60 seconds
79
115
 
80
- // TCP tunnels do NOT support JWT refresh or in-band reauth (unlike HTTP tunnels)
81
- // These properties are not used but kept for potential future implementation
82
116
  }
83
117
 
84
118
  async open() {
@@ -87,18 +121,20 @@ export class TcpTunnel {
87
121
 
88
122
  async _attemptConnect() {
89
123
  return new Promise((resolve, reject) => {
90
- // Store headers for WebSocket connection
91
- if (!this.headers) {
92
- this.headers = {
93
- 'Authorization': `Bearer ${this.jwt}`,
94
- 'X-Asyx-DeviceId': this.deviceId,
95
- 'X-Asyx-RequestId': this.requestId
96
- };
97
- }
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
+ };
98
132
 
99
133
  // Clean up previous WebSocket if exists
100
134
  if (this.ws) {
101
- this.ws.removeAllListeners();
135
+ const old = this.ws;
136
+ old.removeAllListeners();
137
+ old.on('error', () => {}); // a late error from the old socket must not crash the CLI
102
138
  this.ws = null;
103
139
  }
104
140
 
@@ -115,10 +151,8 @@ export class TcpTunnel {
115
151
  reject(new Error('Missing leaseId for TCP tunnel'));
116
152
  return;
117
153
  }
118
- // Add token query parameter (required by TCP relay)
119
- if (this.jwt && !urlObj.searchParams.has('token')) {
120
- urlObj.searchParams.set('token', this.jwt);
121
- } else if (!this.jwt) {
154
+ urlObj.searchParams.delete('token');
155
+ if (!this.jwt) {
122
156
  this.log.error('tcp.ws.missing_jwt', { relayUrl: this.relayUrl, hasLeaseId: !!this.leaseId });
123
157
  reject(new Error('Missing JWT for TCP tunnel'));
124
158
  return;
@@ -134,13 +168,19 @@ export class TcpTunnel {
134
168
  // TCP-S5: Request tcp-v1 subprotocol
135
169
  protocol: 'tcp-v1'
136
170
  };
137
- this.ws = new WebSocket(wsUrl, wsOptions);
171
+ const ws = new WebSocket(wsUrl, wsOptions);
172
+ this.ws = ws;
173
+ let opened = false;
174
+ let failure = null;
138
175
 
139
- this.ws.on('open', () => {
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();
140
182
  this.log.info({ relayUrl: this.relayUrl, localPort: this.localPort }, 'Tunnel WS open - TCP proxy mode active');
141
183
 
142
- // Connection successful
143
-
144
184
  // TCP-S5: Start PING keepalive timer after WebSocket opens
145
185
  // NOTE: Do NOT start legacy JSON heartbeat for TCP - relay only accepts binary tcp-v1 frames
146
186
  this.startPingKeepalive();
@@ -148,9 +188,10 @@ export class TcpTunnel {
148
188
  resolve();
149
189
  });
150
190
 
151
- this.ws.on('message', (data, isBinary) => {
191
+ ws.on('message', (data, isBinary) => {
152
192
  // CRT-Relay-E: Update activity on any message
153
193
  this.lastActivityMs = Date.now();
194
+ this.lastInboundMs = this.lastActivityMs;
154
195
 
155
196
  // TCP-S5: All tcp-v1 frames are binary - relay only accepts binary frames
156
197
  // Note: ws library may pass Buffer for binary, but isBinary flag should be true
@@ -172,41 +213,71 @@ export class TcpTunnel {
172
213
  // Do not process text frames - they will cause protocol violations on the relay
173
214
  });
174
215
 
175
- this.ws.on('close', (code, reason) => {
176
- // QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
216
+ ws.on('close', (code, reason) => {
177
217
  const reasonStr = reason?.toString() || '';
178
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
179
- if (isNormalClose) {
180
- this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
181
- } else {
182
- this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
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;
183
230
  }
184
- // TCP-S5: Stop PING keepalive on close
185
- this.stopPingKeepalive();
186
- // TCP-S5: No JSON control frames for TCP - no cleanup needed
187
- // CLI-REAUTH: Control frames disabled for TCP tunnels (binary-only protocol)
188
-
189
- // TCP-S4: Close all active TCP streams on WebSocket close
190
- this.closeAllStreams();
191
-
192
- // TCP tunnels exit on WebSocket close (unlike HTTP tunnels which have JWT refresh)
193
- // Reconnecting would break active TCP connections and create new leaseId conflicts
194
- this.log.info('TCP tunnel exiting due to WebSocket close');
195
- process.exit(1);
231
+ this._onDropped(code, reasonStr);
196
232
  });
197
233
 
198
- this.ws.on('error', (err) => {
234
+ ws.on('error', (err) => {
235
+ // A 'close' event always follows; the decision is made there
236
+ failure = err;
199
237
  this.log.error({ err }, 'Tunnel WS error');
200
- // TCP-S5: Stop PING keepalive on error
201
238
  this.stopPingKeepalive();
202
-
203
- // TCP tunnels exit on WebSocket error (unlike HTTP tunnels which have JWT refresh)
204
- this.log.info('TCP tunnel exiting due to WebSocket error');
205
- process.exit(1);
206
239
  });
207
240
  });
208
241
  }
209
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
+
210
281
  // TCP-S5: Handle binary tcp-v1 frames
211
282
  handleBinaryFrame(data) {
212
283
  // Append new data to frame buffer
@@ -312,7 +383,7 @@ export class TcpTunnel {
312
383
  this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
313
384
  }
314
385
 
315
- // Protocol violation - exit (TCP tunnels don't support reconnect)
386
+ // Story 11.2: the close event reconnects with fresh state
316
387
  }
317
388
 
318
389
  // TCP-S5: Handle STREAM_OPEN frame
@@ -725,6 +796,7 @@ export class TcpTunnel {
725
796
 
726
797
  // TCP-S5: Start PING keepalive timer (parity with relay)
727
798
  startPingKeepalive() {
799
+ this.stopPingKeepalive(); // never two timers after a reconnect
728
800
  if (this.pingIntervalMs <= 0) {
729
801
  this.log.debug('PING keepalive disabled (ASYX_TCP_PING_INTERVAL_MS <= 0)');
730
802
  return;
@@ -752,6 +824,16 @@ export class TcpTunnel {
752
824
  return;
753
825
  }
754
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
+
755
837
  try {
756
838
  const pingFrame = encodeFrame({
757
839
  type: FrameType.PING,
@@ -806,12 +888,10 @@ export class TcpTunnel {
806
888
  }
807
889
  }
808
890
 
809
- // TCP tunnels do NOT support reconnect (removed - was causing issues with active connections)
810
- // HTTP tunnels have JWT refresh, so they can reconnect safely
811
- // TCP tunnels exit on WebSocket close to avoid breaking active TCP streams
812
-
813
891
  close() {
814
- // TCP tunnels don't have reconnect logic, so no cleanup needed
892
+ // Story 11.2: a deliberate close does not reconnect
893
+ this.closing = true;
894
+ this.reconnector.stop();
815
895
 
816
896
  // TCP-S5: Stop PING keepalive
817
897
  this.stopPingKeepalive();