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,11 +2,23 @@
2
2
  // Handles UDP datagrams over WebSocket using udpWs-v1 framing
3
3
  // UDP-S1: CLI – UDP entrypoint & WS connect
4
4
  import WebSocket from 'ws';
5
+ import { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
5
6
  import dgram from 'dgram';
6
7
  import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, UdpV1FramingError } from '../udp-v1/framing.js';
7
8
  import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
8
9
 
9
10
  export class UdpTunnel {
11
+ static selectDial(targetHost) {
12
+ const host = String(targetHost || '127.0.0.1').trim().toLowerCase();
13
+ if (host === 'localhost' || host === '127.0.0.1' || host.startsWith('127.')) {
14
+ return { family: 'udp4', address: '127.0.0.1' };
15
+ }
16
+ if (host === '::1') {
17
+ return { family: 'udp6', address: '::1' };
18
+ }
19
+ return null;
20
+ }
21
+
10
22
  constructor({
11
23
  relayUrl,
12
24
  jwt,
@@ -26,21 +38,34 @@ export class UdpTunnel {
26
38
  getLastMqttError = () => null,
27
39
  getForceReconnect = () => null,
28
40
  controlPlaneTimeoutMs = 60000,
41
+ // Story 11.2: newest assignment token for reconnects; falls back to the token
42
+ // the tunnel was opened with.
43
+ getJwt = null,
44
+ reassign = null,
45
+ exit = (code) => process.exit(code),
29
46
  }) {
30
47
  this.relayUrl = relayUrl;
31
48
  this.jwt = jwt;
49
+ this.getJwt = getJwt;
50
+ // Story 10.9: async () => ({ relayUrl, jwt, leaseId }) | null - a new assignment when the
51
+ // relay refuses the old one (the tenant was moved to another relay)
52
+ this.reassign = reassign;
53
+ this.exit = exit;
32
54
  this.deviceId = deviceId;
33
55
  this.requestId = requestId;
34
56
  // UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
35
57
  this.targetHost = targetHost || '127.0.0.1';
36
58
  this.targetPort = targetPort || localPort;
59
+ const dial = UdpTunnel.selectDial(this.targetHost);
60
+ this.dialFamily = dial?.family || null;
61
+ this.dialAddress = dial?.address || null;
37
62
  this.leaseId = leaseId;
38
63
  this.relayId = relayId; // AC5.1: Store relayId for JWT validation
39
64
  this.log = log;
40
65
  this.ws = null;
41
66
  // UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
42
67
 
43
- // Coordinator connection (not used for UDP refresh yet)
68
+ // Coordinator connection
44
69
  this.coordinatorCore = coordinatorCore;
45
70
  this.coordinatorIngress = coordinatorIngress;
46
71
 
@@ -74,6 +99,34 @@ export class UdpTunnel {
74
99
  // UDP-S1: Flow idle timeout (60-300 seconds per protocol spec)
75
100
  this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10); // 60 seconds
76
101
  this.flowCleanupTimer = null;
102
+
103
+ // Story 11.2: reconnect to the same lease when the relay connection drops. Flow ids
104
+ // belong to one relay connection, so all flows and their sockets are discarded on a
105
+ // drop; a flow id reused by the relay after reconnecting can never reach an old socket.
106
+ this.closing = false; // set by close(): no reconnect
107
+ this.everOpened = false;
108
+ this.lastInboundMs = Date.now();
109
+ this.reconnectEnabled = reconnectEnabled();
110
+ this.reconnector = new Reconnector({
111
+ onAuthFailure: async () => {
112
+ if (!this.reassign) return false;
113
+ const a = await this.reassign();
114
+ if (!a || !a.jwt) return false;
115
+ this.log.info({ leaseId: a.leaseId, relayUrl: a.relayUrl }, 'udp.tunnel.reassigned');
116
+ this.jwt = a.jwt;
117
+ if (a.relayUrl) this.relayUrl = a.relayUrl;
118
+ if (a.leaseId) this.leaseId = a.leaseId;
119
+ if (a.relayId) this.relayId = a.relayId; // the new relay (UDP checks tokens against it)
120
+ return true;
121
+ },
122
+ kind: 'udp',
123
+ log: this.log,
124
+ connect: () => this._attemptConnect(),
125
+ onGiveUp: (reason) => {
126
+ this.log.info({ reason }, 'UDP tunnel exiting: relay connection could not be restored');
127
+ this.exit(1);
128
+ },
129
+ });
77
130
  }
78
131
 
79
132
  async open() {
@@ -81,6 +134,9 @@ export class UdpTunnel {
81
134
  }
82
135
 
83
136
  async _attemptConnect() {
137
+ // Story 11.2: use the newest assignment token on every (re)connect
138
+ const freshJwt = this.getJwt ? this.getJwt() : null;
139
+ if (freshJwt) this.jwt = freshJwt;
84
140
  return new Promise((resolve, reject) => {
85
141
  // UDP-S1: Validate relayUrl format
86
142
  if (!this.relayUrl) {
@@ -111,8 +167,12 @@ export class UdpTunnel {
111
167
  if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
112
168
  urlObj.searchParams.set('leaseId', this.leaseId);
113
169
  }
114
- if (this.jwt && !urlObj.searchParams.has('token')) {
115
- urlObj.searchParams.set('token', this.jwt);
170
+ urlObj.searchParams.delete('token');
171
+ if (!this.jwt) {
172
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing JWT for UDP tunnel');
173
+ error.code = 'UDP_RELAY_UNAVAILABLE';
174
+ reject(error);
175
+ return;
116
176
  }
117
177
  wsUrl = urlObj.toString();
118
178
  } catch (urlError) {
@@ -132,6 +192,12 @@ export class UdpTunnel {
132
192
  // Note: JWT verification is async, so we need to handle it inside an async IIFE
133
193
  (async () => {
134
194
  try {
195
+ // Story 11.2: a token already verified for this tunnel is not verified again on
196
+ // reconnect, so a reconnect does not depend on reaching the JWKS endpoint
197
+ if (this.verifiedJwt && this.verifiedJwt === this.jwt) {
198
+ this._setupWebSocketConnection(wsUrl, resolve, reject);
199
+ return;
200
+ }
135
201
  // AC1.4/AC5.1: Verify JWT signature and claims using JWKS
136
202
  // verifyAssignmentJWT will initialize JWKS on first call and fail fast if unavailable
137
203
  const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
@@ -150,6 +216,7 @@ export class UdpTunnel {
150
216
  tunnelMode: payload.tunnelMode
151
217
  });
152
218
 
219
+ this.verifiedJwt = this.jwt;
153
220
  // Continue with WebSocket connection setup after JWT verification
154
221
  this._setupWebSocketConnection(wsUrl, resolve, reject);
155
222
  } catch (jwtError) {
@@ -157,6 +224,7 @@ export class UdpTunnel {
157
224
  // This includes: JWKS unavailable, signature invalid, claims mismatch, expired, etc.
158
225
  const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
159
226
  error.code = 'UDP_RELAY_UNAVAILABLE';
227
+ error.cause = jwtError;
160
228
  this.log.error('udp.jwt.verification_failed', {
161
229
  error: jwtError.message,
162
230
  code: jwtError.code,
@@ -172,7 +240,9 @@ export class UdpTunnel {
172
240
  _setupWebSocketConnection(wsUrl, resolve, reject) {
173
241
  // Clean up previous WebSocket if exists
174
242
  if (this.ws) {
175
- this.ws.removeAllListeners();
243
+ const old = this.ws;
244
+ old.removeAllListeners();
245
+ old.on('error', () => {}); // a late error from the old socket must not crash the CLI
176
246
  this.ws = null;
177
247
  }
178
248
 
@@ -185,10 +255,18 @@ export class UdpTunnel {
185
255
  },
186
256
  rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
187
257
  };
188
- this.ws = new WebSocket(wsUrl, wsOptions);
258
+ const ws = new WebSocket(wsUrl, wsOptions);
259
+ this.ws = ws;
260
+ let opened = false;
261
+ let failure = null;
189
262
 
190
- this.ws.on('open', () => {
191
- this.log.info({ relayUrl: wsUrl, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
263
+ ws.on('open', () => {
264
+ opened = true;
265
+ this.everOpened = true;
266
+ this.protocolViolation = false;
267
+ this.frameBuffer = Buffer.alloc(0);
268
+ this.lastInboundMs = Date.now();
269
+ this.log.info({ leaseId: this.leaseId, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
192
270
 
193
271
  // UDP-S1: Start PING keepalive timer
194
272
  this.startPingKeepalive();
@@ -202,7 +280,8 @@ export class UdpTunnel {
202
280
  resolve();
203
281
  });
204
282
 
205
- this.ws.on('message', (data, isBinary) => {
283
+ ws.on('message', (data, isBinary) => {
284
+ this.lastInboundMs = Date.now();
206
285
  // UDP-S1: All udpWs-v1 frames are binary
207
286
  const isActuallyBinary = isBinary || Buffer.isBuffer(data);
208
287
 
@@ -220,38 +299,70 @@ export class UdpTunnel {
220
299
  );
221
300
  });
222
301
 
223
- this.ws.on('close', (code, reason) => {
302
+ ws.on('close', (code, reason) => {
224
303
  const reasonStr = reason?.toString() || '';
225
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
226
- if (isNormalClose) {
227
- this.log.debug({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
228
- } else {
229
- this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
304
+ if (!opened) {
305
+ // The connection attempt failed before it opened
306
+ const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${failure?.message || `closed before open (code ${code})`}`);
307
+ error.code = 'UDP_RELAY_UNAVAILABLE';
308
+ error.closeCode = code;
309
+ error.cause = failure;
310
+ this.stopPingKeepalive();
311
+ this.stopFlowCleanup();
312
+ if (!this.everOpened) {
313
+ // First connect: unchanged behaviour, the CLI ends
314
+ this.log.error('UDP tunnel exiting due to WebSocket error');
315
+ this.exit(1);
316
+ }
317
+ reject(error);
318
+ return;
230
319
  }
231
-
232
- this.stopPingKeepalive();
233
- this.stopFlowCleanup();
234
- this.closeAllFlowSockets();
235
-
236
- // UDP-S1: Exit on WS close (no reconnect loop)
237
- this.log.info('UDP tunnel exiting due to WebSocket close');
238
- process.exit(1);
320
+ this._onDropped(code, reasonStr);
239
321
  });
240
322
 
241
- this.ws.on('error', (err) => {
323
+ ws.on('error', (err) => {
324
+ // A 'close' event always follows; the decision is made there
325
+ failure = err;
242
326
  this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
243
- this.stopPingKeepalive();
244
- this.stopFlowCleanup();
245
- this.closeAllFlowSockets();
246
-
247
- // UDP-S1: Exit on WS error (no reconnect loop)
248
- const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${err.message}`);
249
- error.code = 'UDP_RELAY_UNAVAILABLE';
250
- this.log.error('UDP tunnel exiting due to WebSocket error');
251
- process.exit(1);
252
327
  });
253
328
  }
254
329
 
330
+ // Story 11.2: an established relay connection dropped
331
+ _onDropped(code, reasonStr) {
332
+ const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
333
+ if (isNormalClose) {
334
+ this.log.debug({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
335
+ } else {
336
+ this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
337
+ }
338
+ this.stopPingKeepalive();
339
+ this.stopFlowCleanup();
340
+ this.closeAllFlowSockets();
341
+ this.frameBuffer = Buffer.alloc(0);
342
+
343
+ if (this.closing) return;
344
+ const verdict = classifyDrop(code, reasonStr);
345
+ // Story 10.9: a lease the relay closed (4000 lease_closed) may have been moved to another
346
+ // relay by an operator; ask the control plane once for a new assignment for the same port
347
+ // and continue there. If it refuses, the tunnel ends as before. lease_reconnected (another
348
+ // CLI took the lease) stays final.
349
+ if (this.reconnectEnabled && verdict.fatal && reasonStr === 'lease_closed' && this.reassign) {
350
+ this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.lease_closed.reassigning');
351
+ this.reconnector.onAuthFailure().then((got) => {
352
+ if (got && !this.closing) { this.reconnector.run('lease_closed_reassigned'); return; }
353
+ this.log.info({ reason: verdict.reason }, 'UDP tunnel exiting due to WebSocket close');
354
+ this.exit(1);
355
+ }).catch(() => this.exit(1));
356
+ return;
357
+ }
358
+ if (!this.reconnectEnabled || verdict.fatal) {
359
+ this.log.info({ reason: verdict.reason }, 'UDP tunnel exiting due to WebSocket close');
360
+ this.exit(1);
361
+ return;
362
+ }
363
+ this.reconnector.run(verdict.reason);
364
+ }
365
+
255
366
  // UDP-S1: Handle binary udpWs-v1 frames
256
367
  handleBinaryFrame(data) {
257
368
  // Append new data to frame buffer
@@ -346,13 +457,12 @@ export class UdpTunnel {
346
457
  // Close UDP socket
347
458
  this.closeAllFlowSockets();
348
459
 
349
- // Close WebSocket connection
460
+ // Close WebSocket connection; Story 11.2: the close event reconnects with fresh state
350
461
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
351
462
  this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
463
+ } else if (this.ws) {
464
+ this.ws.terminate();
352
465
  }
353
-
354
- // Protocol violation - exit (UDP tunnels don't support reconnect)
355
- process.exit(1);
356
466
  }
357
467
 
358
468
  // UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
@@ -367,8 +477,16 @@ export class UdpTunnel {
367
477
  let socket = flowState?.socket;
368
478
 
369
479
  if (!socket) {
480
+ if (!this.dialAddress || !this.dialFamily) {
481
+ this.log.warn({
482
+ flowId,
483
+ targetHost: this.targetHost,
484
+ note: 'Refusing non-loopback UDP dial'
485
+ }, 'udp.flow.dial.refused');
486
+ return;
487
+ }
370
488
  // Create new per-flow socket for this flowId
371
- socket = dgram.createSocket('udp4');
489
+ socket = dgram.createSocket(this.dialFamily);
372
490
 
373
491
  // UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
374
492
  this.socketToFlowId.set(socket, flowId);
@@ -377,37 +495,27 @@ export class UdpTunnel {
377
495
  flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
378
496
  this.flowMap.set(flowId, flowState);
379
497
 
380
- // UDP-S13: Bind to OS-assigned port (ephemeral)
381
- socket.bind(0, '0.0.0.0', () => {
498
+ // Bind the ephemeral port on loopback, then connect, then listen.
499
+ socket.bind(0, this.dialAddress, () => {
382
500
  const address = socket.address();
383
501
  this.log.debug({
384
502
  flowId,
385
503
  localAddress: address.address,
386
504
  localPort: address.port,
387
- targetHost: this.targetHost,
505
+ targetHost: this.dialAddress,
388
506
  targetPort: this.targetPort
389
507
  }, 'udp.flow.socket.bound');
390
508
 
391
- // UDP-S13: Connect to targetHost:targetPort (allows send() without address/port)
392
- socket.connect(this.targetPort, this.targetHost, () => {
509
+ socket.connect(this.targetPort, this.dialAddress, () => {
393
510
  this.log.debug({
394
511
  flowId,
395
- targetHost: this.targetHost,
512
+ targetHost: this.dialAddress,
396
513
  targetPort: this.targetPort
397
514
  }, 'udp.flow.socket.connected');
398
515
 
399
- // UDP-S14: Mark socket as connected
400
516
  flowState.connected = true;
401
-
402
- // UDP-S13: Send any pending payload now that socket is connected
403
- if (flowState.pendingPayload) {
404
- this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
405
- flowState.pendingPayload = null;
406
- }
407
- });
408
-
409
- // UDP-S14: Handle incoming datagrams from app on this flow's socket
410
- socket.on('message', (msg, rinfo) => {
517
+
518
+ socket.on('message', (msg, rinfo) => {
411
519
  // We know the flowId from the socket itself
412
520
  const socketFlowId = this.socketToFlowId.get(socket);
413
521
  if (socketFlowId === flowId) {
@@ -432,12 +540,18 @@ export class UdpTunnel {
432
540
  if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
433
541
  this.log.warn({
434
542
  flowId,
435
- targetHost: this.targetHost,
543
+ targetHost: this.dialAddress,
436
544
  targetPort: this.targetPort,
437
545
  note: 'Target app may not be listening on this port'
438
546
  }, 'udp.target.unreachable');
439
547
  }
440
548
  });
549
+
550
+ if (flowState.pendingPayload) {
551
+ this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
552
+ flowState.pendingPayload = null;
553
+ }
554
+ });
441
555
  });
442
556
  } else {
443
557
  // Update lastSeen for existing flow
@@ -584,6 +698,7 @@ export class UdpTunnel {
584
698
 
585
699
  // UDP-S1: Start PING keepalive timer
586
700
  startPingKeepalive() {
701
+ this.stopPingKeepalive(); // never two timers after a reconnect
587
702
  if (this.pingIntervalMs <= 0) {
588
703
  this.log.debug('PING keepalive disabled (ASYX_UDP_PING_INTERVAL_MS <= 0)');
589
704
  return;
@@ -611,6 +726,15 @@ export class UdpTunnel {
611
726
  return;
612
727
  }
613
728
 
729
+ // Story 11.2: nothing received from the relay for three ping intervals means the
730
+ // connection is dead without a close; drop it so the tunnel reconnects
731
+ const silentMs = Date.now() - this.lastInboundMs;
732
+ if (silentMs > 3 * this.pingIntervalMs) {
733
+ this.log.warn({ silentMs }, 'udp.ws.liveness_timeout');
734
+ this.ws.terminate();
735
+ return;
736
+ }
737
+
614
738
  try {
615
739
  const pingFrame = encodeFrame({
616
740
  type: FrameType.PING,
@@ -675,6 +799,9 @@ export class UdpTunnel {
675
799
  }
676
800
 
677
801
  close() {
802
+ // Story 11.2: a deliberate close does not reconnect
803
+ this.closing = true;
804
+ this.reconnector.stop();
678
805
  this.stopPingKeepalive();
679
806
  this.stopFlowCleanup();
680
807
  this.closeAllFlowSockets();