asyx 0.5.5 → 0.5.7

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,10 @@ 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
+
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`.
174
+
171
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.
172
176
 
173
177
  **Tunnel-only CLI (0.5.0)** — npm ships tunnel commands only: `setup`, `mqtt`, and `tunnel`. Focused on secure localhost exposure (HTTP, TCP, UDP). Docs at https://www.asyx.ai/docs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asyx",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "Asyx tunnel CLI — secure localhost exposure (HTTP, TCP, UDP)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -637,14 +637,11 @@ async function httpTunnel(localPort, secGroupSlug) {
637
637
 
638
638
  // Unregister old instance and register new one
639
639
  const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
640
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
640
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
641
641
 
642
642
  // Get old instance context to preserve metadata
643
643
  const oldContext = getInstance(oldInstanceId);
644
644
  if (oldContext) {
645
- // Get assignment from old instance to migrate it
646
- const oldAssignment = getAssignmentFn(oldInstanceId);
647
-
648
645
  // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
649
646
  const preservedRequestId = oldContext.expectedRequestId;
650
647
 
@@ -671,14 +668,19 @@ async function httpTunnel(localPort, secGroupSlug) {
671
668
  // Now unregister old instance (this will clean up old expectedRequestId mapping)
672
669
  unregisterInstance(oldInstanceId);
673
670
 
674
- // Migrate assignment to new instanceId (updates leaseToInstance mapping)
675
- if (oldAssignment) {
676
- setAssignmentFn(newClientId, oldAssignment);
671
+ // Move the assignment onto the new id and drop the old key.
672
+ const migration = migrateInstanceAssignment({
673
+ oldId: oldInstanceId,
674
+ newId: newClientId,
675
+ tunnel: tunnelInstanceRef.tunnel,
676
+ });
677
+ if (migration.moved) {
677
678
  logger.debug("cli.instance.assignment_migrated", {
678
679
  oldInstanceId,
679
680
  newInstanceId: newClientId,
680
- leaseId: oldAssignment.leaseId,
681
- tunnelType: 'http'
681
+ leaseId: migration.leaseId,
682
+ tunnelType: 'http',
683
+ assignmentCount: migration.size,
682
684
  });
683
685
  }
684
686
 
@@ -738,7 +740,7 @@ async function httpTunnel(localPort, secGroupSlug) {
738
740
  // TPB-12: Get instanceId from mqttClient (captured in closure)
739
741
  const refreshInstanceId = mqttClient.getClientId();
740
742
 
741
- const { getAssignment } = await import('../state/assignment.js');
743
+ const { getAssignment, readRefreshAssignment } = await import('../state/assignment.js');
742
744
  const { getFpHash } = await import('../lib/fingerprint.js');
743
745
 
744
746
  // TPB-12: Get assignment for this specific instance
@@ -1028,25 +1030,10 @@ async function httpTunnel(localPort, secGroupSlug) {
1028
1030
  }
1029
1031
  }
1030
1032
 
1031
- // Get new assignment
1032
- const newAssignment = getAssignment();
1033
- if (!newAssignment) {
1034
- throw new Error("No new assignment after refresh");
1035
- }
1036
-
1037
- // Extract expiration from new JWT
1033
+ // Get new assignment for this client id. An unkeyed read is null once
1034
+ // rotation has left more than one map entry.
1035
+ const { assignment: newAssignment, expMs } = readRefreshAssignment(refreshInstanceId);
1038
1036
  const newJwt = newAssignment.jwt;
1039
- const parts = newJwt.split('.');
1040
- if (parts.length !== 3) {
1041
- throw new Error("Invalid JWT format in new assignment");
1042
- }
1043
-
1044
- const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
1045
- const expMs = payload.exp ? payload.exp * 1000 : null;
1046
-
1047
- if (!expMs) {
1048
- throw new Error("No expiration in new JWT");
1049
- }
1050
1037
 
1051
1038
  // QPA-CLI-05: Notify HttpTunnel that new JWT is available
1052
1039
  // HttpTunnel will handle WebSocket update (in-band reauth or reconnect)
@@ -1584,14 +1571,11 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
1584
1571
 
1585
1572
  // Unregister old instance and register new one
1586
1573
  const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
1587
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
1574
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
1588
1575
 
1589
1576
  // Get old instance context to preserve metadata
1590
1577
  const oldContext = getInstance(oldInstanceId);
1591
1578
  if (oldContext) {
1592
- // Get assignment from old instance to migrate it
1593
- const oldAssignment = getAssignmentFn(oldInstanceId);
1594
-
1595
1579
  // Preserve expectedRequestId before unregistering (for in-flight refresh/reconnect)
1596
1580
  const preservedRequestId = oldContext.expectedRequestId;
1597
1581
 
@@ -1618,14 +1602,17 @@ async function tcpTunnel(localPort, serviceName, kind = null, requestedExternalP
1618
1602
  // Now unregister old instance (this will clean up old expectedRequestId mapping)
1619
1603
  unregisterInstance(oldInstanceId);
1620
1604
 
1621
- // Migrate assignment to new instanceId (updates leaseToInstance mapping)
1622
- if (oldAssignment) {
1623
- setAssignmentFn(newClientId, oldAssignment);
1605
+ const migration = migrateInstanceAssignment({
1606
+ oldId: oldInstanceId,
1607
+ newId: newClientId,
1608
+ });
1609
+ if (migration.moved) {
1624
1610
  logger.debug("cli.instance.assignment_migrated", {
1625
1611
  oldInstanceId,
1626
1612
  newInstanceId: newClientId,
1627
- leaseId: oldAssignment.leaseId,
1628
- tunnelType: 'tcp'
1613
+ leaseId: migration.leaseId,
1614
+ tunnelType: 'tcp',
1615
+ assignmentCount: migration.size,
1629
1616
  });
1630
1617
  }
1631
1618
 
@@ -2445,11 +2432,10 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
2445
2432
 
2446
2433
  // Unregister old instance and register new one (similar to TCP/HTTP)
2447
2434
  const { unregisterInstance, registerInstance, getInstance } = await import("../state/instance-registry.js");
2448
- const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn } = await import("../state/assignment.js");
2435
+ const { setAssignment: setAssignmentFn, getAssignment: getAssignmentFn, migrateInstanceAssignment } = await import("../state/assignment.js");
2449
2436
 
2450
2437
  const oldContext = getInstance(oldInstanceId);
2451
2438
  if (oldContext) {
2452
- const oldAssignment = getAssignmentFn(oldInstanceId);
2453
2439
  const preservedRequestId = oldContext.expectedRequestId;
2454
2440
 
2455
2441
  registerInstance(newClientId, {
@@ -2466,8 +2452,18 @@ async function udpTunnel(targetPort, requestedExternalPort = null, targetHost =
2466
2452
 
2467
2453
  unregisterInstance(oldInstanceId);
2468
2454
 
2469
- if (oldAssignment) {
2470
- setAssignmentFn(newClientId, oldAssignment);
2455
+ const migration = migrateInstanceAssignment({
2456
+ oldId: oldInstanceId,
2457
+ newId: newClientId,
2458
+ });
2459
+ if (migration.moved) {
2460
+ logger.debug("cli.instance.assignment_migrated", {
2461
+ oldInstanceId,
2462
+ newInstanceId: newClientId,
2463
+ leaseId: migration.leaseId,
2464
+ tunnelType: 'udp',
2465
+ assignmentCount: migration.size,
2466
+ });
2471
2467
  }
2472
2468
  }
2473
2469
 
@@ -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
@@ -268,6 +269,9 @@ export class MqttControlPlaneClient {
268
269
  handler({ topic, payload: payloadBytes });
269
270
  };
270
271
 
272
+ if (this.client && this._pendingMessageHandler) {
273
+ this.client.removeListener('message', this._pendingMessageHandler);
274
+ }
271
275
  this._pendingMessageHandler = wrappedHandler;
272
276
  if (this.client && this.mqttOnline) {
273
277
  this.client.on('message', wrappedHandler);
@@ -361,6 +365,7 @@ export class MqttControlPlaneClient {
361
365
  this.clearWatchdog();
362
366
  this.mqttOnline = true;
363
367
  this.hardErrorCount = 0;
368
+ this.transientErrorCount = 0;
364
369
  this.reconnectAttempts = 0; // Reset on successful connect
365
370
  this.connectStartTime = null;
366
371
 
@@ -675,6 +680,12 @@ export class MqttControlPlaneClient {
675
680
  const name = (err && (err.name)) || "";
676
681
  const msg = (err && (err.message)) || "";
677
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
+
678
689
  // If close/end fires before connect, it's likely a hard fault (auth/policy issue)
679
690
  if (beforeConnect) {
680
691
  return "hard";
@@ -736,6 +747,20 @@ export class MqttControlPlaneClient {
736
747
  const reason = err?.message || err?.code || kind;
737
748
  this.onOffline?.(reason);
738
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
+
739
764
  if (kind === "hard") {
740
765
  this.hardErrorCount++;
741
766
  this.reconnectAttempts++;
@@ -834,26 +859,37 @@ export class MqttControlPlaneClient {
834
859
  /**
835
860
  * Schedule reconnect with jittered backoff.
836
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
837
863
  */
838
- scheduleReconnect(immediate) {
864
+ scheduleReconnect(immediate, options = {}) {
839
865
  if (this.shuttingDown) return;
840
866
  if (this.reconnectTimer) return; // already scheduled
841
867
 
842
- const base = immediate ? 0 : 200;
843
- const expFactor = Math.min(this.hardErrorCount, 5);
844
- const delayNoJitter =
845
- this.hardErrorCount === 0 ? base : base * Math.pow(2, expFactor);
846
- const jitter = Math.random() * 200; // 0-200ms jitter
847
- const delay =
848
- this.hardErrorCount === 0
849
- ? base
850
- : 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
+ }
851
886
 
852
887
  // QPA-CLI-10: Telemetry logs default to debug for quiet mode
853
888
  this.logger?.debug('mqtt.control_plane.reconnect.scheduled', {
854
- immediate,
889
+ immediate: transient ? false : immediate,
855
890
  delay,
856
891
  hardErrorCount: this.hardErrorCount,
892
+ transientErrorCount: this.transientErrorCount,
857
893
  attempt: this.hardErrorCount + 1
858
894
  });
859
895
 
@@ -150,6 +150,70 @@ export function clearAssignment(instanceId) {
150
150
  }
151
151
  }
152
152
 
153
+ /**
154
+ * Drop one instance key without touching a lease mapping that already points elsewhere.
155
+ * Does not reject assignment waiters.
156
+ * @param {string} instanceId
157
+ */
158
+ export function forgetInstanceAssignment(instanceId) {
159
+ if (!instanceId) return;
160
+ const assignment = assignmentByInstance.get(instanceId);
161
+ if (!assignment) return;
162
+ if (assignment.leaseId && leaseToInstance.get(assignment.leaseId) === instanceId) {
163
+ leaseToInstance.delete(assignment.leaseId);
164
+ }
165
+ assignmentByInstance.delete(instanceId);
166
+ }
167
+
168
+ /**
169
+ * Copy an assignment onto a new instance id and drop the old key.
170
+ * When a tunnel object is passed, its instanceId moves with the assignment.
171
+ * @param {{ oldId: string, newId: string, tunnel?: { instanceId?: string } | null }} opts
172
+ * @returns {{ moved: boolean, leaseId: string | null, size: number }}
173
+ */
174
+ export function migrateInstanceAssignment({ oldId, newId, tunnel } = {}) {
175
+ const oldAssignment = oldId ? getAssignment(oldId) : null;
176
+ const moved = !!(oldAssignment && newId && oldId !== newId);
177
+ if (moved) {
178
+ setAssignment(newId, oldAssignment);
179
+ forgetInstanceAssignment(oldId);
180
+ }
181
+ if (tunnel) {
182
+ tunnel.instanceId = newId;
183
+ }
184
+ return {
185
+ moved,
186
+ leaseId: oldAssignment?.leaseId || null,
187
+ size: assignmentByInstance.size,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Assignment stored for this instance after a refresh ack.
193
+ * Throws when the keyed entry is missing or the JWT has no exp.
194
+ * @param {string} instanceId
195
+ * @returns {{ assignment: Object, expMs: number }}
196
+ */
197
+ export function readRefreshAssignment(instanceId) {
198
+ const newAssignment = getAssignment(instanceId);
199
+ if (!newAssignment) {
200
+ throw new Error("No new assignment after refresh");
201
+ }
202
+
203
+ const parts = typeof newAssignment.jwt === 'string' ? newAssignment.jwt.split('.') : [];
204
+ if (parts.length !== 3) {
205
+ throw new Error("Invalid JWT format in new assignment");
206
+ }
207
+
208
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
209
+ const expMs = payload.exp ? payload.exp * 1000 : null;
210
+ if (!expMs) {
211
+ throw new Error("No expiration in new JWT");
212
+ }
213
+
214
+ return { assignment: newAssignment, expMs };
215
+ }
216
+
153
217
  /**
154
218
  * Check if an assignment exists for a specific tunnel instance
155
219
  * TPB-12: Per-instance assignment check
@@ -905,7 +905,7 @@ export class HttpTunnel {
905
905
 
906
906
  // Record refresh timestamp and delta metrics
907
907
  const { recordRefresh } = await import('../state/assignment.js');
908
- const deltaMs = recordRefresh(Date.now());
908
+ const deltaMs = recordRefresh(this.instanceId, Date.now());
909
909
  this.log.info('jwt.refresh.delta', { deltaMs });
910
910
  this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
911
911
  // QPA-CLI-01: Reset retry state on success
@@ -939,7 +939,7 @@ export class HttpTunnel {
939
939
 
940
940
  // Record refresh timestamp and delta metrics
941
941
  const { recordRefresh } = await import('../state/assignment.js');
942
- const deltaMs = recordRefresh(Date.now());
942
+ const deltaMs = recordRefresh(this.instanceId, Date.now());
943
943
  this.log.info('jwt.refresh.delta', { deltaMs });
944
944
  this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
945
945
  // QPA-CLI-01: Reset retry state on success
@@ -1127,7 +1127,7 @@ export class HttpTunnel {
1127
1127
 
1128
1128
  // Record refresh delta for fallback path
1129
1129
  const { recordRefresh } = await import('../state/assignment.js');
1130
- const deltaMs = recordRefresh(Date.now());
1130
+ const deltaMs = recordRefresh(this.instanceId, Date.now());
1131
1131
  this.log.info('jwt.refresh.delta', { deltaMs });
1132
1132
  this.log.info('jwt.refresh.fallback.success', {
1133
1133
  leaseId: newAssignment.leaseId || leaseId,