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