asyx 0.5.6 → 0.5.8

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
@@ -168,6 +168,8 @@ asyx tunnel --minecraft [--port <n>] [--name <alias>]
168
168
 
169
169
  ## What's new in 0.5.x
170
170
 
171
+ **DNS outage keeps the tunnel up (0.5.7)** — if the IoT hostname fails to resolve, the CLI waits and retries instead of exiting after 20 immediate attempts.
172
+
171
173
  **Refresh after a control-plane reconnect (0.5.6)** — if the MQTT control connection drops and the client id rotates, the next lease refresh keeps the tunnel up instead of exiting with `jwt_refresh_failed`.
172
174
 
173
175
  **Reconnect after a DNS blip (0.5.5)** — if the network drops before the MQTT TLS handshake, the CLI stays up and uses the reconnect it already scheduled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -14,7 +14,7 @@ import mqtt from 'mqtt';
14
14
  import { ulid } from 'ulid';
15
15
 
16
16
  /**
17
- * @typedef {'soft' | 'hard'} MqttFaultKind
17
+ * @typedef {'soft' | 'hard' | 'transient'} MqttFaultKind
18
18
  */
19
19
 
20
20
  /**
@@ -66,6 +66,7 @@ export class MqttControlPlaneClient {
66
66
  this.shuttingDown = false;
67
67
  this.mqttOnline = false;
68
68
  this.hardErrorCount = 0;
69
+ this.transientErrorCount = 0;
69
70
  this.reconnectTimer = null;
70
71
  this.connectStartTime = null;
71
72
  this.reconnectAttempts = 0; // Track total reconnect attempts
@@ -364,6 +365,7 @@ export class MqttControlPlaneClient {
364
365
  this.clearWatchdog();
365
366
  this.mqttOnline = true;
366
367
  this.hardErrorCount = 0;
368
+ this.transientErrorCount = 0;
367
369
  this.reconnectAttempts = 0; // Reset on successful connect
368
370
  this.connectStartTime = null;
369
371
 
@@ -678,6 +680,12 @@ export class MqttControlPlaneClient {
678
680
  const name = (err && (err.name)) || "";
679
681
  const msg = (err && (err.message)) || "";
680
682
 
683
+ // Resolver failures recover, including before the MQTT handshake.
684
+ // The 20-attempt exit is for auth and policy failures that will not.
685
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
686
+ return "transient";
687
+ }
688
+
681
689
  // If close/end fires before connect, it's likely a hard fault (auth/policy issue)
682
690
  if (beforeConnect) {
683
691
  return "hard";
@@ -739,6 +747,20 @@ export class MqttControlPlaneClient {
739
747
  const reason = err?.message || err?.code || kind;
740
748
  this.onOffline?.(reason);
741
749
 
750
+ if (kind === "transient") {
751
+ this.transientErrorCount++;
752
+ this.logger?.debug('mqtt.control_plane.fault.transient', {
753
+ transientErrorCount: this.transientErrorCount,
754
+ reconnectAttempts: this.reconnectAttempts,
755
+ reason,
756
+ clientId: this.currentClientId,
757
+ baseClientId: this.baseClientId
758
+ });
759
+ this.forceCloseClient();
760
+ this.scheduleReconnect(/* immediate */ false, { transient: true });
761
+ return;
762
+ }
763
+
742
764
  if (kind === "hard") {
743
765
  this.hardErrorCount++;
744
766
  this.reconnectAttempts++;
@@ -837,26 +859,37 @@ export class MqttControlPlaneClient {
837
859
  /**
838
860
  * Schedule reconnect with jittered backoff.
839
861
  * @param {boolean} immediate - true for hard faults (ECONNRESET, etc.), false for soft
862
+ * @param {{ transient?: boolean }} [options] - transient resolver failures use a growing delay
840
863
  */
841
- scheduleReconnect(immediate) {
864
+ scheduleReconnect(immediate, options = {}) {
842
865
  if (this.shuttingDown) return;
843
866
  if (this.reconnectTimer) return; // already scheduled
844
867
 
845
- const base = immediate ? 0 : 200;
846
- const expFactor = Math.min(this.hardErrorCount, 5);
847
- const delayNoJitter =
848
- this.hardErrorCount === 0 ? base : base * Math.pow(2, expFactor);
849
- const jitter = Math.random() * 200; // 0-200ms jitter
850
- const delay =
851
- this.hardErrorCount === 0
852
- ? base
853
- : Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
868
+ const transient = options.transient === true;
869
+ let delay;
870
+ if (transient) {
871
+ const expFactor = Math.min(Math.max(this.transientErrorCount - 1, 0), 4);
872
+ const delayNoJitter = 1000 * Math.pow(2, expFactor);
873
+ const jitter = Math.random() * 200; // 0-200ms jitter
874
+ delay = Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
875
+ } else {
876
+ const base = immediate ? 0 : 200;
877
+ const expFactor = Math.min(this.hardErrorCount, 5);
878
+ const delayNoJitter =
879
+ this.hardErrorCount === 0 ? base : base * Math.pow(2, expFactor);
880
+ const jitter = Math.random() * 200; // 0-200ms jitter
881
+ delay =
882
+ this.hardErrorCount === 0
883
+ ? base
884
+ : Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
885
+ }
854
886
 
855
887
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
856
888
  this.logger?.debug('mqtt.control_plane.reconnect.scheduled', {
857
- immediate,
889
+ immediate: transient ? false : immediate,
858
890
  delay,
859
891
  hardErrorCount: this.hardErrorCount,
892
+ transientErrorCount: this.transientErrorCount,
860
893
  attempt: this.hardErrorCount + 1
861
894
  });
862
895
 
@@ -15,6 +15,58 @@ import {
15
15
 
16
16
  const V2_THRESHOLD_BYTES = 8 * 1024 * 1024; // 8 MiB threshold for v2 selection
17
17
 
18
+ const TUNNEL_DROP_HEADERS = new Set([
19
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
20
+ 'te', 'trailers', 'transfer-encoding', 'upgrade',
21
+ 'sec-websocket-key', 'sec-websocket-version',
22
+ 'forwarded', 'x-forwarded-host'
23
+ ]);
24
+
25
+ function headersToObject(headers) {
26
+ const out = {};
27
+ if (Array.isArray(headers)) {
28
+ for (const pair of headers) {
29
+ if (!Array.isArray(pair) || pair.length < 2) continue;
30
+ const name = String(pair[0]).toLowerCase();
31
+ const value = pair[1];
32
+ out[name] = Array.isArray(value) ? value.map((part) => String(part)).join(', ') : (value == null ? '' : String(value));
33
+ }
34
+ return out;
35
+ }
36
+ if (headers && typeof headers === 'object') {
37
+ for (const [name, value] of Object.entries(headers)) {
38
+ out[String(name).toLowerCase()] = value;
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+
44
+ function sanitizeLocalRequest(url, headers, bodyBuffer, localPort) {
45
+ if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//') || /[\r\n]/.test(url)) {
46
+ return { error: 400 };
47
+ }
48
+ const source = headersToObject(headers);
49
+ const out = {};
50
+ for (const [name, value] of Object.entries(source)) {
51
+ if (TUNNEL_DROP_HEADERS.has(name)) continue;
52
+ if (/[\r\n]/.test(name)) return { error: 400 };
53
+ const parts = Array.isArray(value) ? value : [value];
54
+ if (parts.some((part) => typeof part === 'string' && /[\r\n]/.test(part))) {
55
+ return { error: 400 };
56
+ }
57
+ out[name] = value;
58
+ }
59
+ const host = out.host == null ? '' : String(out.host);
60
+ if (!host || /[\r\n]/.test(host)) {
61
+ out.host = `localhost:${localPort}`;
62
+ }
63
+ delete out['transfer-encoding'];
64
+ if (bodyBuffer && bodyBuffer.length > 0) {
65
+ out['content-length'] = String(bodyBuffer.length);
66
+ }
67
+ return { path: url, headers: out };
68
+ }
69
+
18
70
  export class HttpTunnel {
19
71
  constructor({
20
72
  relayUrl,
@@ -1168,6 +1220,19 @@ export class HttpTunnel {
1168
1220
  }
1169
1221
  }
1170
1222
 
1223
+ sendTunnelError(requestId, status) {
1224
+ const responseData = {
1225
+ t: 'http_response',
1226
+ rid: requestId,
1227
+ s: status,
1228
+ h: [['content-type', 'text/plain']],
1229
+ b: ''
1230
+ };
1231
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
1232
+ this.ws.send(JSON.stringify(responseData));
1233
+ }
1234
+ }
1235
+
1171
1236
  handleHttpRequest(msg) {
1172
1237
  // CRT-Relay-E: Update activity on HTTP request
1173
1238
  this.lastActivityMs = Date.now();
@@ -1178,9 +1243,14 @@ export class HttpTunnel {
1178
1243
  // Extract fields from compact format
1179
1244
  const requestId = rid;
1180
1245
  const method = m;
1181
- const url = u;
1182
- const headers = h;
1183
1246
  const bodyBuffer = b ? Buffer.from(b, 'base64') : null;
1247
+ const sanitized = sanitizeLocalRequest(u, h, bodyBuffer, this.localPort);
1248
+ if (sanitized.error) {
1249
+ this.sendTunnelError(requestId, sanitized.error);
1250
+ return;
1251
+ }
1252
+ const url = sanitized.path;
1253
+ const headers = sanitized.headers;
1184
1254
 
1185
1255
  // Forward to local HTTP server
1186
1256
  const options = {
@@ -1191,7 +1261,9 @@ export class HttpTunnel {
1191
1261
  headers: headers
1192
1262
  };
1193
1263
 
1194
- const proxyReq = http.request(options, (proxyRes) => {
1264
+ let proxyReq;
1265
+ try {
1266
+ proxyReq = http.request(options, (proxyRes) => {
1195
1267
  // S-1: Determine response mode at http_response_start
1196
1268
  const contentLength = proxyRes.headers['content-length']
1197
1269
  ? parseInt(proxyRes.headers['content-length'], 10)
@@ -1225,15 +1297,23 @@ export class HttpTunnel {
1225
1297
  proxyReq.write(bodyBuffer);
1226
1298
  }
1227
1299
  proxyReq.end();
1300
+ } catch (err) {
1301
+ if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1302
+ this.sendTunnelError(requestId, 400);
1303
+ return;
1304
+ }
1305
+ this.log.error({ err, requestId }, 'Proxy request error');
1306
+ this.sendTunnelError(requestId, 502);
1307
+ }
1228
1308
  }
1229
1309
 
1230
1310
  handleHttpRequestBuffer(buffer) {
1231
1311
  // Handle raw HTTP request buffer from relay
1232
1312
  const httpString = buffer.toString();
1233
1313
  const lines = httpString.split('\r\n');
1234
- const [method, url, version] = lines[0].split(' ');
1314
+ const [method, rawUrl] = lines[0].split(' ');
1235
1315
 
1236
- const headers = {};
1316
+ const parsedHeaders = {};
1237
1317
  let bodyStart = 0;
1238
1318
  for (let i = 1; i < lines.length; i++) {
1239
1319
  if (lines[i] === '') {
@@ -1241,21 +1321,31 @@ export class HttpTunnel {
1241
1321
  break;
1242
1322
  }
1243
1323
  const [key, value] = lines[i].split(': ');
1244
- headers[key.toLowerCase()] = value;
1324
+ if (key) {
1325
+ parsedHeaders[key.toLowerCase()] = value;
1326
+ }
1245
1327
  }
1246
1328
 
1247
1329
  const body = lines.slice(bodyStart).join('\r\n');
1330
+ const bodyBuffer = Buffer.from(body);
1331
+ const sanitized = sanitizeLocalRequest(rawUrl, parsedHeaders, bodyBuffer, this.localPort);
1332
+ if (sanitized.error) {
1333
+ this.log.warn({ method }, 'Rejected raw tunnel request');
1334
+ return;
1335
+ }
1248
1336
 
1249
1337
  // Forward to local HTTP server
1250
1338
  const options = {
1251
1339
  hostname: 'localhost',
1252
1340
  port: this.localPort,
1253
- path: url,
1341
+ path: sanitized.path,
1254
1342
  method: method,
1255
- headers: headers
1343
+ headers: sanitized.headers
1256
1344
  };
1257
1345
 
1258
- const proxyReq = http.request(options, (proxyRes) => {
1346
+ let proxyReq;
1347
+ try {
1348
+ proxyReq = http.request(options, (proxyRes) => {
1259
1349
  // Send response back to relay as binary
1260
1350
  let responseBuffer = Buffer.from(`HTTP/1.1 ${proxyRes.statusCode} ${proxyRes.statusMessage}\r\n`);
1261
1351
 
@@ -1289,6 +1379,13 @@ export class HttpTunnel {
1289
1379
  proxyReq.write(body);
1290
1380
  }
1291
1381
  proxyReq.end();
1382
+ } catch (err) {
1383
+ if (err && (err.code === 'ERR_INVALID_CHAR' || err.code === 'ERR_INVALID_HTTP_TOKEN')) {
1384
+ this.log.warn({ err }, 'Rejected raw tunnel request header');
1385
+ return;
1386
+ }
1387
+ throw err;
1388
+ }
1292
1389
  }
1293
1390
 
1294
1391
  // S-0: Send hello frame for HTTP-WS v2 negotiation
@@ -115,10 +115,8 @@ export class TcpTunnel {
115
115
  reject(new Error('Missing leaseId for TCP tunnel'));
116
116
  return;
117
117
  }
118
- // Add token query parameter (required by TCP relay)
119
- if (this.jwt && !urlObj.searchParams.has('token')) {
120
- urlObj.searchParams.set('token', this.jwt);
121
- } else if (!this.jwt) {
118
+ urlObj.searchParams.delete('token');
119
+ if (!this.jwt) {
122
120
  this.log.error('tcp.ws.missing_jwt', { relayUrl: this.relayUrl, hasLeaseId: !!this.leaseId });
123
121
  reject(new Error('Missing JWT for TCP tunnel'));
124
122
  return;
@@ -7,6 +7,17 @@ import { FrameType, FRAME_HEADER_SIZE, encodeFrame, decodeFrame, validateFrame,
7
7
  import { verifyAssignmentJWT, isJWKSAvailable } from '../lib/jwt-verifier.js';
8
8
 
9
9
  export class UdpTunnel {
10
+ static selectDial(targetHost) {
11
+ const host = String(targetHost || '127.0.0.1').trim().toLowerCase();
12
+ if (host === 'localhost' || host === '127.0.0.1' || host.startsWith('127.')) {
13
+ return { family: 'udp4', address: '127.0.0.1' };
14
+ }
15
+ if (host === '::1') {
16
+ return { family: 'udp6', address: '::1' };
17
+ }
18
+ return null;
19
+ }
20
+
10
21
  constructor({
11
22
  relayUrl,
12
23
  jwt,
@@ -34,6 +45,9 @@ export class UdpTunnel {
34
45
  // UDP-S13: Use targetHost/targetPort (fallback to localPort for backward compatibility)
35
46
  this.targetHost = targetHost || '127.0.0.1';
36
47
  this.targetPort = targetPort || localPort;
48
+ const dial = UdpTunnel.selectDial(this.targetHost);
49
+ this.dialFamily = dial?.family || null;
50
+ this.dialAddress = dial?.address || null;
37
51
  this.leaseId = leaseId;
38
52
  this.relayId = relayId; // AC5.1: Store relayId for JWT validation
39
53
  this.log = log;
@@ -111,8 +125,12 @@ export class UdpTunnel {
111
125
  if (this.leaseId && !urlObj.searchParams.has('leaseId')) {
112
126
  urlObj.searchParams.set('leaseId', this.leaseId);
113
127
  }
114
- if (this.jwt && !urlObj.searchParams.has('token')) {
115
- urlObj.searchParams.set('token', this.jwt);
128
+ urlObj.searchParams.delete('token');
129
+ if (!this.jwt) {
130
+ const error = new Error('UDP_RELAY_UNAVAILABLE: Missing JWT for UDP tunnel');
131
+ error.code = 'UDP_RELAY_UNAVAILABLE';
132
+ reject(error);
133
+ return;
116
134
  }
117
135
  wsUrl = urlObj.toString();
118
136
  } catch (urlError) {
@@ -188,7 +206,7 @@ export class UdpTunnel {
188
206
  this.ws = new WebSocket(wsUrl, wsOptions);
189
207
 
190
208
  this.ws.on('open', () => {
191
- this.log.info({ relayUrl: wsUrl, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
209
+ this.log.info({ leaseId: this.leaseId, targetHost: this.targetHost, targetPort: this.targetPort }, 'udp.tunnel.ws.open');
192
210
 
193
211
  // UDP-S1: Start PING keepalive timer
194
212
  this.startPingKeepalive();
@@ -367,8 +385,16 @@ export class UdpTunnel {
367
385
  let socket = flowState?.socket;
368
386
 
369
387
  if (!socket) {
388
+ if (!this.dialAddress || !this.dialFamily) {
389
+ this.log.warn({
390
+ flowId,
391
+ targetHost: this.targetHost,
392
+ note: 'Refusing non-loopback UDP dial'
393
+ }, 'udp.flow.dial.refused');
394
+ return;
395
+ }
370
396
  // Create new per-flow socket for this flowId
371
- socket = dgram.createSocket('udp4');
397
+ socket = dgram.createSocket(this.dialFamily);
372
398
 
373
399
  // UDP-S14: Store reverse mapping (socket -> flowId) for message handlers
374
400
  this.socketToFlowId.set(socket, flowId);
@@ -377,37 +403,27 @@ export class UdpTunnel {
377
403
  flowState = { socket, lastSeen: now, connected: false, pendingPayload: frame.payload };
378
404
  this.flowMap.set(flowId, flowState);
379
405
 
380
- // UDP-S13: Bind to OS-assigned port (ephemeral)
381
- socket.bind(0, '0.0.0.0', () => {
406
+ // Bind the ephemeral port on loopback, then connect, then listen.
407
+ socket.bind(0, this.dialAddress, () => {
382
408
  const address = socket.address();
383
409
  this.log.debug({
384
410
  flowId,
385
411
  localAddress: address.address,
386
412
  localPort: address.port,
387
- targetHost: this.targetHost,
413
+ targetHost: this.dialAddress,
388
414
  targetPort: this.targetPort
389
415
  }, 'udp.flow.socket.bound');
390
416
 
391
- // UDP-S13: Connect to targetHost:targetPort (allows send() without address/port)
392
- socket.connect(this.targetPort, this.targetHost, () => {
417
+ socket.connect(this.targetPort, this.dialAddress, () => {
393
418
  this.log.debug({
394
419
  flowId,
395
- targetHost: this.targetHost,
420
+ targetHost: this.dialAddress,
396
421
  targetPort: this.targetPort
397
422
  }, 'udp.flow.socket.connected');
398
423
 
399
- // UDP-S14: Mark socket as connected
400
424
  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) => {
425
+
426
+ socket.on('message', (msg, rinfo) => {
411
427
  // We know the flowId from the socket itself
412
428
  const socketFlowId = this.socketToFlowId.get(socket);
413
429
  if (socketFlowId === flowId) {
@@ -432,12 +448,18 @@ export class UdpTunnel {
432
448
  if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
433
449
  this.log.warn({
434
450
  flowId,
435
- targetHost: this.targetHost,
451
+ targetHost: this.dialAddress,
436
452
  targetPort: this.targetPort,
437
453
  note: 'Target app may not be listening on this port'
438
454
  }, 'udp.target.unreachable');
439
455
  }
440
456
  });
457
+
458
+ if (flowState.pendingPayload) {
459
+ this.sendDatagramToApp(socket, flowId, flowState.pendingPayload);
460
+ flowState.pendingPayload = null;
461
+ }
462
+ });
441
463
  });
442
464
  } else {
443
465
  // Update lastSeen for existing flow