asyx 0.3.2 → 0.4.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.
package/README.md CHANGED
@@ -16,6 +16,12 @@ npm uninstall -g asyx # remove
16
16
 
17
17
  ---
18
18
 
19
+ ## What's New in 0.4.0
20
+
21
+ **Improved large file downloads**: HTTP tunnels now automatically use streaming transport for large responses (8 MiB+ or unknown size). This enables reliable downloads of any size without hitting memory limits or connection timeouts. The switch happens automatically—no flags or configuration needed. Small responses continue to work exactly as before.
22
+
23
+ ---
24
+
19
25
  ## 1. Set up the device (once per host)
20
26
  ```bash
21
27
  asyx setup
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Asyx Command Line Interface",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -58,6 +58,7 @@
58
58
  "src/state/instance-registry.js",
59
59
  "src/tcp-v1/framing.js",
60
60
  "src/tunnel/http-tunnel.js",
61
+ "src/tunnel/httpws-constants.js",
61
62
  "src/tunnel/tcp-tunnel.js",
62
63
  "src/tunnel/udp-tunnel.js",
63
64
  "src/tunnel/ws-control.js",
@@ -88,6 +89,7 @@
88
89
  "check": "node ./src/main.js --version",
89
90
  "test": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand",
90
91
  "test:ci": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --forceExit",
92
+ "test:e2e:httpwsv2": "NODE_OPTIONS=\"--experimental-vm-modules --max-old-space-size=8192\" jest --runInBand --testPathIgnorePatterns=/node_modules/ --testMatch='**/test/e2e/**/*.e2e.test.js'",
91
93
  "pack:verify": "node scripts/pack-verify.mjs",
92
94
  "prepublishOnly": "npm run test:ci && npm run pack:verify",
93
95
  "prepack": "node scripts/prepack.mjs",
@@ -225,21 +225,71 @@ export default async function tunnel(args = []) {
225
225
  process.exit(2);
226
226
  }
227
227
 
228
+ // UDP-S16: Helper to find closest matching flag for "did you mean" suggestions
229
+ function findClosestFlag(unknownFlag, knownFlags) {
230
+ // Normalize: convert underscores to dashes and lowercase
231
+ const normalize = (str) => str.replace(/_/g, '-').toLowerCase();
232
+ const normalizedUnknown = normalize(unknownFlag);
233
+
234
+ // Find exact match after normalization
235
+ for (const known of knownFlags) {
236
+ if (normalize(known) === normalizedUnknown) {
237
+ return known;
238
+ }
239
+ }
240
+
241
+ // Find close match (contains normalized unknown or vice versa)
242
+ let closest = null;
243
+ for (const known of knownFlags) {
244
+ const normalizedKnown = normalize(known);
245
+ if (normalizedKnown.includes(normalizedUnknown) || normalizedUnknown.includes(normalizedKnown)) {
246
+ if (!closest || Math.abs(normalizedKnown.length - normalizedUnknown.length) < Math.abs(normalize(closest).length - normalizedUnknown.length)) {
247
+ closest = known;
248
+ }
249
+ }
250
+ }
251
+
252
+ return closest;
253
+ }
254
+
255
+ // UDP-S16: List of known flags for tunnel command
256
+ const KNOWN_TUNNEL_FLAGS = [
257
+ '--http',
258
+ '--tcp',
259
+ '--udp',
260
+ '--minecraft',
261
+ '--port',
262
+ '--name',
263
+ '--secgroup',
264
+ '--target-host',
265
+ '--external-port',
266
+ '--ext-port',
267
+ '--help',
268
+ '-h'
269
+ ];
270
+
228
271
  // Simple argument parser (minimist-like)
272
+ // UDP-S16: Enhanced with unknown flag detection
229
273
  function parseArgs(args) {
230
274
  const parsed = {};
275
+ const consumed = new Set(); // Track consumed argument indices
276
+
231
277
  for (let i = 0; i < args.length; i++) {
278
+ if (consumed.has(i)) continue; // Skip already consumed arguments
279
+
232
280
  const arg = args[i];
233
281
  if (arg === '--http') {
234
282
  parsed.http = true;
283
+ consumed.add(i);
235
284
  } else if (arg === '--tcp') {
236
285
  parsed.tcp = true;
286
+ consumed.add(i);
237
287
  } else if (arg === '--udp') {
238
288
  parsed.udp = true;
289
+ consumed.add(i);
239
290
  } else if (arg === '--minecraft') {
240
291
  parsed.minecraft = true;
241
- } else if (arg === '--minecraft') {
242
- parsed.minecraft = true;
292
+ consumed.add(i);
243
293
  } else if (arg === '--port') {
244
294
  if (i + 1 < args.length) {
245
295
  const port = parseInt(args[i + 1], 10);
@@ -249,6 +299,8 @@ function parseArgs(args) {
249
299
  process.exit(2);
250
300
  }
251
301
  parsed.port = port;
302
+ consumed.add(i);
303
+ consumed.add(i + 1);
252
304
  i++; // Skip next argument as it's the port value
253
305
  } else {
254
306
  logger.error("cli.args.port_missing", {});
@@ -259,6 +311,8 @@ function parseArgs(args) {
259
311
  // Optional service name for TCP mode
260
312
  if (i + 1 < args.length) {
261
313
  parsed.serviceName = args[i + 1];
314
+ consumed.add(i);
315
+ consumed.add(i + 1);
262
316
  i++; // Skip next argument as it's the service name value
263
317
  } else {
264
318
  logger.error("cli.args.name_missing", {});
@@ -269,6 +323,8 @@ function parseArgs(args) {
269
323
  // QPA-04: Parse --secgroup flag
270
324
  if (i + 1 < args.length) {
271
325
  parsed.secGroupSlug = args[i + 1];
326
+ consumed.add(i);
327
+ consumed.add(i + 1);
272
328
  i++; // Skip next argument as it's the slug value
273
329
  } else {
274
330
  logger.error("cli.args.secgroup_missing", {});
@@ -279,6 +335,8 @@ function parseArgs(args) {
279
335
  // UDP-S13: Parse --target-host flag (defaults to 127.0.0.1)
280
336
  if (i + 1 < args.length) {
281
337
  parsed.targetHost = args[i + 1];
338
+ consumed.add(i);
339
+ consumed.add(i + 1);
282
340
  i++; // Skip next argument as it's the target host value
283
341
  } else {
284
342
  logger.error("cli.args.target_host_missing", {});
@@ -295,6 +353,8 @@ function parseArgs(args) {
295
353
  process.exit(2);
296
354
  }
297
355
  parsed.externalPort = externalPort;
356
+ consumed.add(i);
357
+ consumed.add(i + 1);
298
358
  i++; // Skip next argument as it's the external port value
299
359
  } else {
300
360
  logger.error("cli.args.external_port_missing", {});
@@ -303,7 +363,20 @@ function parseArgs(args) {
303
363
  }
304
364
  } else if (arg === '--help' || arg === '-h') {
305
365
  parsed.help = true;
366
+ consumed.add(i);
367
+ } else if (arg.startsWith('--')) {
368
+ // UDP-S16: Unknown flag detected
369
+ const closest = findClosestFlag(arg, KNOWN_TUNNEL_FLAGS);
370
+ if (closest) {
371
+ // User-friendly error message only (no structured logging for user-facing errors)
372
+ process.stderr.write(`Error: Unknown option: ${arg}. Did you mean: ${closest}?\n`);
373
+ } else {
374
+ // User-friendly error message only (no structured logging for user-facing errors)
375
+ process.stderr.write(`Error: Unknown option: ${arg}\n`);
376
+ }
377
+ process.exit(1);
306
378
  }
379
+ // Non-flag arguments (like "connect") are not consumed here and will be handled by the caller
307
380
  }
308
381
  return parsed;
309
382
  }
@@ -201,7 +201,12 @@ export async function dispatch(parsedMessage) {
201
201
  });
202
202
  unmatchedEventLogged = true;
203
203
  // Reset after 60 seconds to allow occasional logging
204
- setTimeout(() => { unmatchedEventLogged = false; }, 60000);
204
+ // Store timeout handle for potential cleanup (though module-level cleanup is rare)
205
+ const timeoutHandle = setTimeout(() => { unmatchedEventLogged = false; }, 60000);
206
+ // In test mode, unref the timeout so it doesn't keep the process alive
207
+ if (process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test') {
208
+ timeoutHandle.unref();
209
+ }
205
210
  }
206
211
  return;
207
212
  }
@@ -6,6 +6,15 @@ import crypto from 'node:crypto';
6
6
  // CLI-REAUTH: Control frame helper for in-band reauth
7
7
  import { sendControlAndWaitAck, dispatchControlFrame, clearAllWaiters } from './ws-control.js';
8
8
 
9
+ // S-3: Import HTTP-WS v2 protocol constants
10
+ import {
11
+ HTTPWS_V2_TARGET_CHUNK_BYTES,
12
+ HTTPWS_V2_MAX_CHUNK_BYTES,
13
+ HTTP_BODY_CHUNK
14
+ } from './httpws-constants.js';
15
+
16
+ const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
17
+
9
18
  export class HttpTunnel {
10
19
  constructor({
11
20
  relayUrl,
@@ -81,6 +90,12 @@ export class HttpTunnel {
81
90
  // CLI-REAUTH: In-band reauth configuration
82
91
  this.reauthAckTimeoutMs = Number(process.env.CLI_REAUTH_ACK_TIMEOUT_MS || 3000); // 3 seconds default
83
92
  this.reauthInFlight = null; // Single-flight guard: Promise or null
93
+
94
+ // S-0: Track negotiated HTTP-WS version
95
+ this.httpWsVersion = null;
96
+
97
+ // S-1: Track in-progress v2 responses (requestId -> { mode: 'v2', bufferedBytes: 0 })
98
+ this.activeV2Responses = new Map();
84
99
  }
85
100
 
86
101
  // CLI-RES-DPJWT-LEAD: Safe JWT decode helper
@@ -492,6 +507,9 @@ export class HttpTunnel {
492
507
  // CLI-IMG-WSReconnect: Reset retry count on successful connection
493
508
  this.retryCount = 0;
494
509
 
510
+ // S-0: Send hello frame for HTTP-WS v2 negotiation
511
+ this._sendHello();
512
+
495
513
  // CLI-RES-DPJWT-LEAD: Check if refresh needed before resuming
496
514
  this._checkRefreshLeadWindow();
497
515
 
@@ -526,6 +544,12 @@ export class HttpTunnel {
526
544
  return;
527
545
  }
528
546
 
547
+ // S-0: Handle hello_ack for HTTP-WS v2 negotiation
548
+ if (msg.type === 'hello_ack') {
549
+ this._handleHelloAck(msg);
550
+ return;
551
+ }
552
+
529
553
  if (msg.type === 'ping') {
530
554
  this.ws.send(JSON.stringify({ type: 'pong' }));
531
555
  return;
@@ -1168,31 +1192,23 @@ export class HttpTunnel {
1168
1192
  };
1169
1193
 
1170
1194
  const proxyReq = http.request(options, (proxyRes) => {
1171
- // Send response back to relay using CRT-Relay-B compact format
1172
- const responseChunks = [];
1173
- proxyRes.on('data', chunk => {
1174
- responseChunks.push(chunk);
1175
- });
1195
+ // S-1: Determine response mode at http_response_start
1196
+ const contentLength = proxyRes.headers['content-length']
1197
+ ? parseInt(proxyRes.headers['content-length'], 10)
1198
+ : null;
1199
+ const isChunked = proxyRes.headers['transfer-encoding']?.toLowerCase() === 'chunked';
1200
+ const selectedMode = this._selectResponseMode(contentLength, isChunked);
1176
1201
 
1177
- proxyRes.on('end', () => {
1178
- // CRT-Relay-E: Update activity on HTTP response
1179
- this.lastActivityMs = Date.now();
1180
-
1181
- // Convert headers to array format and encode body as base64
1182
- const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
1183
- const bodyBuffer = Buffer.concat(responseChunks);
1184
- const bodyBase64 = bodyBuffer.length ? bodyBuffer.toString('base64') : '';
1185
-
1186
- const responseData = {
1187
- t: 'http_response',
1188
- rid: requestId, // Use the same rid from the request
1189
- s: proxyRes.statusCode,
1190
- h: headerArray,
1191
- b: bodyBase64
1192
- };
1193
-
1194
- this.ws.send(JSON.stringify(responseData));
1195
- });
1202
+ // S-1: Version guard - if v2 not negotiated, force v1
1203
+ const useV2 = selectedMode === 'v2' && this._canUseV2();
1204
+
1205
+ if (useV2) {
1206
+ // S-1: V2 streaming path
1207
+ this._handleV2Response(proxyRes, requestId);
1208
+ } else {
1209
+ // S-1: V1 single-frame path (existing behavior)
1210
+ this._handleV1Response(proxyRes, requestId);
1211
+ }
1196
1212
  });
1197
1213
 
1198
1214
  // Handle connection errors to local service
@@ -1275,6 +1291,233 @@ export class HttpTunnel {
1275
1291
  proxyReq.end();
1276
1292
  }
1277
1293
 
1294
+ // S-0: Send hello frame for HTTP-WS v2 negotiation
1295
+ _sendHello() {
1296
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1297
+ this.log.warn('Cannot send hello: WebSocket not open');
1298
+ return;
1299
+ }
1300
+
1301
+ const hello = {
1302
+ type: 'hello',
1303
+ protocols: {
1304
+ httpWs: ['v2']
1305
+ }
1306
+ };
1307
+
1308
+ this.ws.send(JSON.stringify(hello));
1309
+ this.log.debug('Hello frame sent', { protocols: hello.protocols });
1310
+ }
1311
+
1312
+ // S-0: Handle hello_ack for HTTP-WS v2 negotiation
1313
+ _handleHelloAck(helloAck) {
1314
+ this.httpWsVersion = helloAck.protocols?.httpWs || null;
1315
+ this.log.info('Hello ack received', { httpWsVersion: this.httpWsVersion });
1316
+
1317
+ if (this.httpWsVersion !== 'v2') {
1318
+ this.log.debug('HTTP-WS v2 not negotiated, will use v1 mode');
1319
+ }
1320
+ }
1321
+
1322
+ // S-0: Check if HTTP-WS v2 can be used (guard for v2 frame sending)
1323
+ // This method should be called before sending any HTTP_BODY_CHUNK (0x20) frames
1324
+ // Returns true if v2 is negotiated, false otherwise (should fallback to v1)
1325
+ _canUseV2() {
1326
+ return this.httpWsVersion === 'v2';
1327
+ }
1328
+
1329
+ // S-1: Convert requestId string to 8-byte big-endian uint64 buffer
1330
+ // Note: requestId is a UUID string, so we hash it deterministically to get 8 bytes
1331
+ // Both CLI and relay use the same hash function for matching
1332
+ _encodeRequestId(requestId) {
1333
+ const hash = crypto.createHash('sha256').update(requestId).digest();
1334
+ const buffer = Buffer.alloc(8);
1335
+ hash.copy(buffer, 0, 0, 8);
1336
+ // Buffer is already big-endian by default in Node.js
1337
+ return buffer;
1338
+ }
1339
+
1340
+ // S-1: Determine response mode (v1 or v2) based on content-length and size
1341
+ _selectResponseMode(contentLength, isChunked) {
1342
+ // S-1: Use v2 if:
1343
+ // - Content-Length >= 8 MiB, OR
1344
+ // - Content-Length unknown/missing or TE: chunked, OR
1345
+ // - Will cross 8 MiB threshold during buffering
1346
+ if (isChunked || contentLength === null || contentLength === undefined) {
1347
+ return 'v2'; // Unknown length or chunked - use v2
1348
+ }
1349
+ if (contentLength >= V2_THRESHOLD_BYTES) {
1350
+ return 'v2'; // Large known size - use v2
1351
+ }
1352
+ return 'v1'; // Small known size - use v1
1353
+ }
1354
+
1355
+ // S-1: Send HTTP-WS v2 binary chunk frame
1356
+ _sendV2Chunk(requestId, payload) {
1357
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1358
+ this.log.warn('Cannot send v2 chunk: WebSocket not open', { requestId });
1359
+ return false;
1360
+ }
1361
+
1362
+ // Encode frame: frameType (1 byte) + requestId (8 bytes) + payload
1363
+ const requestIdBuffer = this._encodeRequestId(requestId);
1364
+ const frame = Buffer.concat([
1365
+ Buffer.from([HTTP_BODY_CHUNK]),
1366
+ requestIdBuffer,
1367
+ payload
1368
+ ]);
1369
+
1370
+ try {
1371
+ this.ws.send(frame, { binary: true });
1372
+ return true;
1373
+ } catch (error) {
1374
+ this.log.error('Failed to send v2 chunk', { requestId, error: error.message });
1375
+ return false;
1376
+ }
1377
+ }
1378
+
1379
+ // S-1: Chunk payload into v2-compliant sizes (64 KiB target, 256 KiB max)
1380
+ _chunkPayload(payload) {
1381
+ const chunks = [];
1382
+ let offset = 0;
1383
+
1384
+ while (offset < payload.length) {
1385
+ // Target 64 KiB, but don't exceed 256 KiB
1386
+ const remaining = payload.length - offset;
1387
+ const chunkSize = Math.min(
1388
+ HTTPWS_V2_TARGET_CHUNK_BYTES,
1389
+ Math.min(remaining, HTTPWS_V2_MAX_CHUNK_BYTES)
1390
+ );
1391
+ chunks.push(payload.slice(offset, offset + chunkSize));
1392
+ offset += chunkSize;
1393
+ }
1394
+
1395
+ return chunks;
1396
+ }
1397
+
1398
+ // S-1: Handle v2 streaming response
1399
+ _handleV2Response(proxyRes, requestId) {
1400
+ // Track this response as v2
1401
+ this.activeV2Responses.set(requestId, { mode: 'v2', bufferedBytes: 0 });
1402
+
1403
+ // Convert headers to array format
1404
+ const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
1405
+
1406
+ // S-1: Send http_response_start with mode: "stream"
1407
+ const responseStart = {
1408
+ type: 'http_response_start',
1409
+ rid: requestId,
1410
+ status: proxyRes.statusCode,
1411
+ headers: headerArray,
1412
+ mode: 'stream'
1413
+ };
1414
+
1415
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1416
+ this.log.warn('Cannot send v2 response: WebSocket not open', { requestId });
1417
+ this.activeV2Responses.delete(requestId);
1418
+ return;
1419
+ }
1420
+
1421
+ this.ws.send(JSON.stringify(responseStart));
1422
+
1423
+ // S-1: Stream chunks as they arrive
1424
+ let buffer = Buffer.alloc(0);
1425
+ const flushBuffer = () => {
1426
+ if (buffer.length === 0) return;
1427
+
1428
+ const chunks = this._chunkPayload(buffer);
1429
+ for (const chunk of chunks) {
1430
+ if (!this._sendV2Chunk(requestId, chunk)) {
1431
+ // Send failed, abort response
1432
+ this.log.error('Failed to send v2 chunk, aborting response', { requestId });
1433
+ this.activeV2Responses.delete(requestId);
1434
+ return;
1435
+ }
1436
+ }
1437
+ buffer = Buffer.alloc(0);
1438
+ };
1439
+
1440
+ proxyRes.on('data', (chunk) => {
1441
+ // CRT-Relay-E: Update activity on HTTP response data
1442
+ this.lastActivityMs = Date.now();
1443
+
1444
+ // Accumulate chunk
1445
+ buffer = Buffer.concat([buffer, chunk]);
1446
+
1447
+ // Flush when buffer reaches target chunk size
1448
+ if (buffer.length >= HTTPWS_V2_TARGET_CHUNK_BYTES) {
1449
+ flushBuffer();
1450
+ }
1451
+ });
1452
+
1453
+ proxyRes.on('end', () => {
1454
+ // CRT-Relay-E: Update activity on HTTP response end
1455
+ this.lastActivityMs = Date.now();
1456
+
1457
+ // Flush any remaining data
1458
+ flushBuffer();
1459
+
1460
+ // S-1: Send http_response_end
1461
+ const responseEnd = {
1462
+ type: 'http_response_end',
1463
+ rid: requestId
1464
+ };
1465
+
1466
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1467
+ this.ws.send(JSON.stringify(responseEnd));
1468
+ }
1469
+
1470
+ // Clean up tracking
1471
+ this.activeV2Responses.delete(requestId);
1472
+ });
1473
+
1474
+ proxyRes.on('error', (error) => {
1475
+ this.log.error('Error in v2 response stream', { requestId, error: error.message });
1476
+ this.activeV2Responses.delete(requestId);
1477
+ });
1478
+ }
1479
+
1480
+ // S-1: Handle v1 single-frame response (existing behavior)
1481
+ _handleV1Response(proxyRes, requestId) {
1482
+ const responseChunks = [];
1483
+ let bufferedBytes = 0;
1484
+
1485
+ proxyRes.on('data', (chunk) => {
1486
+ responseChunks.push(chunk);
1487
+ bufferedBytes += chunk.length;
1488
+
1489
+ // S-1: If buffering for v1 crosses 8 MiB, abort and retry as v2
1490
+ if (bufferedBytes >= V2_THRESHOLD_BYTES && this._canUseV2()) {
1491
+ this.log.warn('V1 response exceeded 8 MiB threshold, aborting', { requestId, bufferedBytes });
1492
+ // Note: In a real implementation, we'd need to abort the proxyRes stream
1493
+ // For now, we'll continue with v1 but log the issue
1494
+ // This is a limitation - we can't easily switch mid-stream
1495
+ }
1496
+ });
1497
+
1498
+ proxyRes.on('end', () => {
1499
+ // CRT-Relay-E: Update activity on HTTP response
1500
+ this.lastActivityMs = Date.now();
1501
+
1502
+ // Convert headers to array format and encode body as base64
1503
+ const headerArray = Object.entries(proxyRes.headers).map(([name, value]) => [name, value]);
1504
+ const bodyBuffer = Buffer.concat(responseChunks);
1505
+ const bodyBase64 = bodyBuffer.length ? bodyBuffer.toString('base64') : '';
1506
+
1507
+ const responseData = {
1508
+ t: 'http_response',
1509
+ rid: requestId, // Use the same rid from the request
1510
+ s: proxyRes.statusCode,
1511
+ h: headerArray,
1512
+ b: bodyBase64
1513
+ };
1514
+
1515
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1516
+ this.ws.send(JSON.stringify(responseData));
1517
+ }
1518
+ });
1519
+ }
1520
+
1278
1521
  close() {
1279
1522
  // CLI-IMG-WSReconnect: Disable reconnects and clear timer
1280
1523
  this.shouldReconnect = false;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * HTTP-WS v2 Protocol Constants
3
+ *
4
+ * These constants define the authoritative values for HTTP-WS v2 protocol
5
+ * implementation. They must match the values used by the relay server.
6
+ *
7
+ * @see relay/src/httpws-constants.js
8
+ */
9
+
10
+ // S-3: Protocol constants alignment
11
+ export const HTTPWS_V2_TARGET_CHUNK_BYTES = 65_536; // 64 KiB target chunk size
12
+ export const HTTPWS_V2_MAX_CHUNK_BYTES = 262_144; // 256 KiB hard maximum chunk size
13
+ export const HTTPWS_V2_PROTOCOL_ERROR_CLOSE_CODE = 1002; // WebSocket close code for protocol errors
14
+ export const HTTPWS_V2_PROTOCOL_ERROR_REASON = 'httpws_v2_without_negotiation'; // Close reason string
15
+ export const HTTP_BODY_CHUNK = 0x20; // Frame type for HTTP body chunks (v2)
16
+
@@ -38,7 +38,7 @@ export class UdpTunnel {
38
38
  this.relayId = relayId; // AC5.1: Store relayId for JWT validation
39
39
  this.log = log;
40
40
  this.ws = null;
41
- this.udpSocket = null;
41
+ // UDP-S14: Per-flow sockets managed via flowMap (no single udpSocket)
42
42
 
43
43
  // Coordinator connection (not used for UDP refresh yet)
44
44
  this.coordinatorCore = coordinatorCore;
@@ -51,10 +51,11 @@ export class UdpTunnel {
51
51
  this.getForceReconnect = getForceReconnect;
52
52
  this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
53
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
54
+ // UDP-S14: Per-flow socket mapping for correct return path routing
55
+ // flowId -> { socket, lastSeen } - one UDP socket per flowId, connected to targetHost:targetPort
56
+ this.flowMap = new Map(); // flowId -> { socket, lastSeen }
57
+ // Reverse mapping: socket -> flowId (for message handlers)
58
+ this.socketToFlowId = new WeakMap(); // socket -> flowId
58
59
 
59
60
  // UDP-S1: Binary frame buffer for partial frames
60
61
  this.frameBuffer = Buffer.alloc(0);
@@ -195,74 +196,10 @@ export class UdpTunnel {
195
196
  // UDP-S1: Start flow cleanup timer
196
197
  this.startFlowCleanup();
197
198
 
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');
199
+ // UDP-S14: Per-flow sockets are created on-demand in handleUdpDatagram
200
+ // No global socket initialization needed - each flowId gets its own socket
201
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
- });
202
+ resolve();
266
203
  });
267
204
 
268
205
  this.ws.on('message', (data, isBinary) => {
@@ -294,7 +231,7 @@ export class UdpTunnel {
294
231
 
295
232
  this.stopPingKeepalive();
296
233
  this.stopFlowCleanup();
297
- this.closeUdpSocket();
234
+ this.closeAllFlowSockets();
298
235
 
299
236
  // UDP-S1: Exit on WS close (no reconnect loop)
300
237
  this.log.info('UDP tunnel exiting due to WebSocket close');
@@ -305,7 +242,7 @@ export class UdpTunnel {
305
242
  this.log.error({ err: err.message, code: err.code }, 'udp.tunnel.ws.error');
306
243
  this.stopPingKeepalive();
307
244
  this.stopFlowCleanup();
308
- this.closeUdpSocket();
245
+ this.closeAllFlowSockets();
309
246
 
310
247
  // UDP-S1: Exit on WS error (no reconnect loop)
311
248
  const error = new Error(`UDP_RELAY_UNAVAILABLE: WebSocket connection failed: ${err.message}`);
@@ -407,7 +344,7 @@ export class UdpTunnel {
407
344
  }, 'udp.protocol_violation_closing_tunnel');
408
345
 
409
346
  // Close UDP socket
410
- this.closeUdpSocket();
347
+ this.closeAllFlowSockets();
411
348
 
412
349
  // Close WebSocket connection
413
350
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
@@ -420,51 +357,147 @@ export class UdpTunnel {
420
357
 
421
358
  // UDP-S1: Handle UDP_DGRAM frame (datagram from relay)
422
359
  // UDP-S13: Forward to targetHost:targetPort (app's listening port)
360
+ // UDP-S14: Use per-flow socket for correct return path routing
423
361
  handleUdpDatagram(frame) {
424
362
  const flowId = frame.flowId;
363
+ const now = Date.now();
425
364
 
426
- // Update flow mapping (track lastSeen)
427
- this.flowMap.set(flowId, { lastSeen: Date.now() });
365
+ // UDP-S14: Lookup or create per-flow socket
366
+ let flowState = this.flowMap.get(flowId);
367
+ let socket = flowState?.socket;
428
368
 
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
- }
369
+ if (!socket) {
370
+ // Create new per-flow socket for this flowId
371
+ socket = dgram.createSocket('udp4');
372
+
373
+ // UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
374
+ this.socketToFlowId.set(socket, flowId);
375
+
376
+ // UDP-S14: Store socket in flowMap immediately (before bind completes)
377
+ flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
378
+ this.flowMap.set(flowId, flowState);
379
+
380
+ // UDP-S13: Bind to OS-assigned port (ephemeral)
381
+ socket.bind(0, '0.0.0.0', () => {
382
+ const address = socket.address();
383
+ this.log.debug({
384
+ flowId,
385
+ localAddress: address.address,
386
+ localPort: address.port,
387
+ targetHost: this.targetHost,
388
+ targetPort: this.targetPort
389
+ }, 'udp.flow.socket.bound');
390
+
391
+ // UDP-S13: Connect to targetHost:targetPort (allows send() without address/port)
392
+ socket.connect(this.targetPort, this.targetHost, () => {
393
+ this.log.debug({
394
+ flowId,
395
+ targetHost: this.targetHost,
396
+ targetPort: this.targetPort
397
+ }, 'udp.flow.socket.connected');
398
+
399
+ // UDP-S14: Mark socket as connected
400
+ flowState.connected = true;
401
+
402
+ // UDP-S13: Send any pending payload now that socket is connected
403
+ if (flowState.pendingPayload) {
404
+ this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
405
+ flowState.pendingPayload = null;
406
+ }
407
+ });
408
+
409
+ // UDP-S14: Handle incoming datagrams from app on this flow's socket
410
+ socket.on('message', (msg, rinfo) => {
411
+ // We know the flowId from the socket itself
412
+ const socketFlowId = this.socketToFlowId.get(socket);
413
+ if (socketFlowId === flowId) {
414
+ this.handleLocalDatagram(msg, rinfo, flowId);
451
415
  } else {
452
- this.log.debug({
416
+ this.log.error({
453
417
  flowId,
454
- size: frame.payload.length,
418
+ socketFlowId,
419
+ note: 'FlowId mismatch in socket message handler'
420
+ }, 'udp.flow.socket.mismatch');
421
+ }
422
+ });
423
+
424
+ socket.on('error', (err) => {
425
+ this.log.error({
426
+ flowId,
427
+ error: err.message,
428
+ code: err.code
429
+ }, 'udp.flow.socket.error');
430
+
431
+ // UDP-S13: If target app isn't listening, log clearly
432
+ if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
433
+ this.log.warn({
434
+ flowId,
455
435
  targetHost: this.targetHost,
456
- targetPort: this.targetPort
457
- }, 'udp.datagram.delivered');
436
+ targetPort: this.targetPort,
437
+ note: 'Target app may not be listening on this port'
438
+ }, 'udp.target.unreachable');
458
439
  }
459
- }
460
- );
440
+ });
441
+ });
442
+ } else {
443
+ // Update lastSeen for existing flow
444
+ flowState.lastSeen = now;
445
+
446
+ // UDP-S13: Send payload using existing socket
447
+ // If socket is not yet connected, queue the payload
448
+ if (flowState.connected) {
449
+ this.sendDatagramToApp(socket, flowId, frame.payload);
450
+ } else {
451
+ // Queue payload until socket is connected
452
+ flowState.pendingPayload = frame.payload;
453
+ }
454
+ }
455
+ }
456
+
457
+ // UDP-S13: Helper to send datagram to app on flow-specific socket
458
+ sendDatagramToApp(socket, flowId, payload) {
459
+ if (!socket || this.protocolViolation) {
460
+ return;
461
461
  }
462
+
463
+ socket.send(
464
+ payload,
465
+ (err) => {
466
+ if (err) {
467
+ this.log.error({
468
+ flowId,
469
+ error: err.message,
470
+ code: err.code,
471
+ targetHost: this.targetHost,
472
+ targetPort: this.targetPort
473
+ }, 'udp.datagram.send_error');
474
+ } else {
475
+ // UDP-S14: Log with flowId for tracking
476
+ this.log.debug({
477
+ flowId,
478
+ size: payload.length,
479
+ targetHost: this.targetHost,
480
+ targetPort: this.targetPort
481
+ }, 'udp.datagram.delivered');
482
+ }
483
+ }
484
+ );
462
485
  }
463
486
 
464
487
  // UDP-S1: Handle UDP_CLOSE frame (flow shutdown hint)
488
+ // UDP-S14: Close per-flow socket
465
489
  handleUdpClose(frame) {
466
490
  const flowId = frame.flowId;
467
491
  this.log.debug({ flowId }, 'udp.flow.close');
492
+
493
+ // UDP-S14: Close and remove per-flow socket
494
+ const flowState = this.flowMap.get(flowId);
495
+ if (flowState?.socket) {
496
+ flowState.socket.close();
497
+ this.socketToFlowId.delete(flowState.socket);
498
+ this.log.debug({ flowId }, 'udp.flow.socket.closed');
499
+ }
500
+
468
501
  // Remove flow from mapping
469
502
  this.flowMap.delete(flowId);
470
503
  }
@@ -492,37 +525,25 @@ export class UdpTunnel {
492
525
  this.lastPongMs = Date.now();
493
526
  }
494
527
 
495
- // UDP-S13: Handle incoming datagram from app (via connected ephemeral socket)
528
+ // UDP-S13: Handle incoming datagram from app (via per-flow socket)
496
529
  // 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;
530
+ // UDP-S14: flowId is known from the socket itself (per-flow socket architecture)
531
+ handleLocalDatagram(msg, rinfo, flowId) {
532
+ // UDP-S14: flowId is passed as parameter (we know it from the socket)
533
+ if (!flowId) {
534
+ this.log.error({
535
+ note: 'flowId not provided to handleLocalDatagram - this should not happen'
536
+ }, 'udp.datagram.flow_missing');
537
+ return; // Drop datagram if flowId is unknown
538
+ }
500
539
 
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');
540
+ // UDP-S14: Verify flowId is still active
541
+ if (!this.flowMap.has(flowId)) {
542
+ this.log.warn({
543
+ flowId,
544
+ note: 'Received datagram on closed/evicted flow'
545
+ }, 'udp.datagram.flow_closed');
546
+ return; // Drop datagram if flow is closed
526
547
  }
527
548
 
528
549
  // UDP-S1: Validate datagram size (max 64 KiB)
@@ -543,7 +564,13 @@ export class UdpTunnel {
543
564
  payload: msg
544
565
  });
545
566
  this.ws.send(frame, { binary: true });
546
- this.log.debug({ flowId, size: msg.length }, 'udp.datagram.sent');
567
+ // UDP-S14: Log with flowId for tracking return path
568
+ // UDP-S14: Log with flowId (known from per-flow socket)
569
+ this.log.debug({
570
+ flowId,
571
+ size: msg.length,
572
+ note: 'App response forwarded with flowId (per-flow socket)'
573
+ }, 'udp.datagram.sent');
547
574
  } catch (err) {
548
575
  if (err instanceof UdpV1FramingError) {
549
576
  this.log.error({ flowId, error: err.message }, 'udp.frame_encode_error');
@@ -614,6 +641,13 @@ export class UdpTunnel {
614
641
  }
615
642
 
616
643
  for (const flowId of expiredFlows) {
644
+ // UDP-S14: Close per-flow socket before removing
645
+ const flowState = this.flowMap.get(flowId);
646
+ if (flowState?.socket) {
647
+ flowState.socket.close();
648
+ this.socketToFlowId.delete(flowState.socket);
649
+ this.log.debug({ flowId }, 'udp.flow.socket.closed');
650
+ }
617
651
  this.flowMap.delete(flowId);
618
652
  this.log.debug({ flowId }, 'udp.flow.idle_evicted');
619
653
  }
@@ -628,18 +662,22 @@ export class UdpTunnel {
628
662
  }
629
663
  }
630
664
 
631
- // UDP-S1: Close UDP socket
632
- closeUdpSocket() {
633
- if (this.udpSocket) {
634
- this.udpSocket.close();
635
- this.udpSocket = null;
665
+ // UDP-S14: Close all per-flow sockets
666
+ closeAllFlowSockets() {
667
+ for (const [flowId, flowState] of this.flowMap.entries()) {
668
+ if (flowState?.socket) {
669
+ flowState.socket.close();
670
+ this.socketToFlowId.delete(flowState.socket);
671
+ this.log.debug({ flowId }, 'udp.flow.socket.closed');
672
+ }
636
673
  }
674
+ this.flowMap.clear();
637
675
  }
638
676
 
639
677
  close() {
640
678
  this.stopPingKeepalive();
641
679
  this.stopFlowCleanup();
642
- this.closeUdpSocket();
680
+ this.closeAllFlowSockets();
643
681
 
644
682
  if (this.ws) {
645
683
  this.ws.close();