asyx 0.5.9 → 0.6.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 (88) hide show
  1. package/README.md +73 -9
  2. package/SECURITY.md +5 -3
  3. package/package.json +13 -23
  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 +279 -2425
  8. package/src/lib/naming.js +81 -0
  9. package/src/main.js +9 -1
  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 -1738
  84. package/src/tunnel/reconnect.js +0 -182
  85. package/src/tunnel/tcp-tunnel.js +0 -944
  86. package/src/tunnel/udp-tunnel.js +0 -813
  87. package/src/tunnel/ws-control.js +0 -135
  88. package/src/udp-v1/framing.js +0 -203
@@ -1,813 +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 { Reconnector, reconnectEnabled, classifyDrop } from './reconnect.js';
6
- import dgram from 'dgram';
7
- import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame, UdpV1FramingError } from '../udp-v1/framing.js';
8
- import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
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
-
22
- constructor({
23
- relayUrl,
24
- jwt,
25
- deviceId,
26
- requestId,
27
- localPort, // UDP-S13: Deprecated, use targetHost/targetPort instead
28
- targetHost, // UDP-S13: Target host (must be loopback)
29
- targetPort, // UDP-S13: Target port (app's listening port)
30
- leaseId,
31
- relayId, // AC5.1: Relay ID for JWT validation
32
- log,
33
- coordinatorCore,
34
- coordinatorIngress,
35
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
36
- isControlPlaneConnected = () => true,
37
- waitForControlPlane = () => Promise.resolve(),
38
- getLastMqttError = () => null,
39
- getForceReconnect = () => null,
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),
46
- }) {
47
- this.relayUrl = relayUrl;
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;
54
- this.deviceId = deviceId;
55
- this.requestId = requestId;
56
- // UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
57
- this.targetHost = targetHost || '127.0.0.1';
58
- this.targetPort = targetPort || localPort;
59
- const dial = UdpTunnel.selectDial(this.targetHost);
60
- this.dialFamily = dial?.family || null;
61
- this.dialAddress = dial?.address || null;
62
- this.leaseId = leaseId;
63
- this.relayId = relayId; // AC5.1: Store relayId for JWT validation
64
- this.log = log;
65
- this.ws = null;
66
- // UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
67
-
68
- // Coordinator connection
69
- this.coordinatorCore = coordinatorCore;
70
- this.coordinatorIngress = coordinatorIngress;
71
-
72
- // CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
73
- this.isControlPlaneConnected = isControlPlaneConnected;
74
- this.waitForControlPlane = waitForControlPlane;
75
- this.getLastMqttError = getLastMqttError;
76
- this.getForceReconnect = getForceReconnect;
77
- this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
78
-
79
- // UDP-S14: Per-flow socket mapping for correct return path routing
80
- // flowId -> { socket, lastSeen } - one UDP socket per flowId, connected to targetHost:targetPort
81
- this.flowMap = new Map(); // flowId -> { socket, lastSeen }
82
- // Reverse mapping: socket -> flowId (for message handlers)
83
- this.socketToFlowId = new WeakMap(); // socket -> flowId
84
-
85
- // UDP-S1: Binary frame buffer for partial frames
86
- this.frameBuffer = Buffer.alloc(0);
87
-
88
- // UDP-S1: Protocol violation flag
89
- this.protocolViolation = false;
90
-
91
- // UDP-S1: Idle timeout configuration (15 minutes default, parity with relay)
92
- this.idleTimeoutMs = parseInt(process.env.ASYX_UDP_IDLE_TIMEOUT_MS || "900000", 10); // 15 minutes
93
-
94
- // UDP-S1: PING/PONG keepalive configuration (30 seconds default)
95
- this.pingIntervalMs = parseInt(process.env.ASYX_UDP_PING_INTERVAL_MS || "30000", 10); // 30 seconds
96
- this.pingTimer = null;
97
- this.lastPongMs = Date.now();
98
-
99
- // UDP-S1: Flow idle timeout (60-300 seconds per protocol spec)
100
- this.flowIdleTimeoutMs = parseInt(process.env.ASYX_UDP_FLOW_IDLE_TIMEOUT_MS || "60000", 10); // 60 seconds
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
- });
130
- }
131
-
132
- async open() {
133
- await this._attemptConnect();
134
- }
135
-
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;
140
- return new Promise((resolve, reject) => {
141
- // UDP-S1: Validate relayUrl format
142
- if (!this.relayUrl) {
143
- const error = new Error('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
144
- error.code = 'UDP_RELAY_UNAVAILABLE';
145
- this.log.error('udp.ws.missing_relayUrl', { relayUrl: this.relayUrl });
146
- reject(error);
147
- return;
148
- }
149
-
150
- // UDP-S1: Parse relayUrl and ensure it's for /udp endpoint
151
- let wsUrl = this.relayUrl;
152
- try {
153
- const urlObj = new URL(this.relayUrl);
154
- // Ensure path is /udp
155
- if (!urlObj.pathname.includes('/udp')) {
156
- this.log.warn('udp.ws.path_mismatch', {
157
- relayUrl: this.relayUrl,
158
- pathname: urlObj.pathname,
159
- note: 'Expected /udp path, adjusting'
160
- });
161
- // Replace path with /udp
162
- urlObj.pathname = '/udp';
163
- wsUrl = urlObj.toString();
164
- }
165
-
166
- // Add leaseId and token query parameters if not present
167
- if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
168
- urlObj.searchParams.set('leaseId', this.leaseId);
169
- }
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;
176
- }
177
- wsUrl = urlObj.toString();
178
- } catch (urlError) {
179
- const error = new Error(`UDP_RELAY_UNAVAILABLE: Invalid relayUrl format: ${urlError.message}`);
180
- error.code = 'UDP_RELAY_UNAVAILABLE';
181
- this.log.error('udp.ws.invalid_relayUrl', {
182
- relayUrl: this.relayUrl,
183
- error: urlError.message
184
- });
185
- reject(error);
186
- return;
187
- }
188
-
189
- // UDP-S1: Validate JWT (AC1.4/AC5.1: signature verification and claim validation)
190
- // AC1.4/AC5.1: Use JWKS verifier - fail fast if JWKS unavailable (same as TCP/HTTP)
191
- // Enforces "no JWKS → no tunnel" policy
192
- // Note: JWT verification is async, so we need to handle it inside an async IIFE
193
- (async () => {
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
- }
201
- // AC1.4/AC5.1: Verify JWT signature and claims using JWKS
202
- // verifyAssignmentJWT will initialize JWKS on first call and fail fast if unavailable
203
- const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
204
- const payload = await verifyAssignmentJWT(this.jwt, {
205
- relayId: this.relayId,
206
- protocol: 'udp',
207
- tunnelMode: 'udpWs-v1',
208
- leaseId: this.leaseId
209
- });
210
-
211
- // Verification successful - payload is already validated (signature + all claims)
212
- this.log.debug('udp.jwt.verified', {
213
- relayId: payload.relayId,
214
- leaseId: payload.leaseId,
215
- protocol: payload.protocol,
216
- tunnelMode: payload.tunnelMode
217
- });
218
-
219
- this.verifiedJwt = this.jwt;
220
- // Continue with WebSocket connection setup after JWT verification
221
- this._setupWebSocketConnection(wsUrl, resolve, reject);
222
- } catch (jwtError) {
223
- // AC1.4/AC5.1: Map all verification errors to UDP_RELAY_UNAVAILABLE
224
- // This includes: JWKS unavailable, signature invalid, claims mismatch, expired, etc.
225
- const error = new Error(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
226
- error.code = 'UDP_RELAY_UNAVAILABLE';
227
- error.cause = jwtError;
228
- this.log.error('udp.jwt.verification_failed', {
229
- error: jwtError.message,
230
- code: jwtError.code,
231
- leaseId: this.leaseId,
232
- relayId: this.relayId
233
- });
234
- reject(error);
235
- }
236
- })();
237
- });
238
- }
239
-
240
- _setupWebSocketConnection(wsUrl, resolve, reject) {
241
- // Clean up previous WebSocket if exists
242
- if (this.ws) {
243
- const old = this.ws;
244
- old.removeAllListeners();
245
- old.on('error', () => {}); // a late error from the old socket must not crash the CLI
246
- this.ws = null;
247
- }
248
-
249
- // UDP-S1: Connect to relay with TLS (rejectUnauthorized: true by default)
250
- const wsOptions = {
251
- headers: {
252
- 'Authorization': `Bearer ${this.jwt}`,
253
- 'X-Asyx-DeviceId': this.deviceId,
254
- 'X-Asyx-RequestId': this.requestId
255
- },
256
- rejectUnauthorized: process.env.ASYX_TLS_INSECURE !== '1', // Allow dev override
257
- };
258
- const ws = new WebSocket(wsUrl, wsOptions);
259
- this.ws = ws;
260
- let opened = false;
261
- let failure = null;
262
-
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');
270
-
271
- // UDP-S1: Start PING keepalive timer
272
- this.startPingKeepalive();
273
-
274
- // UDP-S1: Start flow cleanup timer
275
- this.startFlowCleanup();
276
-
277
- // UDP-S14: Per-flow sockets are created on-demand in handleUdpDatagram
278
- // No global socket initialization needed - each flowId gets its own socket
279
-
280
- resolve();
281
- });
282
-
283
- ws.on('message', (data, isBinary) => {
284
- this.lastInboundMs = Date.now();
285
- // UDP-S1: All udpWs-v1 frames are binary
286
- const isActuallyBinary = isBinary || Buffer.isBuffer(data);
287
-
288
- if (isActuallyBinary) {
289
- this.handleBinaryFrame(data);
290
- return;
291
- }
292
-
293
- // UDP-S1: Non-binary frames are protocol violations
294
- this.log.warn({ size: data.length, isBinary }, 'udp.text_frame_rejected', {
295
- note: 'UDP tunnel only accepts binary udpWs-v1 frames'
296
- });
297
- this.handleProtocolViolation(
298
- new UdpV1FramingError('Text frame received in UDP tunnel', 'INVALID_FRAME_TYPE')
299
- );
300
- });
301
-
302
- ws.on('close', (code, reason) => {
303
- const reasonStr = reason?.toString() || '';
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;
319
- }
320
- this._onDropped(code, reasonStr);
321
- });
322
-
323
- ws.on('error', (err) => {
324
- // A 'close' event always follows; the decision is made there
325
- failure = err;
326
- this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
327
- });
328
- }
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
-
366
- // UDP-S1: Handle binary udpWs-v1 frames
367
- handleBinaryFrame(data) {
368
- // Append new data to frame buffer
369
- this.frameBuffer = Buffer.concat([this.frameBuffer, Buffer.from(data)]);
370
-
371
- // Process complete frames from buffer
372
- while (this.frameBuffer.length >= FRAME_HEADER_SIZE) {
373
- try {
374
- const frame = decodeFrame(this.frameBuffer, 0);
375
-
376
- // Remove consumed bytes from buffer
377
- this.frameBuffer = this.frameBuffer.subarray(frame.consumed);
378
-
379
- // Validate frame
380
- try {
381
- validateFrame(frame);
382
- } catch (err) {
383
- if (err instanceof UdpV1FramingError) {
384
- this.log.error({
385
- error: err.message,
386
- code: err.code,
387
- frameType: frame.type,
388
- flowId: frame.flowId,
389
- payloadSize: frame.payload.length
390
- }, 'udp.protocol_violation');
391
- this.handleProtocolViolation(err);
392
- return;
393
- }
394
- throw err;
395
- }
396
-
397
- // Route frame by type
398
- this.routeFrame(frame);
399
- } catch (err) {
400
- if (err instanceof UdpV1FramingError) {
401
- // Incomplete frame - wait for more data
402
- if (err.code === 'INCOMPLETE_FRAME') {
403
- break; // Wait for more data
404
- }
405
- // Other framing errors are protocol violations
406
- this.log.error({
407
- error: err.message,
408
- code: err.code
409
- }, 'udp.protocol_violation');
410
- this.handleProtocolViolation(err);
411
- return;
412
- }
413
- // Unexpected error
414
- this.log.error({ error: err.message }, 'udp.frame_decode_error');
415
- this.handleProtocolViolation(new UdpV1FramingError(`Frame decode error: ${err.message}`, 'DECODE_ERROR'));
416
- return;
417
- }
418
- }
419
- }
420
-
421
- // UDP-S1: Route frame by type
422
- routeFrame(frame) {
423
- switch (frame.type) {
424
- case FrameType.UDP_DGRAM:
425
- this.handleUdpDatagram(frame);
426
- break;
427
- case FrameType.UDP_CLOSE:
428
- this.handleUdpClose(frame);
429
- break;
430
- case FrameType.PING:
431
- this.handlePing(frame);
432
- break;
433
- case FrameType.PONG:
434
- this.handlePong(frame);
435
- break;
436
- default:
437
- // Unknown frame type - protocol violation
438
- this.log.error({ frameType: frame.type }, 'udp.unknown_frame_type');
439
- this.handleProtocolViolation(
440
- new UdpV1FramingError(`Unknown frame type: ${frame.type}`, 'UNKNOWN_FRAME_TYPE')
441
- );
442
- }
443
- }
444
-
445
- // UDP-S1: Handle protocol violation - close tunnel
446
- handleProtocolViolation(error) {
447
- if (this.protocolViolation) {
448
- return; // Already handling violation
449
- }
450
-
451
- this.protocolViolation = true;
452
- this.log.error({
453
- error: error.message,
454
- code: error.code
455
- }, 'udp.protocol_violation_closing_tunnel');
456
-
457
- // Close UDP socket
458
- this.closeAllFlowSockets();
459
-
460
- // Close WebSocket connection; Story 11.2: the close event reconnects with fresh state
461
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
462
- this.ws.close(1003, `Protocol violation: ${error.message}`); // 1003 = Unsupported Data
463
- } else if (this.ws) {
464
- this.ws.terminate();
465
- }
466
- }
467
-
468
- // UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
469
- // UDP-S13: Forward to targetHost:targetPort (app's listening port)
470
- // UDP-S14: Use per-flow socket for correct return path routing
471
- handleUdpDatagram(frame) {
472
- const flowId = frame.flowId;
473
- const now = Date.now();
474
-
475
- // UDP-S14: Lookup or create per-flow socket
476
- let flowState = this.flowMap.get(flowId);
477
- let socket = flowState?.socket;
478
-
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
- }
488
- // Create new per-flow socket for this flowId
489
- socket = dgram.createSocket(this.dialFamily);
490
-
491
- // UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
492
- this.socketToFlowId.set(socket, flowId);
493
-
494
- // UDP-S14: Store socket in flowMap immediately (before bind completes)
495
- flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
496
- this.flowMap.set(flowId, flowState);
497
-
498
- // Bind the ephemeral port on loopback, then connect, then listen.
499
- socket.bind(0, this.dialAddress, () => {
500
- const address = socket.address();
501
- this.log.debug({
502
- flowId,
503
- localAddress: address.address,
504
- localPort: address.port,
505
- targetHost: this.dialAddress,
506
- targetPort: this.targetPort
507
- }, 'udp.flow.socket.bound');
508
-
509
- socket.connect(this.targetPort, this.dialAddress, () => {
510
- this.log.debug({
511
- flowId,
512
- targetHost: this.dialAddress,
513
- targetPort: this.targetPort
514
- }, 'udp.flow.socket.connected');
515
-
516
- flowState.connected = true;
517
-
518
- socket.on('message', (msg, rinfo) => {
519
- // We know the flowId from the socket itself
520
- const socketFlowId = this.socketToFlowId.get(socket);
521
- if (socketFlowId === flowId) {
522
- this.handleLocalDatagram(msg, rinfo, flowId);
523
- } else {
524
- this.log.error({
525
- flowId,
526
- socketFlowId,
527
- note: 'FlowId mismatch in socket message handler'
528
- }, 'udp.flow.socket.mismatch');
529
- }
530
- });
531
-
532
- socket.on('error', (err) => {
533
- this.log.error({
534
- flowId,
535
- error: err.message,
536
- code: err.code
537
- }, 'udp.flow.socket.error');
538
-
539
- // UDP-S13: If target app isn't listening, log clearly
540
- if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
541
- this.log.warn({
542
- flowId,
543
- targetHost: this.dialAddress,
544
- targetPort: this.targetPort,
545
- note: 'Target app may not be listening on this port'
546
- }, 'udp.target.unreachable');
547
- }
548
- });
549
-
550
- if (flowState.pendingPayload) {
551
- this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
552
- flowState.pendingPayload = null;
553
- }
554
- });
555
- });
556
- } else {
557
- // Update lastSeen for existing flow
558
- flowState.lastSeen = now;
559
-
560
- // UDP-S13: Send payload using existing socket
561
- // If socket is not yet connected, queue the payload
562
- if (flowState.connected) {
563
- this.sendDatagramToApp(socket, flowId, frame.payload);
564
- } else {
565
- // Queue payload until socket is connected
566
- flowState.pendingPayload = frame.payload;
567
- }
568
- }
569
- }
570
-
571
- // UDP-S13: Helper to send datagram to app on flow-specific socket
572
- sendDatagramToApp(socket, flowId, payload) {
573
- if (!socket || this.protocolViolation) {
574
- return;
575
- }
576
-
577
- socket.send(
578
- payload,
579
- (err) => {
580
- if (err) {
581
- this.log.error({
582
- flowId,
583
- error: err.message,
584
- code: err.code,
585
- targetHost: this.targetHost,
586
- targetPort: this.targetPort
587
- }, 'udp.datagram.send_error');
588
- } else {
589
- // UDP-S14: Log with flowId for tracking
590
- this.log.debug({
591
- flowId,
592
- size: payload.length,
593
- targetHost: this.targetHost,
594
- targetPort: this.targetPort
595
- }, 'udp.datagram.delivered');
596
- }
597
- }
598
- );
599
- }
600
-
601
- // UDP-S1: Handle UDP_CLOSE frame (flow shutdown hint)
602
- // UDP-S14: Close per-flow socket
603
- handleUdpClose(frame) {
604
- const flowId = frame.flowId;
605
- this.log.debug({ flowId }, 'udp.flow.close');
606
-
607
- // UDP-S14: Close and remove per-flow socket
608
- const flowState = this.flowMap.get(flowId);
609
- if (flowState?.socket) {
610
- flowState.socket.close();
611
- this.socketToFlowId.delete(flowState.socket);
612
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
613
- }
614
-
615
- // Remove flow from mapping
616
- this.flowMap.delete(flowId);
617
- }
618
-
619
- // UDP-S1: Handle PING frame (respond with PONG)
620
- handlePing(frame) {
621
- this.lastPongMs = Date.now();
622
-
623
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
624
- try {
625
- const pongFrame = encodeFrame({
626
- type: FrameType.PONG,
627
- flowId: 0,
628
- payload: frame.payload // Echo ping payload in pong
629
- });
630
- this.ws.send(pongFrame, { binary: true });
631
- } catch (err) {
632
- this.log.error({ error: err.message }, 'udp.pong.encode_error');
633
- }
634
- }
635
- }
636
-
637
- // UDP-S1: Handle PONG frame (update lastPongMs)
638
- handlePong(frame) {
639
- this.lastPongMs = Date.now();
640
- }
641
-
642
- // UDP-S13: Handle incoming datagram from app (via per-flow socket)
643
- // Forward app responses to relay via WebSocket
644
- // UDP-S14: flowId is known from the socket itself (per-flow socket architecture)
645
- handleLocalDatagram(msg, rinfo, flowId) {
646
- // UDP-S14: flowId is passed as parameter (we know it from the socket)
647
- if (!flowId) {
648
- this.log.error({
649
- note: 'flowId not provided to handleLocalDatagram - this should not happen'
650
- }, 'udp.datagram.flow_missing');
651
- return; // Drop datagram if flowId is unknown
652
- }
653
-
654
- // UDP-S14: Verify flowId is still active
655
- if (!this.flowMap.has(flowId)) {
656
- this.log.warn({
657
- flowId,
658
- note: 'Received datagram on closed/evicted flow'
659
- }, 'udp.datagram.flow_closed');
660
- return; // Drop datagram if flow is closed
661
- }
662
-
663
- // UDP-S1: Validate datagram size (max 64 KiB)
664
- if (msg.length > 65536) {
665
- this.log.error({
666
- size: msg.length,
667
- maxSize: 65536
668
- }, 'udp.datagram.oversize');
669
- return; // Drop oversize datagram
670
- }
671
-
672
- // UDP-S1: Encode as UDP_DGRAM frame and send over WS
673
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
674
- try {
675
- const frame = encodeFrame({
676
- type: FrameType.UDP_DGRAM,
677
- flowId: flowId,
678
- payload: msg
679
- });
680
- this.ws.send(frame, { binary: true });
681
- // UDP-S14: Log with flowId for tracking return path
682
- // UDP-S14: Log with flowId (known from per-flow socket)
683
- this.log.debug({
684
- flowId,
685
- size: msg.length,
686
- note: 'App response forwarded with flowId (per-flow socket)'
687
- }, 'udp.datagram.sent');
688
- } catch (err) {
689
- if (err instanceof UdpV1FramingError) {
690
- this.log.error({ flowId, error: err.message }, 'udp.frame_encode_error');
691
- this.handleProtocolViolation(err);
692
- } else {
693
- this.log.error({ flowId, error: err.message }, 'udp.send_error');
694
- }
695
- }
696
- }
697
- }
698
-
699
- // UDP-S1: Start PING keepalive timer
700
- startPingKeepalive() {
701
- this.stopPingKeepalive(); // never two timers after a reconnect
702
- if (this.pingIntervalMs <= 0) {
703
- this.log.debug('PING keepalive disabled (ASYX_UDP_PING_INTERVAL_MS <= 0)');
704
- return;
705
- }
706
-
707
- this.pingTimer = setInterval(() => {
708
- this.sendPing();
709
- }, this.pingIntervalMs);
710
-
711
- this.log.debug({ interval: this.pingIntervalMs }, 'udp.ping.keepalive.started');
712
- }
713
-
714
- // UDP-S1: Stop PING keepalive timer
715
- stopPingKeepalive() {
716
- if (this.pingTimer) {
717
- clearInterval(this.pingTimer);
718
- this.pingTimer = null;
719
- this.log.debug('udp.ping.keepalive.stopped');
720
- }
721
- }
722
-
723
- // UDP-S1: Send PING frame
724
- sendPing() {
725
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.protocolViolation) {
726
- return;
727
- }
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
-
738
- try {
739
- const pingFrame = encodeFrame({
740
- type: FrameType.PING,
741
- flowId: 0,
742
- payload: Buffer.from(Date.now().toString()) // Include timestamp for debugging
743
- });
744
- this.ws.send(pingFrame, { binary: true });
745
- } catch (err) {
746
- this.log.error({ error: err.message }, 'udp.ping.encode_error');
747
- }
748
- }
749
-
750
- // UDP-S1: Start flow cleanup timer (evict idle flows)
751
- startFlowCleanup() {
752
- if (this.flowIdleTimeoutMs <= 0) {
753
- return;
754
- }
755
-
756
- // Run cleanup every 30 seconds
757
- this.flowCleanupTimer = setInterval(() => {
758
- const now = Date.now();
759
- const expiredFlows = [];
760
-
761
- for (const [flowId, flow] of this.flowMap.entries()) {
762
- if (now - flow.lastSeen > this.flowIdleTimeoutMs) {
763
- expiredFlows.push(flowId);
764
- }
765
- }
766
-
767
- for (const flowId of expiredFlows) {
768
- // UDP-S14: Close per-flow socket before removing
769
- const flowState = this.flowMap.get(flowId);
770
- if (flowState?.socket) {
771
- flowState.socket.close();
772
- this.socketToFlowId.delete(flowState.socket);
773
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
774
- }
775
- this.flowMap.delete(flowId);
776
- this.log.debug({ flowId }, 'udp.flow.idle_evicted');
777
- }
778
- }, 30000); // Check every 30 seconds
779
- }
780
-
781
- // UDP-S1: Stop flow cleanup timer
782
- stopFlowCleanup() {
783
- if (this.flowCleanupTimer) {
784
- clearInterval(this.flowCleanupTimer);
785
- this.flowCleanupTimer = null;
786
- }
787
- }
788
-
789
- // UDP-S14: Close all per-flow sockets
790
- closeAllFlowSockets() {
791
- for (const [flowId, flowState] of this.flowMap.entries()) {
792
- if (flowState?.socket) {
793
- flowState.socket.close();
794
- this.socketToFlowId.delete(flowState.socket);
795
- this.log.debug({ flowId }, 'udp.flow.socket.closed');
796
- }
797
- }
798
- this.flowMap.clear();
799
- }
800
-
801
- close() {
802
- // Story 11.2: a deliberate close does not reconnect
803
- this.closing = true;
804
- this.reconnector.stop();
805
- this.stopPingKeepalive();
806
- this.stopFlowCleanup();
807
- this.closeAllFlowSockets();
808
-
809
- if (this.ws) {
810
- this.ws.close();
811
- }
812
- }
813
- }