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