asyx 0.1.3 → 0.2.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.
@@ -93,6 +93,8 @@ 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`);
97
+ process.stdout.write(` asyx tunnel --minecraft [--port 25565] [--name <svc>] Create Minecraft TCP tunnel (expands to --tcp --port 25565 --kind minecraft)\n`);
96
98
  process.stdout.write(` --secgroup <slug> Request QuickPass security group (requires tunnel reopen to apply)\n`);
97
99
  process.stdout.write(` asyx tunnel --help Show this help\n`);
98
100
  return;
@@ -101,26 +103,63 @@ export default async function tunnel(args = []) {
101
103
  // Handle legacy connect command
102
104
  if (args[0] === "connect") return connect();
103
105
 
104
- // Handle new --http --port flags
105
- if (parsed.http && parsed.port) {
106
- // QPA-CLI-11: Track QuickPass request for vault UX messaging
107
- if (parsed.secGroupSlug) {
108
- logger.info("qp.requested", { group: parsed.secGroupSlug });
106
+ // E3-S8: Handle --minecraft flag (expands to --tcp --port 25565 --kind minecraft)
107
+ if (parsed.minecraft) {
108
+ parsed.tcp = true;
109
+ if (!parsed.port) {
110
+ parsed.port = 25565; // Default Minecraft port
109
111
  }
110
- return httpTunnel(parsed.port, parsed.secGroupSlug);
112
+ parsed.kind = 'minecraft';
111
113
  }
112
114
 
113
- // Fail fast on unsupported combinations
115
+ // Validation: Mutual exclusion check MUST happen before dispatch to handlers
116
+ if (parsed.tcp && parsed.http) {
117
+ logger.error("cli.args.invalid", { reason: "--tcp and --http are mutually exclusive" });
118
+ process.stderr.write("Error: --tcp and --http are mutually exclusive\n");
119
+ process.exit(2);
120
+ }
121
+
122
+ // Validation: Fail fast on unsupported combinations
114
123
  if (parsed.http && !parsed.port) {
115
124
  logger.error("cli.args.invalid", { reason: "--http requires --port" });
116
125
  process.exit(2);
117
126
  }
118
127
 
119
- if (parsed.port && !parsed.http) {
120
- logger.error("cli.args.invalid", { reason: "--port requires --http" });
128
+ if (parsed.tcp && !parsed.port) {
129
+ logger.error("cli.args.invalid", { reason: "--tcp requires --port" });
130
+ process.stderr.write("Error: --tcp requires --port\n");
131
+ process.exit(2);
132
+ }
133
+
134
+ if (parsed.port && !parsed.http && !parsed.tcp) {
135
+ logger.error("cli.args.invalid", { reason: "--port requires --http or --tcp" });
136
+ process.stderr.write("Error: --port requires --http or --tcp\n");
121
137
  process.exit(2);
122
138
  }
123
139
 
140
+ // Handle new --http --port flags
141
+ if (parsed.http && parsed.port) {
142
+ // QPA-CLI-11: Track QuickPass request for vault UX messaging
143
+ if (parsed.secGroupSlug) {
144
+ logger.info("qp.requested", { group: parsed.secGroupSlug });
145
+ }
146
+ return httpTunnel(parsed.port, parsed.secGroupSlug);
147
+ }
148
+
149
+ // Handle new --tcp --port flags
150
+ if (parsed.tcp && parsed.port) {
151
+ // Validate target is localhost-only (defaults to 127.0.0.1)
152
+ const target = buildTcpTarget(parsed.port);
153
+ if (!isLocalhostTarget(target)) {
154
+ logger.error("cli.args.invalid", {
155
+ reason: `TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost). Got: ${target}`
156
+ });
157
+ process.stderr.write(`Error: TCP tunnels in v4.1 can only target localhost (127.0.0.1 / ::1 / localhost).\n`);
158
+ process.exit(2);
159
+ }
160
+ return tcpTunnel(parsed.port, parsed.serviceName, parsed.kind);
161
+ }
162
+
124
163
  logger.error("cli.args.unknown", { args: args.join(' ') });
125
164
  process.stderr.write(`Unknown subcommand or invalid flags: ${args.join(' ')}\n`);
126
165
  process.exit(2);
@@ -133,6 +172,12 @@ function parseArgs(args) {
133
172
  const arg = args[i];
134
173
  if (arg === '--http') {
135
174
  parsed.http = true;
175
+ } else if (arg === '--tcp') {
176
+ parsed.tcp = true;
177
+ } else if (arg === '--minecraft') {
178
+ parsed.minecraft = true;
179
+ } else if (arg === '--minecraft') {
180
+ parsed.minecraft = true;
136
181
  } else if (arg === '--port') {
137
182
  if (i + 1 < args.length) {
138
183
  const port = parseInt(args[i + 1], 10);
@@ -148,6 +193,16 @@ function parseArgs(args) {
148
193
  process.stderr.write("Error: --port requires a port number\n");
149
194
  process.exit(2);
150
195
  }
196
+ } else if (arg === '--name') {
197
+ // Optional service name for TCP mode
198
+ if (i + 1 < args.length) {
199
+ parsed.serviceName = args[i + 1];
200
+ i++; // Skip next argument as it's the service name value
201
+ } else {
202
+ logger.error("cli.args.name_missing", {});
203
+ process.stderr.write("Error: --name requires a service name\n");
204
+ process.exit(2);
205
+ }
151
206
  } else if (arg === '--secgroup') {
152
207
  // QPA-04: Parse --secgroup flag
153
208
  if (i + 1 < args.length) {
@@ -961,23 +1016,9 @@ async function connectToRelay(
961
1016
  await tunnel.open();
962
1017
 
963
1018
  // QPA-CLI-05: Schedule initial proactive refresh via MqttControlPlaneClient
964
- // Decode JWT to get expiration
965
- const jwtParts = assignment.jwt.split('.');
966
- if (jwtParts.length === 3) {
967
- try {
968
- const payload = JSON.parse(Buffer.from(jwtParts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
969
- const expMs = payload.exp ? payload.exp * 1000 : null;
970
- if (expMs) {
971
- // Use assignment.leaseId if available, otherwise pass null (will be set on next refresh)
972
- const leaseId = assignment.leaseId || null;
973
- mqttClient.scheduleRefresh(expMs, leaseId);
974
- // QPA-CLI-10: Telemetry logs default to debug for quiet mode
975
- logger.debug("jwt.refresh.schedule", { expEpochMs: expMs, context: 'open_ack', leaseId });
976
- }
977
- } catch (e) {
978
- logger.warn('jwt.refresh.schedule.invalid_token', { context: 'open_ack', error: e.message });
979
- }
980
- }
1019
+ // TCP-S4: Skip refresh scheduling for TCP tunnels (refresh not implemented yet)
1020
+ // HTTP tunnels continue to schedule refresh as before
1021
+ // Note: This is a temporary limitation until TCP refresh is implemented
981
1022
 
982
1023
  // QPA-CLI-11: Vault UX messaging - Final tunnel live message
983
1024
  const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
@@ -1054,4 +1095,515 @@ async function connectToRelay(
1054
1095
  }
1055
1096
  }
1056
1097
 
1098
+ /**
1099
+ * Build TCP target string from port.
1100
+ * Defaults to 127.0.0.1 (localhost-only in v4.1).
1101
+ * @param {number} port - Port number
1102
+ * @returns {string} Target string in format "127.0.0.1:port"
1103
+ */
1104
+ function buildTcpTarget(port) {
1105
+ return `127.0.0.1:${port}`;
1106
+ }
1107
+
1108
+ /**
1109
+ * Validate that target is localhost-only (127.0.0.1, ::1, or localhost).
1110
+ * @param {string} target - Target string in format "host:port"
1111
+ * @returns {boolean} True if target is localhost-only
1112
+ */
1113
+ function isLocalhostTarget(target) {
1114
+ // Extract host part (before the colon)
1115
+ const host = target.split(':')[0];
1116
+
1117
+ // Normalize hostname to lowercase for comparison
1118
+ const normalizedHost = host.toLowerCase();
1119
+
1120
+ // Allowed localhost values
1121
+ const allowedHosts = ['127.0.0.1', '::1', 'localhost'];
1122
+
1123
+ return allowedHosts.includes(normalizedHost);
1124
+ }
1125
+
1126
+ /**
1127
+ * TCP tunnel implementation (TCP-S2: cmd/open Payload + Compatibility).
1128
+ * Builds and sends MQTT cmd/open payload with protocol:"tcp" and target.
1129
+ * Reuses existing MQTT control-plane infrastructure.
1130
+ * @param {number} localPort - Local port number
1131
+ * @param {string} [serviceName] - Optional service name
1132
+ */
1133
+ async function tcpTunnel(localPort, serviceName, kind = null) {
1134
+ logger.info('cli.tcp.start', { localPort, serviceName });
1135
+ process.stdout.write(`⚙️ Initializing TCP tunnel on port ${localPort}…\n`);
1136
+
1137
+ // TCP-S1: Validation complete, target constructed
1138
+ const target = buildTcpTarget(localPort);
1139
+ logger.info('cli.tcp.target', { target });
1140
+
1141
+ // 0) Imports (kept local to this command to avoid global side-effects)
1142
+ const { loadAwsIotConfig } = await import("@asyx/mqtt-broker-aws");
1143
+ const { MqttCore } = await import("@asyx/mqtt-core");
1144
+ const { waitForAssignment } = await import("../state/assignment.js");
1145
+ const { MqttControlPlaneClient } = await import("../control-plane/MqttControlPlaneClient.js");
1146
+ const { MqttControlPlaneTransport } = await import("../control-plane/MqttControlPlaneTransport.js");
1147
+ const { readFileSync } = await import("node:fs");
1148
+
1149
+ // 1) Load IoT config (throws with clear messages if misconfigured)
1150
+ let cfg;
1151
+ try {
1152
+ cfg = loadAwsIotConfig();
1153
+ } catch (e) {
1154
+ logger.error("config.error", { error: e?.message || String(e) });
1155
+ process.stderr.write(`Config error: ${e?.message || e}\n`);
1156
+ process.exit(1);
1157
+ }
1158
+
1159
+ logger.info("cli.tcp.control_plane.establish", {});
1160
+ process.stdout.write(`🔐 Negotiating control-plane security…\n`);
1161
+
1162
+ // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
1163
+ const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || "60000", 10);
1164
+
1165
+ // Build MQTT URL from config - use mqtts (TLS) not wss (WebSocket)
1166
+ const port = 443;
1167
+ const mqttUrl = `mqtts://${cfg.endpoint}:${port}`;
1168
+
1169
+ // Load certificates for MQTT TLS options
1170
+ const ca = readFileSync(cfg.caPath);
1171
+ const cert = readFileSync(cfg.certPath);
1172
+ const key = readFileSync(cfg.keyPath);
1173
+
1174
+ // CLI-IMG-MQTT-Parity: Use relay's robust transport configuration
1175
+ const keepalive = parseInt(process.env.ASYX_CONTROL_PLANE_KEEPALIVE_SEC || "60", 10);
1176
+
1177
+ // CLI-MQTT-UniqueID-CleanSession: Use base client ID (MqttControlPlaneClient will add ULID suffix in unique mode)
1178
+ const baseClientId = cfg.clientId;
1179
+
1180
+ // 2) Build MqttControlPlaneClient for connection management
1181
+ const mqttClient = new MqttControlPlaneClient({
1182
+ url: mqttUrl,
1183
+ baseClientId,
1184
+ mqttOptions: {
1185
+ protocol: 'mqtts',
1186
+ port: 443,
1187
+ cert,
1188
+ key,
1189
+ ca,
1190
+ rejectUnauthorized: true,
1191
+ keepalive,
1192
+ connectTimeout: 8000,
1193
+ // ALPN for port 443 (AWS IoT)
1194
+ ALPNProtocols: ['x-amzn-mqtt-ca'],
1195
+ },
1196
+ mode: process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique',
1197
+ logger,
1198
+ onConnected: async (mqttClientInstance) => {
1199
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1200
+ logger.debug("mqtt.control_plane.connected", { clientId: mqttClient.getClientId() });
1201
+ process.stdout.write("✅ Control-plane sealed\n");
1202
+
1203
+ // Resubscribe to topics on reconnect
1204
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1205
+ try {
1206
+ await mqttClient.subscribe(evtWildcard, 0);
1207
+ logger.debug("mqtt.control_plane.resubscribed", { topic: evtWildcard });
1208
+ } catch (e) {
1209
+ logger.debug("mqtt.control_plane.resubscribe.failed", { error: e?.message || String(e) });
1210
+ }
1211
+ },
1212
+ onOffline: (reason) => {
1213
+ logger.debug("mqtt.control_plane.disconnected", { reason, clientId: mqttClient.getClientId() });
1214
+ process.stderr.write(`[mqtt] Control-plane connection lost: ${reason}\n`);
1215
+ },
1216
+ onFatalError: (reason, err) => {
1217
+ logger.error("mqtt.control_plane.fatal", { reason, error: err?.message || String(err) });
1218
+ process.stderr.write(`❌ Fatal control-plane error: ${reason}\n`);
1219
+ process.exit(1);
1220
+ },
1221
+ // TCP-S2: Refresh lease callback (similar to HTTP, but with TCP protocol)
1222
+ // TCP-S4: Make refresh non-fatal - disable refresh scheduling for TCP until implemented
1223
+ onRefreshLease: async () => {
1224
+ // TCP refresh not yet implemented - log and skip (non-fatal)
1225
+ logger.warn('tcp.refresh.not_implemented', {
1226
+ note: 'TCP refresh is not yet implemented; lease will expire naturally'
1227
+ });
1228
+ // Return without throwing to prevent fatal errors
1229
+ return;
1230
+ },
1231
+ });
1232
+
1233
+ // Create Transport adapter and MqttCore
1234
+ const transport = new MqttControlPlaneTransport(mqttClient);
1235
+ const core = new MqttCore(transport, { canPublish: () => true, canSubscribe: () => true });
1236
+
1237
+ // CLI-IMG-ControlPlane-Watchdog: Expose helpers for TcpTunnel compatibility
1238
+ const isControlPlaneConnected = () => {
1239
+ return mqttClient.isOnline();
1240
+ };
1241
+
1242
+ const waitForControlPlane = () => {
1243
+ if (mqttClient.isOnline()) {
1244
+ return Promise.resolve();
1245
+ }
1246
+ // Poll until connected or timeout
1247
+ const start = Date.now();
1248
+ return new Promise((resolve, reject) => {
1249
+ const interval = setInterval(() => {
1250
+ if (mqttClient.isOnline()) {
1251
+ clearInterval(interval);
1252
+ resolve();
1253
+ } else if (Date.now() - start >= CONTROL_PLANE_TIMEOUT_MS) {
1254
+ clearInterval(interval);
1255
+ reject(new Error('control_plane_timeout'));
1256
+ }
1257
+ }, 250);
1258
+ });
1259
+ };
1260
+
1261
+ // QPA-CLI-02: Expose helper to get last MQTT error for diagnostics
1262
+ const getLastMqttError = () => {
1263
+ // TODO: Add getLastMqttError to MqttControlPlaneClient if needed
1264
+ return null;
1265
+ };
1266
+
1267
+ // QPA-CLI-03: Expose helper to force reconnect
1268
+ const getForceReconnect = () => {
1269
+ // MqttControlPlaneClient handles reconnects automatically, but we can expose a method if needed
1270
+ return async () => {
1271
+ if (!mqttClient.isOnline()) {
1272
+ await mqttClient.disconnect();
1273
+ await mqttClient.connect();
1274
+ }
1275
+ };
1276
+ };
1277
+
1278
+ // QPA-CLI-01: Store tunnel reference for reconnect hook (use shared object so callback can access it)
1279
+ const tunnelInstanceRef = { tunnel: null };
1280
+
1281
+ // 3) Connect to control plane
1282
+ try {
1283
+ await mqttClient.connect();
1284
+ } catch (e) {
1285
+ logger.error("mqtt.connect.failed", { error: e?.message || String(e) });
1286
+ process.stderr.write(`Tunnel command failed: ${e?.message || e}\n`);
1287
+ process.exit(1);
1288
+ }
1289
+
1290
+ // 4) Set up topics and message handling
1291
+ const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
1292
+ const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
1293
+ const acknowledgmentTopic = `asyx/tunnel/clients/${baseClientId}/evt/ack`;
1294
+
1295
+ // Subscribe to topics after initial connect
1296
+ await core.subscribe(evtWildcard, 0);
1297
+
1298
+ // 5) Set up message ingress and dispatcher
1299
+ const ingress = new MessageIngress({
1300
+ maxAwaiters: 100,
1301
+ observability: process.env.ASYX_DEBUG === '1',
1302
+ logger
1303
+ });
1304
+
1305
+ ingress.setDispatcher(dispatchEvt);
1306
+
1307
+ core.onMessage(async (m) => {
1308
+ try {
1309
+ await ingress.handleMessage(m);
1310
+ } catch (e) {
1311
+ if (e && e.code === "SETUP_REQUIRED") {
1312
+ process.stderr.write(`❌ ${e.message}\n`);
1313
+ try { await core.end(); } catch {}
1314
+ process.exit(2);
1315
+ }
1316
+ if (e && typeof e.code === "string" && e.code.startsWith("ERROR_")) {
1317
+ process.stderr.write(`❌ ${e.message}\n`);
1318
+ try { await core.end(); } catch {}
1319
+ process.exit(1);
1320
+ }
1321
+ process.stderr.write(`❌ Unexpected: ${e?.message || String(e)}\n`);
1322
+ try { await core.end(); } catch {}
1323
+ process.exit(1);
1324
+ }
1325
+ });
1326
+
1327
+ // 6) Publish cmd/open request with TCP protocol
1328
+ const requestId = crypto.randomUUID();
1329
+ const { getFpHash } = await import("../lib/fingerprint.js");
1330
+ const fingerprint = await getFpHash(cfg.clientId);
1331
+
1332
+ // TCP-S2: Build TCP cmd/open payload
1333
+ // E3-S8: Include kind field if provided
1334
+ const openPayload = {
1335
+ requestId,
1336
+ proto: 'tcp', // Protocol identifier
1337
+ target: target, // "127.0.0.1:<port>" from TCP-S1
1338
+ clientId: cfg.clientId,
1339
+ ...fingerprint
1340
+ };
1341
+
1342
+ // TCP-S2: Include optional opts.name if service name provided
1343
+ // E3-S8: Include opts.kind if provided
1344
+ openPayload.opts = {
1345
+ preferredPort: null // Can be wired to a flag later if needed
1346
+ };
1347
+
1348
+ if (serviceName) {
1349
+ openPayload.opts.name = serviceName;
1350
+ }
1351
+
1352
+ if (kind) {
1353
+ openPayload.opts.kind = kind;
1354
+ }
1355
+
1356
+ // Publish the open request
1357
+ await core.publish({
1358
+ topic: cmdOpenTopic,
1359
+ payload: JSON.stringify(openPayload),
1360
+ qos: 1,
1361
+ retain: false
1362
+ });
1363
+
1364
+ logger.info("cli.cmd.open.sent", { requestId, protocol: 'tcp', target });
1365
+
1366
+ // 7) Wait for ack and assignment
1367
+ const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
1368
+
1369
+ try {
1370
+ const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
1371
+ logger.info("cli.ack.wait.start", { requestId });
1372
+ const assignment = await assignmentPromise;
1373
+ logger.info("cli.ack.wait.resolved", { requestId });
1374
+ logger.info("cli.assignment.received", {
1375
+ relayId: assignment.relayId,
1376
+ leaseId: assignment.leaseId,
1377
+ tcpAliasFqdn: assignment.tcpAliasFqdn,
1378
+ publicPort: assignment.publicPort
1379
+ });
1380
+
1381
+ // Persist assignment for refresh/fallback paths
1382
+ try {
1383
+ const { setAssignment } = await import("../state/assignment.js");
1384
+ setAssignment(assignment);
1385
+ } catch {}
1386
+
1387
+ // TCP-S3: Handle warnings array (alias unavailable)
1388
+ const warnings = assignment.warnings || [];
1389
+ if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
1390
+ logger.warn('tcp.alias.unavailable', {
1391
+ requestId,
1392
+ fqdn: assignment.fqdn,
1393
+ publicPort: assignment.publicPort
1394
+ });
1395
+ }
1396
+
1397
+ // TCP-S3: Build and display UX based on alias and SRV presence
1398
+ // E3-S8: Check for SRV status for Minecraft tunnels
1399
+ const tcpAliasFqdn = assignment.tcpAliasFqdn;
1400
+ const srvProvisioned = assignment.srvProvisioned === true;
1401
+ const srvFqdn = assignment.srvFqdn || null;
1402
+ const fqdn = assignment.fqdn;
1403
+ const publicPort = assignment.publicPort;
1404
+ const aliasRequestedButFailed = warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE');
1405
+
1406
+ if (tcpAliasFqdn) {
1407
+ // Alias present: show both alias and host:port
1408
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1409
+ process.stdout.write(` ${tcpAliasFqdn}\n`);
1410
+ process.stdout.write(` or\n`);
1411
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1412
+ // E3-S8: Show SRV info if available
1413
+ if (srvProvisioned && srvFqdn) {
1414
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record)\n`);
1415
+ }
1416
+ } else if (srvProvisioned && srvFqdn) {
1417
+ // E3-S8: SRV available but no alias (Minecraft without --name)
1418
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1419
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1420
+ process.stdout.write(`\n Minecraft clients can connect to: ${srvFqdn.replace('_minecraft._tcp.', '')} (SRV record, no port needed)\n`);
1421
+ } else if (aliasRequestedButFailed) {
1422
+ // User requested alias (--name) but provisioning failed
1423
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1424
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1425
+ process.stdout.write(` (alias unavailable; using host:port only)\n`);
1426
+ } else {
1427
+ // No alias requested, no SRV: just show host:port (normal case for plain --tcp)
1428
+ process.stdout.write(`Your TCP server is available at:\n\n`);
1429
+ process.stdout.write(` ${fqdn}:${publicPort}\n`);
1430
+ }
1431
+
1432
+ // TCP-S3: Log alias readiness if previously null alias becomes non-null
1433
+ // (This would require tracking previous assignment state, but for now we just log current state)
1434
+ if (tcpAliasFqdn) {
1435
+ logger.debug('tcp.alias.ready', {
1436
+ requestId,
1437
+ tcpAliasFqdn,
1438
+ fqdn,
1439
+ publicPort
1440
+ });
1441
+ }
1442
+
1443
+ // TCP-S4: Connect to relay using TcpTunnel for data-plane readiness
1444
+ await connectToRelayTcp(
1445
+ assignment,
1446
+ cfg.clientId,
1447
+ localPort,
1448
+ core,
1449
+ ingress,
1450
+ { isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS },
1451
+ tunnelInstanceRef, // QPA-CLI-01: Shared reference - tunnel will be stored here
1452
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
1453
+ );
1454
+
1455
+ } catch (error) {
1456
+ // TCP-S3: Handle Coordinator error codes distinctly
1457
+ const errorCode = error.code || error.reason || error.data?.reason;
1458
+
1459
+ if (errorCode === 'TCP_PORT_CAPACITY_EXHAUSTED' || errorCode === 'tcp_port_capacity_exhausted') {
1460
+ logger.error("cli.tcp.error.capacity_exhausted", { error: error.message });
1461
+ process.stderr.write(`Relay TCP port capacity exhausted. Please retry later.\n`);
1462
+ try { await core.end(); } catch {}
1463
+ process.exit(1);
1464
+ }
1465
+
1466
+ if (errorCode === 'TENANT_TCP_LEASE_LIMIT_REACHED' || errorCode === 'tenant_tcp_lease_limit_reached') {
1467
+ const relayId = error.relayId || error.data?.relayId || 'unknown';
1468
+ logger.error("cli.tcp.error.lease_limit", { error: error.message, relayId });
1469
+ process.stderr.write(`Tenant TCP lease limit reached on relay ${relayId}\n`);
1470
+ try { await core.end(); } catch {}
1471
+ process.exit(1);
1472
+ }
1473
+
1474
+ // TCP_ALIAS_UNAVAILABLE is handled as a warning, not an error
1475
+
1476
+ // Generic error handling
1477
+ logger.error("cli.ack.wait.failed", { error: error.message, errorCode });
1478
+ process.stderr.write(`❌ Tunnel assignment failed: ${error.message}\n`);
1479
+ try { await core.end(); } catch {}
1480
+ process.exit(1);
1481
+ }
1482
+ }
1483
+
1484
+ export async function connectToRelayTcp(
1485
+ assignment,
1486
+ deviceId,
1487
+ localPort,
1488
+ coordinatorCore,
1489
+ coordinatorIngress,
1490
+ controlPlaneHelpers,
1491
+ tunnelInstanceRef, // QPA-CLI-01: Pass reference to store tunnel instance
1492
+ mqttClient // QPA-CLI-05: Pass mqttClient for refresh scheduling (not used for TCP yet)
1493
+ ) {
1494
+ // Import TCP tunnel logic
1495
+ const { TcpTunnel } = await import("../tunnel/tcp-tunnel.js");
1496
+
1497
+ const tunnel = new TcpTunnel({
1498
+ relayUrl: assignment.relayUrl,
1499
+ jwt: assignment.jwt, // Use JWT as-is (no validation)
1500
+ deviceId,
1501
+ requestId: assignment.requestId,
1502
+ localPort,
1503
+ leaseId: assignment.leaseId, // E3-S3: Pass leaseId for TCP relay WebSocket query parameters
1504
+ coordinatorCore, // CLI-IMG-WSReconnect: Pass coordinator connection for JWT refresh (not used for TCP yet)
1505
+ coordinatorIngress, // CLI-IMG-WSReconnect: Pass coordinator ingress for JWT refresh (not used for TCP yet)
1506
+ // CLI-IMG-ControlPlane-Watchdog: Pass control-plane helpers
1507
+ isControlPlaneConnected: controlPlaneHelpers.isControlPlaneConnected,
1508
+ waitForControlPlane: controlPlaneHelpers.waitForControlPlane,
1509
+ getLastMqttError: controlPlaneHelpers.getLastMqttError, // QPA-CLI-02: Pass helper to get last MQTT error
1510
+ getForceReconnect: controlPlaneHelpers.getForceReconnect, // QPA-CLI-03: Pass helper to force reconnect
1511
+ controlPlaneTimeoutMs: controlPlaneHelpers.controlPlaneTimeoutMs,
1512
+ log: {
1513
+ info: (msgOrFields, maybeFields) => {
1514
+ if (typeof msgOrFields === 'string') return logger.info(msgOrFields, maybeFields);
1515
+ return logger.info(maybeFields, msgOrFields);
1516
+ },
1517
+ warn: (msgOrFields, maybeFields) => {
1518
+ if (typeof msgOrFields === 'string') return logger.warn(msgOrFields, maybeFields);
1519
+ return logger.warn(maybeFields, msgOrFields);
1520
+ },
1521
+ error: (msgOrFields, maybeFields) => {
1522
+ if (typeof msgOrFields === 'string') return logger.error(msgOrFields, maybeFields);
1523
+ return logger.error(maybeFields, msgOrFields);
1524
+ },
1525
+ debug: (msgOrFields, maybeFields) => {
1526
+ if (typeof msgOrFields === 'string') return logger.debug(msgOrFields, maybeFields);
1527
+ return logger.debug(maybeFields, msgOrFields);
1528
+ }
1529
+ }
1530
+ });
1531
+
1532
+ // QPA-CLI-01: Store tunnel instance before opening (so MQTT reconnect hook can access it)
1533
+ if (tunnelInstanceRef) {
1534
+ tunnelInstanceRef.tunnel = tunnel;
1535
+ }
1536
+
1537
+ try {
1538
+ await tunnel.open();
1539
+
1540
+ // TCP-S4: Log tunnel active
1541
+ logger.info("tunnel.active", {
1542
+ target: `tcp://127.0.0.1:${localPort}`,
1543
+ relayId: assignment.relayId,
1544
+ leaseMs: assignment.leaseMs
1545
+ });
1546
+
1547
+ // Tunnel live message
1548
+ process.stdout.write(`🔌 TCP tunnel active (ready for connections)\n`);
1549
+ process.stdout.write(` Target: 127.0.0.1:${localPort}\n`);
1550
+
1551
+ // QPA-CLI-12: Lease and relay info only shown with LOG_LEVEL=info or higher
1552
+ const logLevel = (process.env.ASYX_LOG_LEVEL || process.env.LOG_LEVEL || 'warn').toLowerCase();
1553
+ if (logLevel === 'info' || logLevel === 'debug') {
1554
+ process.stdout.write(` Relay: ${assignment.relayId}\n`);
1555
+ const leaseMinutes = Math.floor(assignment.leaseMs / 60000);
1556
+ process.stdout.write(` Lease window: ${leaseMinutes} minutes\n`);
1557
+ }
1558
+
1559
+ process.stdout.write(` Press Ctrl+C to stop\n`);
1560
+
1561
+ // CLI-IMG-WSReconnect: Set up graceful shutdown
1562
+ let shuttingDown = false;
1563
+ const onSig = async (sig) => {
1564
+ if (shuttingDown) return;
1565
+ shuttingDown = true;
1566
+ logger.info("cli.signal.shutdown", { sig });
1567
+ process.stdout.write(`\nsignal ${sig} — shutting down…\n`);
1568
+
1569
+ const killer = setTimeout(() => {
1570
+ logger.error("tunnel.close.timeout", {});
1571
+ process.stderr.write("tunnel.close() timed out; forcing exit\n");
1572
+ process.exit(0);
1573
+ }, 3000);
1574
+
1575
+ try {
1576
+ // TCP-S4: Close tunnel and all active streams
1577
+ tunnel.close();
1578
+ await mqttClient.disconnect();
1579
+ } catch (e) {
1580
+ logger.debug('tunnel.shutdown.error', { error: e.message });
1581
+ }
1582
+
1583
+ clearTimeout(killer);
1584
+ process.exit(0);
1585
+ };
1586
+
1587
+ process.once("SIGINT", onSig);
1588
+ process.once("SIGTERM", onSig);
1589
+
1590
+ // Keep process alive until SIGINT/SIGTERM
1591
+ await new Promise(() => {});
1592
+
1593
+ } catch (error) {
1594
+ logger.error("tunnel.open.failed", { error: error.message });
1595
+ try {
1596
+ tunnel.close();
1597
+ } catch (e) {
1598
+ logger.debug('tunnel.close.error', { error: e.message });
1599
+ }
1600
+ try {
1601
+ await mqttClient.disconnect();
1602
+ } catch (e) {
1603
+ logger.debug('mqtt.control_plane.disconnect.error', { error: e.message });
1604
+ }
1605
+ process.exit(1);
1606
+ }
1607
+ }
1608
+
1057
1609
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
@@ -849,7 +849,13 @@ export class MqttControlPlaneClient {
849
849
 
850
850
  this.reconnectTimer = setTimeout(() => {
851
851
  this.reconnectTimer = null;
852
- void this.connectWithNewClient();
852
+ // Swallow reconnect promise rejections (non-initial reconnects are fire-and-forget)
853
+ void this.connectWithNewClient().catch((err) => {
854
+ this.logger?.debug('mqtt.control_plane.reconnect.attempt_failed', {
855
+ error: err?.message || String(err),
856
+ code: err?.code
857
+ });
858
+ });
853
859
  }, delay);
854
860
  // Don't keep process alive for reconnect timer
855
861
  if (this.reconnectTimer) {
@@ -1142,4 +1148,3 @@ export class MqttControlPlaneClient {
1142
1148
  void this.disconnect();
1143
1149
  }
1144
1150
  }
1145
-