asyx 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +103 -17
  2. package/SECURITY.md +5 -3
  3. package/package.json +15 -22
  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 +304 -2316
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +24 -6
  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 -1694
  84. package/src/tunnel/tcp-tunnel.js +0 -862
  85. package/src/tunnel/udp-tunnel.js +0 -708
  86. package/src/tunnel/ws-control.js +0 -135
  87. package/src/udp-v1/framing.js +0 -203
@@ -1,708 +0,0 @@
1
- // UDP Tunnel - udpWs-v1 protocol
2
- // Handles UDP datagrams over WebSocket using udpWs-v1 framing
3
- // UDP-S1: CLI – UDP entrypoint & WS connect
4
- import WebSocket from 'ws';
5
- import dgram from 'dgram';
6
- import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, UdpV1FramingError } from '../udp-v1/framing.js';
7
- import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
8
-
9
- export class UdpTunnel {
10
- static selectDial(targetHost) {
11
- const host = String(targetHost || '127.0.0.1').trim().toLowerCase();
12
- if (host === 'localhost' || host === '127.0.0.1' || host.startsWith('127.')) {
13
- return { family: 'udp4', address: '127.0.0.1' };
14
- }
15
- if (host === '::1') {
16
- return { family: 'udp6', address: '::1' };
17
- }
18
- return null;
19
- }
20
-
21
- constructor({
22
- relayUrl,
23
- jwt,
24
- deviceId,
25
- requestId,
26
- localPort, // UDP-S13: Deprecated, use targetHost/targetPort instead
27
- targetHost, // UDP-S13: Target host (must be loopback)
28
- targetPort, // UDP-S13: Target port (app's listening port)
29
- leaseId,
30
- relayId, // AC5.1: Relay ID for JWT validation
31
- log,
32
- coordinatorCore,
33
- coordinatorIngress,
34
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
35
- isControlPlaneConnected = () => true,
36
- waitForControlPlane = () => Promise.resolve(),
37
- getLastMqttError = () => null,
38
- getForceReconnect = () => null,
39
- controlPlaneTimeoutMs = 60000,
40
- }) {
41
- this.relayUrl = relayUrl;
42
- this.jwt = jwt;
43
- this.deviceId = deviceId;
44
- this.requestId = requestId;
45
- // UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
46
- this.targetHost = targetHost || '127.0.0.1';
47
- this.targetPort = targetPort || localPort;
48
- const dial = UdpTunnel.selectDial(this.targetHost);
49
- this.dialFamily = dial?.family || null;
50
- this.dialAddress = dial?.address || null;
51
- this.leaseId = leaseId;
52
- this.relayId = relayId; // AC5.1: Store relayId for JWT validation
53
- this.log = log;
54
- this.ws = null;
55
- // UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
56
-
57
- // Coordinator connection (not used for UDP refresh yet)
58
- this.coordinatorCore = coordinatorCore;
59
- this.coordinatorIngress = coordinatorIngress;
60
-
61
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
62
- this.isControlPlaneConnected = isControlPlaneConnected;
63
- this.waitForControlPlane = waitForControlPlane;
64
- this.getLastMqttError = getLastMqttError;
65
- this.getForceReconnect = getForceReconnect;
66
- this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
67
-
68
- // UDP-S14: Per-flow socket mapping for correct return path routing
69
- // flowId -> { socket, lastSeen } - one UDP socket per flowId, connected to targetHost:targetPort
70
- this.flowMap = new Map(); // flowId -> { socket, lastSeen }
71
- // Reverse mapping: socket -> flowId (for message handlers)
72
- this.socketToFlowId = new WeakMap(); // socket -> flowId
73
-
74
- // UDP-S1: Binary frame buffer for partial frames
75
- this.frameBuffer = Buffer.alloc(0);
76
-
77
- // UDP-S1: Protocol violation flag
78
- this.protocolViolation = false;
79
-
80
- // UDP-S1: Idle timeout configuration (15 minutes default, parity with relay)
81
- this.idleTimeoutMs = parseInt(process.env.ASYX_UDP_IDLE_TIMEOUT_MS || "900000", 10); // 15 minutes
82
-
83
- // UDP-S1: PING/PONG keepalive configuration (30 seconds default)
84
- this.pingIntervalMs = parseInt(process.env.ASYX_UDP_PING_INTERVAL_MS || "30000", 10); // 30 seconds
85
- this.pingTimer = null;
86
- this.lastPongMs = Date.now();
87
-
88
- // UDP-S1: Flow idle timeout (60-300 seconds per protocol spec)
89
- this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10); // 60 seconds
90
- this.flowCleanupTimer = null;
91
- }
92
-
93
- async open() {
94
- await this._attemptConnect();
95
- }
96
-
97
- async _attemptConnect() {
98
- return new Promise((resolve, reject) => {
99
- // UDP-S1: Validate relayUrl format
100
- if (!this.relayUrl) {
101
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
102
- error.code = 'UDP_RELAY_UNAVAILABLE';
103
- this.log.error('udp.ws.missing_relayUrl', { relayUrl: this.relayUrl });
104
- reject(error);
105
- return;
106
- }
107
-
108
- // UDP-S1: Parse relayUrl and ensure it's for /udp endpoint
109
- let wsUrl = this.relayUrl;
110
- try {
111
- const urlObj = new URL(this.relayUrl);
112
- // Ensure path is /udp
113
- if (!urlObj.pathname.includes('/udp')) {
114
- this.log.warn('udp.ws.path_mismatch', {
115
- relayUrl: this.relayUrl,
116
- pathname: urlObj.pathname,
117
- note: 'Expected /udp path, adjusting'
118
- });
119
- // Replace path with /udp
120
- urlObj.pathname = '/udp';
121
- wsUrl = urlObj.toString();
122
- }
123
-
124
- // Add leaseId and token query parameters if not present
125
- if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
126
- urlObj.searchParams.set('leaseId', this.leaseId);
127
- }
128
- urlObj.searchParams.delete('token');
129
- if (!this.jwt) {
130
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing JWT for UDP tunnel');
131
- error.code = 'UDP_RELAY_UNAVAILABLE';
132
- reject(error);
133
- return;
134
- }
135
- wsUrl = urlObj.toString();
136
- } catch (urlError) {
137
- const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid relayUrl format: ${urlError.message}`);
138
- error.code = 'UDP_RELAY_UNAVAILABLE';
139
- this.log.error('udp.ws.invalid_relayUrl', {
140
- relayUrl: this.relayUrl,
141
- error: urlError.message
142
- });
143
- reject(error);
144
- return;
145
- }
146
-
147
- // UDP-S1: Validate JWT (AC1.4/AC5.1: signature verification and claim validation)
148
- // AC1.4/AC5.1: Use JWKS verifier - fail fast if JWKS unavailable (same as TCP/HTTP)
149
- // Enforces "no JWKS → no tunnel" policy
150
- // Note: JWT verification is async, so we need to handle it inside an async IIFE
151
- (async () => {
152
- try {
153
- // AC1.4/AC5.1: Verify JWT signature and claims using JWKS
154
- // verifyAssignmentJWT will initialize JWKS on first call and fail fast if unavailable
155
- const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
156
- const payload = await verifyAssignmentJWT(this.jwt, {
157
- relayId: this.relayId,
158
- protocol: 'udp',
159
- tunnelMode: 'udpWs-v1',
160
- leaseId: this.leaseId
161
- });
162
-
163
- // Verification successful - payload is already validated (signature + all claims)
164
- this.log.debug('udp.jwt.verified', {
165
- relayId: payload.relayId,
166
- leaseId: payload.leaseId,
167
- protocol: payload.protocol,
168
- tunnelMode: payload.tunnelMode
169
- });
170
-
171
- // Continue with WebSocket connection setup after JWT verification
172
- this._setupWebSocketConnection(wsUrl, resolve, reject);
173
- } catch (jwtError) {
174
- // AC1.4/AC5.1: Map all verification errors to UDP_RELAY_UNAVAILABLE
175
- // This includes: JWKS unavailable, signature invalid, claims mismatch, expired, etc.
176
- const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
177
- error.code = 'UDP_RELAY_UNAVAILABLE';
178
- this.log.error('udp.jwt.verification_failed', {
179
- error: jwtError.message,
180
- code: jwtError.code,
181
- leaseId: this.leaseId,
182
- relayId: this.relayId
183
- });
184
- reject(error);
185
- }
186
- })();
187
- });
188
- }
189
-
190
- _setupWebSocketConnection(wsUrl, resolve, reject) {
191
- // Clean up previous WebSocket if exists
192
- if (this.ws) {
193
- this.ws.removeAllListeners();
194
- this.ws = null;
195
- }
196
-
197
- // UDP-S1: Connect to relay with TLS (rejectUnauthorized: true by default)
198
- const wsOptions = {
199
- headers: {
200
- 'Authorization': `Bearer ${this.jwt}`,
201
- 'X-Asyx-DeviceId': this.deviceId,
202
- 'X-Asyx-RequestId': this.requestId
203
- },
204
- rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
205
- };
206
- this.ws = new WebSocket(wsUrl, wsOptions);
207
-
208
- this.ws.on('open', () => {
209
- this.log.info({ leaseId: this.leaseId, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
210
-
211
- // UDP-S1: Start PING keepalive timer
212
- this.startPingKeepalive();
213
-
214
- // UDP-S1: Start flow cleanup timer
215
- this.startFlowCleanup();
216
-
217
- // UDP-S14: Per-flow sockets are created on-demand in handleUdpDatagram
218
- // No global socket initialization needed - each flowId gets its own socket
219
-
220
- resolve();
221
- });
222
-
223
- this.ws.on('message', (data, isBinary) => {
224
- // UDP-S1: All udpWs-v1 frames are binary
225
- const isActuallyBinary = isBinary || Buffer.isBuffer(data);
226
-
227
- if (isActuallyBinary) {
228
- this.handleBinaryFrame(data);
229
- return;
230
- }
231
-
232
- // UDP-S1: Non-binary frames are protocol violations
233
- this.log.warn({ size: data.length, isBinary }, 'udp.text_frame_rejected', {
234
- note: 'UDP tunnel only accepts binary udpWs-v1 frames'
235
- });
236
- this.handleProtocolViolation(
237
- new UdpV1FramingError('Text frame received in UDP tunnel', 'INVALID_FRAME_TYPE')
238
- );
239
- });
240
-
241
- this.ws.on('close', (code, reason) => {
242
- const reasonStr = reason?.toString() || '';
243
- const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
244
- if (isNormalClose) {
245
- this.log.debug({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
246
- } else {
247
- this.log.warn({ code, reason: reasonStr }, 'udp.tunnel.ws.closed');
248
- }
249
-
250
- this.stopPingKeepalive();
251
- this.stopFlowCleanup();
252
- this.closeAllFlowSockets();
253
-
254
- // UDP-S1: Exit on WS close (no reconnect loop)
255
- this.log.info('UDP tunnel exiting due to WebSocket close');
256
- process.exit(1);
257
- });
258
-
259
- this.ws.on('error', (err) => {
260
- this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
261
- this.stopPingKeepalive();
262
- this.stopFlowCleanup();
263
- this.closeAllFlowSockets();
264
-
265
- // UDP-S1: Exit on WS error (no reconnect loop)
266
- const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${err.message}`);
267
- error.code = 'UDP_RELAY_UNAVAILABLE';
268
- this.log.error('UDP tunnel exiting due to WebSocket error');
269
- process.exit(1);
270
- });
271
- }
272
-
273
- // UDP-S1: Handle binary udpWs-v1 frames
274
- handleBinaryFrame(data) {
275
- // Append new data to frame buffer
276
- this.frameBuffer = Buffer.concat([this.frameBuffer, Buffer.from(data)]);
277
-
278
- // Process complete frames from buffer
279
- while (this.frameBuffer.length >= FRAME_HEADER_SIZE) {
280
- try {
281
- const frame = decodeFrame(this.frameBuffer, 0);
282
-
283
- // Remove consumed bytes from buffer
284
- this.frameBuffer = this.frameBuffer.subarray(frame.consumed);
285
-
286
- // Validate frame
287
- try {
288
- validateFrame(frame);
289
- } catch (err) {
290
- if (err instanceof UdpV1FramingError) {
291
- this.log.error({
292
- error: err.message,
293
- code: err.code,
294
- frameType: frame.type,
295
- flowId: frame.flowId,
296
- payloadSize: frame.payload.length
297
- }, 'udp.protocol_violation');
298
- this.handleProtocolViolation(err);
299
- return;
300
- }
301
- throw err;
302
- }
303
-
304
- // Route frame by type
305
- this.routeFrame(frame);
306
- } catch (err) {
307
- if (err instanceof UdpV1FramingError) {
308
- // Incomplete frame - wait for more data
309
- if (err.code === 'INCOMPLETE_FRAME') {
310
- break; // Wait for more data
311
- }
312
- // Other framing errors are protocol violations
313
- this.log.error({
314
- error: err.message,
315
- code: err.code
316
- }, 'udp.protocol_violation');
317
- this.handleProtocolViolation(err);
318
- return;
319
- }
320
- // Unexpected error
321
- this.log.error({ error: err.message }, 'udp.frame_decode_error');
322
- this.handleProtocolViolation(new UdpV1FramingError(`Frame decode error: ${err.message}`, 'DECODE_ERROR'));
323
- return;
324
- }
325
- }
326
- }
327
-
328
- // UDP-S1: Route frame by type
329
- routeFrame(frame) {
330
- switch (frame.type) {
331
- case FrameType.UDP_DGRAM:
332
- this.handleUdpDatagram(frame);
333
- break;
334
- case FrameType.UDP_CLOSE:
335
- this.handleUdpClose(frame);
336
- break;
337
- case FrameType.PING:
338
- this.handlePing(frame);
339
- break;
340
- case FrameType.PONG:
341
- this.handlePong(frame);
342
- break;
343
- default:
344
- // Unknown frame type - protocol violation
345
- this.log.error({ frameType: frame.type }, 'udp.unknown_frame_type');
346
- this.handleProtocolViolation(
347
- new UdpV1FramingError(`Unknown frame type: ${frame.type}`, 'UNKNOWN_FRAME_TYPE')
348
- );
349
- }
350
- }
351
-
352
- // UDP-S1: Handle protocol violation - close tunnel
353
- handleProtocolViolation(error) {
354
- if (this.protocolViolation) {
355
- return; // Already handling violation
356
- }
357
-
358
- this.protocolViolation = true;
359
- this.log.error({
360
- error: error.message,
361
- code: error.code
362
- }, 'udp.protocol_violation_closing_tunnel');
363
-
364
- // Close UDP socket
365
- this.closeAllFlowSockets();
366
-
367
- // Close WebSocket connection
368
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
369
- this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
370
- }
371
-
372
- // Protocol violation - exit (UDP tunnels don't support reconnect)
373
- process.exit(1);
374
- }
375
-
376
- // UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
377
- // UDP-S13: Forward to targetHost:targetPort (app's listening port)
378
- // UDP-S14: Use per-flow socket for correct return path routing
379
- handleUdpDatagram(frame) {
380
- const flowId = frame.flowId;
381
- const now = Date.now();
382
-
383
- // UDP-S14: Lookup or create per-flow socket
384
- let flowState = this.flowMap.get(flowId);
385
- let socket = flowState?.socket;
386
-
387
- if (!socket) {
388
- if (!this.dialAddress || !this.dialFamily) {
389
- this.log.warn({
390
- flowId,
391
- targetHost: this.targetHost,
392
- note: 'Refusing non-loopback UDP dial'
393
- }, 'udp.flow.dial.refused');
394
- return;
395
- }
396
- // Create new per-flow socket for this flowId
397
- socket = dgram.createSocket(this.dialFamily);
398
-
399
- // UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
400
- this.socketToFlowId.set(socket, flowId);
401
-
402
- // UDP-S14: Store socket in flowMap immediately (before bind completes)
403
- flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
404
- this.flowMap.set(flowId, flowState);
405
-
406
- // Bind the ephemeral port on loopback, then connect, then listen.
407
- socket.bind(0, this.dialAddress, () => {
408
- const address = socket.address();
409
- this.log.debug({
410
- flowId,
411
- localAddress: address.address,
412
- localPort: address.port,
413
- targetHost: this.dialAddress,
414
- targetPort: this.targetPort
415
- }, 'udp.flow.socket.bound');
416
-
417
- socket.connect(this.targetPort, this.dialAddress, () => {
418
- this.log.debug({
419
- flowId,
420
- targetHost: this.dialAddress,
421
- targetPort: this.targetPort
422
- }, 'udp.flow.socket.connected');
423
-
424
- flowState.connected = true;
425
-
426
- socket.on('message', (msg, rinfo) => {
427
- // We know the flowId from the socket itself
428
- const socketFlowId = this.socketToFlowId.get(socket);
429
- if (socketFlowId === flowId) {
430
- this.handleLocalDatagram(msg, rinfo, flowId);
431
- } else {
432
- this.log.error({
433
- flowId,
434
- socketFlowId,
435
- note: 'FlowId mismatch in socket message handler'
436
- }, 'udp.flow.socket.mismatch');
437
- }
438
- });
439
-
440
- socket.on('error', (err) => {
441
- this.log.error({
442
- flowId,
443
- error: err.message,
444
- code: err.code
445
- }, 'udp.flow.socket.error');
446
-
447
- // UDP-S13: If target app isn't listening, log clearly
448
- if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
449
- this.log.warn({
450
- flowId,
451
- targetHost: this.dialAddress,
452
- targetPort: this.targetPort,
453
- note: 'Target app may not be listening on this port'
454
- }, 'udp.target.unreachable');
455
- }
456
- });
457
-
458
- if (flowState.pendingPayload) {
459
- this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
460
- flowState.pendingPayload = null;
461
- }
462
- });
463
- });
464
- } else {
465
- // Update lastSeen for existing flow
466
- flowState.lastSeen = now;
467
-
468
- // UDP-S13: Send payload using existing socket
469
- // If socket is not yet connected, queue the payload
470
- if (flowState.connected) {
471
- this.sendDatagramToApp(socket, flowId, frame.payload);
472
- } else {
473
- // Queue payload until socket is connected
474
- flowState.pendingPayload = frame.payload;
475
- }
476
- }
477
- }
478
-
479
- // UDP-S13: Helper to send datagram to app on flow-specific socket
480
- sendDatagramToApp(socket, flowId, payload) {
481
- if (!socket || this.protocolViolation) {
482
- return;
483
- }
484
-
485
- socket.send(
486
- payload,
487
- (err) => {
488
- if (err) {
489
- this.log.error({
490
- flowId,
491
- error: err.message,
492
- code: err.code,
493
- targetHost: this.targetHost,
494
- targetPort: this.targetPort
495
- }, 'udp.datagram.send_error');
496
- } else {
497
- // UDP-S14: Log with flowId for tracking
498
- this.log.debug({
499
- flowId,
500
- size: payload.length,
501
- targetHost: this.targetHost,
502
- targetPort: this.targetPort
503
- }, 'udp.datagram.delivered');
504
- }
505
- }
506
- );
507
- }
508
-
509
- // UDP-S1: Handle UDP_CLOSE frame (flow shutdown hint)
510
- // UDP-S14: Close per-flow socket
511
- handleUdpClose(frame) {
512
- const flowId = frame.flowId;
513
- this.log.debug({ flowId }, 'udp.flow.close');
514
-
515
- // UDP-S14: Close and remove per-flow socket
516
- const flowState = this.flowMap.get(flowId);
517
- if (flowState?.socket) {
518
- flowState.socket.close();
519
- this.socketToFlowId.delete(flowState.socket);
520
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
521
- }
522
-
523
- // Remove flow from mapping
524
- this.flowMap.delete(flowId);
525
- }
526
-
527
- // UDP-S1: Handle PING frame (respond with PONG)
528
- handlePing(frame) {
529
- this.lastPongMs = Date.now();
530
-
531
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
532
- try {
533
- const pongFrame = encodeFrame({
534
- type: FrameType.PONG,
535
- flowId: 0,
536
- payload: frame.payload // Echo ping payload in pong
537
- });
538
- this.ws.send(pongFrame, { binary: true });
539
- } catch (err) {
540
- this.log.error({ error: err.message }, 'udp.pong.encode_error');
541
- }
542
- }
543
- }
544
-
545
- // UDP-S1: Handle PONG frame (update lastPongMs)
546
- handlePong(frame) {
547
- this.lastPongMs = Date.now();
548
- }
549
-
550
- // UDP-S13: Handle incoming datagram from app (via per-flow socket)
551
- // Forward app responses to relay via WebSocket
552
- // UDP-S14: flowId is known from the socket itself (per-flow socket architecture)
553
- handleLocalDatagram(msg, rinfo, flowId) {
554
- // UDP-S14: flowId is passed as parameter (we know it from the socket)
555
- if (!flowId) {
556
- this.log.error({
557
- note: 'flowId not provided to handleLocalDatagram - this should not happen'
558
- }, 'udp.datagram.flow_missing');
559
- return; // Drop datagram if flowId is unknown
560
- }
561
-
562
- // UDP-S14: Verify flowId is still active
563
- if (!this.flowMap.has(flowId)) {
564
- this.log.warn({
565
- flowId,
566
- note: 'Received datagram on closed/evicted flow'
567
- }, 'udp.datagram.flow_closed');
568
- return; // Drop datagram if flow is closed
569
- }
570
-
571
- // UDP-S1: Validate datagram size (max 64 KiB)
572
- if (msg.length > 65536) {
573
- this.log.error({
574
- size: msg.length,
575
- maxSize: 65536
576
- }, 'udp.datagram.oversize');
577
- return; // Drop oversize datagram
578
- }
579
-
580
- // UDP-S1: Encode as UDP_DGRAM frame and send over WS
581
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
582
- try {
583
- const frame = encodeFrame({
584
- type: FrameType.UDP_DGRAM,
585
- flowId: flowId,
586
- payload: msg
587
- });
588
- this.ws.send(frame, { binary: true });
589
- // UDP-S14: Log with flowId for tracking return path
590
- // UDP-S14: Log with flowId (known from per-flow socket)
591
- this.log.debug({
592
- flowId,
593
- size: msg.length,
594
- note: 'App response forwarded with flowId (per-flow socket)'
595
- }, 'udp.datagram.sent');
596
- } catch (err) {
597
- if (err instanceof UdpV1FramingError) {
598
- this.log.error({ flowId, error: err.message }, 'udp.frame_encode_error');
599
- this.handleProtocolViolation(err);
600
- } else {
601
- this.log.error({ flowId, error: err.message }, 'udp.send_error');
602
- }
603
- }
604
- }
605
- }
606
-
607
- // UDP-S1: Start PING keepalive timer
608
- startPingKeepalive() {
609
- if (this.pingIntervalMs <= 0) {
610
- this.log.debug('PING keepalive disabled (ASYX_UDP_PING_INTERVAL_MS <= 0)');
611
- return;
612
- }
613
-
614
- this.pingTimer = setInterval(() => {
615
- this.sendPing();
616
- }, this.pingIntervalMs);
617
-
618
- this.log.debug({ interval: this.pingIntervalMs }, 'udp.ping.keepalive.started');
619
- }
620
-
621
- // UDP-S1: Stop PING keepalive timer
622
- stopPingKeepalive() {
623
- if (this.pingTimer) {
624
- clearInterval(this.pingTimer);
625
- this.pingTimer = null;
626
- this.log.debug('udp.ping.keepalive.stopped');
627
- }
628
- }
629
-
630
- // UDP-S1: Send PING frame
631
- sendPing() {
632
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.protocolViolation) {
633
- return;
634
- }
635
-
636
- try {
637
- const pingFrame = encodeFrame({
638
- type: FrameType.PING,
639
- flowId: 0,
640
- payload: Buffer.from(Date.now().toString()) // Include timestamp for debugging
641
- });
642
- this.ws.send(pingFrame, { binary: true });
643
- } catch (err) {
644
- this.log.error({ error: err.message }, 'udp.ping.encode_error');
645
- }
646
- }
647
-
648
- // UDP-S1: Start flow cleanup timer (evict idle flows)
649
- startFlowCleanup() {
650
- if (this.flowIdleTimeoutMs <= 0) {
651
- return;
652
- }
653
-
654
- // Run cleanup every 30 seconds
655
- this.flowCleanupTimer = setInterval(() => {
656
- const now = Date.now();
657
- const expiredFlows = [];
658
-
659
- for (const [flowId, flow] of this.flowMap.entries()) {
660
- if (now - flow.lastSeen > this.flowIdleTimeoutMs) {
661
- expiredFlows.push(flowId);
662
- }
663
- }
664
-
665
- for (const flowId of expiredFlows) {
666
- // UDP-S14: Close per-flow socket before removing
667
- const flowState = this.flowMap.get(flowId);
668
- if (flowState?.socket) {
669
- flowState.socket.close();
670
- this.socketToFlowId.delete(flowState.socket);
671
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
672
- }
673
- this.flowMap.delete(flowId);
674
- this.log.debug({ flowId }, 'udp.flow.idle_evicted');
675
- }
676
- }, 30000); // Check every 30 seconds
677
- }
678
-
679
- // UDP-S1: Stop flow cleanup timer
680
- stopFlowCleanup() {
681
- if (this.flowCleanupTimer) {
682
- clearInterval(this.flowCleanupTimer);
683
- this.flowCleanupTimer = null;
684
- }
685
- }
686
-
687
- // UDP-S14: Close all per-flow sockets
688
- closeAllFlowSockets() {
689
- for (const [flowId, flowState] of this.flowMap.entries()) {
690
- if (flowState?.socket) {
691
- flowState.socket.close();
692
- this.socketToFlowId.delete(flowState.socket);
693
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
694
- }
695
- }
696
- this.flowMap.clear();
697
- }
698
-
699
- close() {
700
- this.stopPingKeepalive();
701
- this.stopFlowCleanup();
702
- this.closeAllFlowSockets();
703
-
704
- if (this.ws) {
705
- this.ws.close();
706
- }
707
- }
708
- }