asyx 0.2.3 → 0.2.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Asyx Command Line Interface",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -93,7 +93,7 @@ export default async function tunnel(args = []) {
93
93
  process.stdout.write(` asyx tunnel connect Connect to control plane (TLS 8883)\n`);
94
94
  process.stdout.write(` asyx tunnel --http --port <n> Create HTTP tunnel on local port <n>\n`);
95
95
  process.stdout.write(` asyx tunnel --http --port <n> --secgroup <slug> Create HTTP tunnel with QuickPass security group\n`);
96
- process.stdout.write(` asyx tunnel --tcp --port <n> Create TCP tunnel on local port <n> (localhost only)\n`);
96
+ process.stdout.write(` asyx tunnel --tcp --port <n> [--external-port <p>] Create TCP tunnel on local port <n> (localhost only)\n`);
97
97
  process.stdout.write(` asyx tunnel --minecraft [--port 25565] [--name <svc>] Create Minecraft TCP tunnel (expands to --tcp --port 25565 --kind minecraft)\n`);
98
98
  process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
99
99
  process.stdout.write(` asyx tunnel --help Show this help\n`);
@@ -157,7 +157,7 @@ export default async function tunnel(args = []) {
157
157
  process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
158
158
  process.exit(2);
159
159
  }
160
- return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind);
160
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind, parsed.externalPort);
161
161
  }
162
162
 
163
163
  logger.error("cli.args.unknown", { args: args.join(' ') });
@@ -213,6 +213,22 @@ function parseArgs(args) {
213
213
  process.stderr.write("Error: --secgroup requires a slug\n");
214
214
  process.exit(2);
215
215
  }
216
+ } else if (arg === '--external-port' || arg === '--ext-port') {
217
+ // TPB-03B: Parse --external-port flag (alias --ext-port)
218
+ if (i + 1 < args.length) {
219
+ const externalPort = parseInt(args[i + 1], 10);
220
+ if (isNaN(externalPort) || externalPort < 1 || externalPort > 65535) {
221
+ logger.error("cli.args.external_port_invalid", { value: args[i + 1] });
222
+ process.stderr.write(`Error: Invalid external port number: ${args[i + 1]}\n`);
223
+ process.exit(2);
224
+ }
225
+ parsed.externalPort = externalPort;
226
+ i++; // Skip next argument as it's the external port value
227
+ } else {
228
+ logger.error("cli.args.external_port_missing", {});
229
+ process.stderr.write("Error: --external-port requires a port number\n");
230
+ process.exit(2);
231
+ }
216
232
  } else if (arg === '--help' || arg === '-h') {
217
233
  parsed.help = true;
218
234
  }
@@ -757,11 +773,8 @@ async function httpTunnel(localPort, secGroupSlug) {
757
773
  // Update jwtMeta for HttpTunnel
758
774
  tunnelInstanceRef.tunnel.jwtMeta = { token: newJwt, expMs };
759
775
 
760
- // Record refresh timestamp and delta metrics
761
- const { recordRefresh } = await import('../state/assignment.js');
762
- const deltaMs = recordRefresh(Date.now());
763
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
764
- logger.debug('jwt.refresh.delta', { deltaMs });
776
+ // Note: recordRefresh is called in http-tunnel.js after in-band reauth succeeds
777
+ // to avoid double-counting when refresh happens via in-band reauth
765
778
 
766
779
  // Try in-band reauth if WebSocket is open
767
780
  if (tunnelInstanceRef.tunnel.ws && tunnelInstanceRef.tunnel.ws.readyState === 1) {
@@ -1149,8 +1162,10 @@ function isLocalhostTarget(target) {
1149
1162
  * Reuses existing MQTT control-plane infrastructure.
1150
1163
  * @param {number} localPort - Local port number
1151
1164
  * @param {string} [serviceName] - Optional service name
1165
+ * @param {string} [kind] - Optional service kind
1166
+ * @param {number} [requestedExternalPort] - Optional requested external port (TPB-03B)
1152
1167
  */
1153
- async function tcpTunnel(localPort, serviceName, kind = null) {
1168
+ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalPort = null) {
1154
1169
  logger.info('cli.tcp.start', { localPort, serviceName });
1155
1170
  process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1156
1171
 
@@ -1361,6 +1376,7 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1361
1376
 
1362
1377
  // TCP-S2: Include optional opts.name if service name provided
1363
1378
  // E3-S8: Include opts.kind if provided
1379
+ // TPB-03B: Include requestedExternalPort if provided
1364
1380
  openPayload.opts = {
1365
1381
  preferredPort: null // Can be wired to a flag later if needed
1366
1382
  };
@@ -1372,6 +1388,11 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1372
1388
  if (kind) {
1373
1389
  openPayload.opts.kind = kind;
1374
1390
  }
1391
+
1392
+ // TPB-03B: Include requestedExternalPort in opts (null if omitted)
1393
+ if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
1394
+ openPayload.opts.requestedExternalPort = requestedExternalPort;
1395
+ }
1375
1396
 
1376
1397
  // Publish the open request
1377
1398
  await core.publish({
@@ -1474,8 +1495,45 @@ async function tcpTunnel(localPort, serviceName, kind = null) {
1474
1495
 
1475
1496
  } catch (error) {
1476
1497
  // TCP-S3: Handle Coordinator error codes distinctly
1498
+ // TPB-03B: Handle new port block error codes
1477
1499
  const errorCode = error.code || error.reason || error.data?.reason;
1478
1500
 
1501
+ // TPB-03B: TCP_PORT_OUT_OF_BLOCK
1502
+ if (errorCode === 'TCP_PORT_OUT_OF_BLOCK' || errorCode === 'tcp_port_out_of_block') {
1503
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
1504
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
1505
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
1506
+ logger.error("cli.tcp.error.port_out_of_block", {
1507
+ error: error.message,
1508
+ requestedPort,
1509
+ blockStart,
1510
+ blockEnd
1511
+ });
1512
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
1513
+ try { await core.end(); } catch {}
1514
+ process.exit(1);
1515
+ }
1516
+
1517
+ // TPB-03B: TCP_PORT_ALREADY_IN_USE
1518
+ if (errorCode === 'TCP_PORT_ALREADY_IN_USE' || errorCode === 'tcp_port_already_in_use') {
1519
+ const requestedPort = error.requestedPort || error.data?.requestedPort || requestedExternalPort || 'X';
1520
+ logger.error("cli.tcp.error.port_already_in_use", { error: error.message, requestedPort });
1521
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
1522
+ try { await core.end(); } catch {}
1523
+ process.exit(1);
1524
+ }
1525
+
1526
+ // TPB-03B: TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT
1527
+ if (errorCode === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || errorCode === 'tcp_port_block_exhausted_for_tenant' ||
1528
+ errorCode === 'TCP_PORT_BLOCK_EXHAUSTED' || errorCode === 'tcp_port_block_exhausted') {
1529
+ const blockStart = error.blockStart || error.data?.blockStart || 'A';
1530
+ const blockEnd = error.blockEnd || error.data?.blockEnd || 'B';
1531
+ logger.error("cli.tcp.error.block_exhausted", { error: error.message, blockStart, blockEnd });
1532
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
1533
+ try { await core.end(); } catch {}
1534
+ process.exit(1);
1535
+ }
1536
+
1479
1537
  if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
1480
1538
  logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
1481
1539
  process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
@@ -167,6 +167,29 @@ const registry = {
167
167
  }
168
168
 
169
169
  // TCP-S3: Handle TCP-specific error codes
170
+ // TPB-03B: Handle new port block error codes
171
+ if (d.reason === 'TCP_PORT_OUT_OF_BLOCK' || d.reason === 'tcp_port_out_of_block') {
172
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
173
+ const blockStart = d.blockStart || 'A';
174
+ const blockEnd = d.blockEnd || 'B';
175
+ process.stderr.write(`Requested external port ${requestedPort} is outside your assigned block ${blockStart}–${blockEnd}.\n`);
176
+ process.exit(1);
177
+ }
178
+
179
+ if (d.reason === 'TCP_PORT_ALREADY_IN_USE' || d.reason === 'tcp_port_already_in_use') {
180
+ const requestedPort = d.requestedPort || d.requestedExternalPort || 'X';
181
+ process.stderr.write(`External port ${requestedPort} is already in use by another active tunnel.\n`);
182
+ process.exit(1);
183
+ }
184
+
185
+ if (d.reason === 'TCP_PORT_BLOCK_EXHAUSTED_FOR_TENANT' || d.reason === 'tcp_port_block_exhausted_for_tenant' ||
186
+ d.reason === 'TCP_PORT_BLOCK_EXHAUSTED' || d.reason === 'tcp_port_block_exhausted') {
187
+ const blockStart = d.blockStart || 'A';
188
+ const blockEnd = d.blockEnd || 'B';
189
+ process.stderr.write(`All 10 ports in your block ${blockStart}–${blockEnd} are currently in use.\n`);
190
+ process.exit(1);
191
+ }
192
+
170
193
  if (d.reason === 'TCP_PORT_CAPACITY_EXHAUSTED' || d.reason === 'tcp_port_capacity_exhausted') {
171
194
  process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
172
195
  process.exit(1);
@@ -325,7 +325,7 @@ export class TcpTunnel {
325
325
  this.closeStream(streamId);
326
326
  }
327
327
 
328
- this.log.info({ streamId }, 'tcp.stream.open');
328
+ this.log.info({ streamId, localPort: this.localPort }, 'tcp.stream.open');
329
329
 
330
330
  // Open local TCP socket to 127.0.0.1:localPort
331
331
  const localSocket = net.createConnection({
@@ -335,6 +335,9 @@ export class TcpTunnel {
335
335
  keepAliveInitialDelay: this.tcpKeepaliveInitialDelay
336
336
  });
337
337
 
338
+ // Log when connection attempt starts
339
+ this.log.debug({ streamId, localPort: this.localPort }, 'tcp.stream.local_connecting');
340
+
338
341
  // TCP-S5: Set up idle timeout for this stream (parity with relay)
339
342
  const idleTimer = setTimeout(() => {
340
343
  this.log.warn({ streamId }, 'tcp.stream.idle_timeout');
@@ -344,14 +347,9 @@ export class TcpTunnel {
344
347
  // Track stream activity
345
348
  const lastActivity = Date.now();
346
349
 
347
- // Buffer for STREAM_DATA frames that arrive before socket is connected
348
- const dataBuffer = [];
349
- let socketConnected = false;
350
-
351
350
  // Handle local socket connection
352
351
  localSocket.on('connect', () => {
353
352
  this.log.debug({ streamId }, 'tcp.stream.local_connected');
354
- socketConnected = true;
355
353
 
356
354
  // Update stream state to mark socket as connected
357
355
  const stream = this.activeStreams.get(streamId);
@@ -359,21 +357,20 @@ export class TcpTunnel {
359
357
  stream.socketConnected = true;
360
358
  }
361
359
 
362
- // Flush any buffered STREAM_DATA frames
363
- if (dataBuffer.length > 0) {
364
- this.log.debug({ streamId, bufferedCount: dataBuffer.length }, 'tcp.stream.flushing_buffered_data');
365
- if (stream && stream.localSocket && !stream.localSocket.destroyed) {
366
- for (const bufferedData of dataBuffer) {
367
- const written = stream.localSocket.write(bufferedData);
360
+ // Flush any buffered STREAM_DATA frames from stream.dataBuffer
361
+ if (stream && stream.dataBuffer && stream.dataBuffer.length > 0) {
362
+ this.log.debug({ streamId, bufferedCount: stream.dataBuffer.length }, 'tcp.stream.flushing_buffered_data');
363
+ if (stream.localSocket && !stream.localSocket.destroyed) {
364
+ const buf = stream.dataBuffer;
365
+ while (buf.length > 0) {
366
+ const chunk = buf.shift();
367
+ const written = stream.localSocket.write(chunk);
368
368
  if (!written) {
369
369
  this.log.warn({ streamId }, 'tcp.stream_data.local_socket_backpressure_on_flush');
370
370
  }
371
371
  }
372
372
  }
373
- dataBuffer.length = 0; // Clear buffer
374
- if (stream) {
375
- stream.dataBuffer = []; // Also clear in stream state
376
- }
373
+ stream.dataBuffer = []; // Clear buffer after flush
377
374
  }
378
375
  });
379
376
 
@@ -426,21 +423,21 @@ export class TcpTunnel {
426
423
 
427
424
  // Handle local socket errors
428
425
  localSocket.on('error', (err) => {
429
- this.log.error({ streamId, error: err.message }, 'tcp.stream.local_error');
426
+ this.log.error({ streamId, error: err.message, code: err.code, localPort: this.localPort }, 'tcp.stream.local_error');
430
427
  if (err.code === 'ECONNREFUSED') {
431
428
  this.log.error({ port: this.localPort }, 'Local TCP service refused connection');
432
- // Send STREAM_ERROR to relay
433
- if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
434
- try {
435
- const errorFrame = encodeFrame({
436
- type: FrameType.STREAM_ERROR,
437
- streamId: streamId,
438
- payload: Buffer.from(`ECONNREFUSED: ${err.message}`)
439
- });
440
- this.ws.send(errorFrame, { binary: true });
441
- } catch (frameErr) {
442
- this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
443
- }
429
+ }
430
+ // Send STREAM_ERROR to relay for all errors so it knows the connection failed
431
+ if (this.ws && this.ws.readyState === WebSocket.OPEN && !this.protocolViolation) {
432
+ try {
433
+ const errorFrame = encodeFrame({
434
+ type: FrameType.STREAM_ERROR,
435
+ streamId: streamId,
436
+ payload: Buffer.from(`${err.code || 'ERROR'}: ${err.message}`)
437
+ });
438
+ this.ws.send(errorFrame, { binary: true });
439
+ } catch (frameErr) {
440
+ this.log.error({ streamId, error: frameErr.message }, 'tcp.frame_encode_error');
444
441
  }
445
442
  }
446
443
  this.closeStream(streamId);
@@ -470,7 +467,7 @@ export class TcpTunnel {
470
467
  localSocket,
471
468
  idleTimer,
472
469
  lastActivity,
473
- dataBuffer, // Buffer for data arriving before socket connects
470
+ dataBuffer: [], // Buffer for data arriving before socket connects
474
471
  socketConnected: false // Will be set to true in 'connect' handler
475
472
  });
476
473
  }