asyx 0.10.1 → 0.11.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.
Files changed (93) hide show
  1. package/AGENTS.md +42 -0
  2. package/bin/asyx.js +1 -1
  3. package/package.json +3 -2
  4. package/src/commands/account.js +80 -71
  5. package/src/commands/app.js +317 -151
  6. package/src/commands/in-use-messages.js +47 -48
  7. package/src/commands/mqtt-broker.js +36 -49
  8. package/src/commands/mqtt.js +111 -149
  9. package/src/commands/name.js +24 -22
  10. package/src/commands/reject-messages.js +123 -123
  11. package/src/commands/setup.js +107 -131
  12. package/src/commands/sts.js +45 -61
  13. package/src/commands/tunnel.js +853 -932
  14. package/src/commands/validate-target-host.js +36 -59
  15. package/src/lib/aws-iot-config.js +26 -24
  16. package/src/lib/certs.js +15 -18
  17. package/src/lib/csr.js +107 -182
  18. package/src/lib/device.js +26 -37
  19. package/src/lib/ids.js +1 -2
  20. package/src/lib/naming.js +74 -68
  21. package/src/lib/pairing.js +10 -11
  22. package/src/lib/shared-transport.js +5 -9
  23. package/src/main.js +63 -53
  24. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +25 -287
  25. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +0 -72
  26. package/vendor/tunnel-core/dist/control-plane/session.js +0 -20
  27. package/vendor/tunnel-core/dist/errors.js +0 -19
  28. package/vendor/tunnel-core/dist/flows/account.js +1 -6
  29. package/vendor/tunnel-core/dist/flows/goodbye.js +0 -4
  30. package/vendor/tunnel-core/dist/flows/http.js +24 -112
  31. package/vendor/tunnel-core/dist/flows/identity.js +11 -10
  32. package/vendor/tunnel-core/dist/flows/in-use.js +0 -6
  33. package/vendor/tunnel-core/dist/flows/reopen.js +0 -4
  34. package/vendor/tunnel-core/dist/flows/tcp.js +18 -84
  35. package/vendor/tunnel-core/dist/flows/udp.js +15 -52
  36. package/vendor/tunnel-core/dist/lib/fingerprint.js +38 -42
  37. package/vendor/tunnel-core/dist/lib/jwt-verifier.js +14 -67
  38. package/vendor/tunnel-core/dist/lib/logger.js +1 -9
  39. package/vendor/tunnel-core/dist/lib/refresh-helpers.js +1 -22
  40. package/vendor/tunnel-core/dist/lifecycle.js +1 -8
  41. package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +1 -53
  42. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +10 -64
  43. package/vendor/tunnel-core/dist/mqtt/events/index.js +3 -36
  44. package/vendor/tunnel-core/dist/mqtt/events/schemas.js +0 -1
  45. package/vendor/tunnel-core/dist/mqtt/ingress.js +0 -60
  46. package/vendor/tunnel-core/dist/state/assignment.js +6 -122
  47. package/vendor/tunnel-core/dist/state/instance-registry.js +0 -63
  48. package/vendor/tunnel-core/dist/tcp-v1/framing.js +2 -64
  49. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +64 -331
  50. package/vendor/tunnel-core/dist/tunnel/httpws-constants.js +5 -14
  51. package/vendor/tunnel-core/dist/tunnel/reconnect.js +10 -50
  52. package/vendor/tunnel-core/dist/tunnel/request-sink.js +0 -16
  53. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +32 -195
  54. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +28 -153
  55. package/vendor/tunnel-core/dist/tunnel/ws-control.js +4 -39
  56. package/vendor/tunnel-core/dist/types.js +0 -2
  57. package/vendor/tunnel-core/dist/udp-v1/framing.js +2 -64
  58. package/vendor/tunnel-core/package.json +0 -25
  59. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +0 -273
  60. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +0 -79
  61. package/vendor/tunnel-core/dist/control-plane/session.d.ts +0 -55
  62. package/vendor/tunnel-core/dist/errors.d.ts +0 -49
  63. package/vendor/tunnel-core/dist/flows/account.d.ts +0 -24
  64. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +0 -10
  65. package/vendor/tunnel-core/dist/flows/http.d.ts +0 -61
  66. package/vendor/tunnel-core/dist/flows/identity.d.ts +0 -23
  67. package/vendor/tunnel-core/dist/flows/in-use.d.ts +0 -27
  68. package/vendor/tunnel-core/dist/flows/reopen.d.ts +0 -9
  69. package/vendor/tunnel-core/dist/flows/tcp.d.ts +0 -85
  70. package/vendor/tunnel-core/dist/flows/udp.d.ts +0 -52
  71. package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +0 -2
  72. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +0 -145
  73. package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +0 -27
  74. package/vendor/tunnel-core/dist/lib/logger.d.ts +0 -9
  75. package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +0 -16
  76. package/vendor/tunnel-core/dist/lifecycle.d.ts +0 -24
  77. package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +0 -56
  78. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +0 -60
  79. package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +0 -1
  80. package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +0 -498
  81. package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +0 -63
  82. package/vendor/tunnel-core/dist/state/assignment.d.ts +0 -136
  83. package/vendor/tunnel-core/dist/state/instance-registry.d.ts +0 -88
  84. package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +0 -43
  85. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +0 -140
  86. package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +0 -13
  87. package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +0 -76
  88. package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +0 -40
  89. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +0 -92
  90. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +0 -93
  91. package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +0 -22
  92. package/vendor/tunnel-core/dist/types.d.ts +0 -24
  93. package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +0 -41
@@ -1,18 +1,6 @@
1
- // Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the TCP tunnel flow, moved from tcpTunnel() and
2
- // connectToRelayTcp() in clients/asyx/src/commands/tunnel.js. Behaviour is unchanged; what the CLI
3
- // printed or exited on is now an event or a typed error, and the CLI maps both to its old wording:
4
- // 'control-connected' / 'control-fatal' (TCP has never reported a lost control-plane connection)
5
- // 'assigned' { tcpAliasFqdn, srvProvisioned, srvFqdn, fqdn, publicPort, aliasRequestedButFailed, portMoved }
6
- // when the coordinator's assignment arrives (the CLI prints where the server is reachable)
7
- // state events: 'opening', 'live', 'renewed', and a final 'closed' { error } when a reply ends
8
- // the tunnel after it opened (SetupRequiredError, RefusedError, InternalError).
9
- // open() rejects with: ConnectionError control_plane_connect_failed | assignment_failed |
10
- // tunnel_connect_failed, or RefusedError tcp_port_out_of_block | tcp_port_already_in_use |
11
- // tcp_port_block_exhausted_for_tenant | tcp_port_capacity_exhausted | tenant_tcp_lease_limit_reached
12
- // (details carry what the CLI prints: requestedPort, blockStart, blockEnd, relayId).
13
1
  import { randomUUID } from 'node:crypto';
14
- import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
15
- import { sayGoodbye } from './goodbye.js'; // Story 3.13
2
+ import { ReopenLimiter, reopenPayload } from './reopen.js';
3
+ import { sayGoodbye } from './goodbye.js';
16
4
  import { LifecycleEmitter } from '../lifecycle.js';
17
5
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
18
6
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -22,9 +10,7 @@ export class TcpTunnelHandle extends LifecycleEmitter {
22
10
  opts;
23
11
  tunnel = null;
24
12
  mqttClient = null;
25
- /** Story 1.9: one id for this tunnel across its opens. */
26
13
  tunnelSession = randomUUID();
27
- /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
28
14
  reopenLimiter = new ReopenLimiter();
29
15
  core = null;
30
16
  assignment = null;
@@ -32,11 +18,9 @@ export class TcpTunnelHandle extends LifecycleEmitter {
32
18
  super();
33
19
  this.opts = { serviceName: null, kind: null, requestedExternalPort: null, ...o };
34
20
  }
35
- /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
36
21
  async goodbye(timeoutMs = 2000) {
37
22
  return sayGoodbye(this, timeoutMs);
38
23
  }
39
- /** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
40
24
  async open() {
41
25
  const { credentials, localPort, target, serviceName, kind, requestedExternalPort, logger } = this.opts;
42
26
  this.setState('opening');
@@ -45,11 +29,9 @@ export class TcpTunnelHandle extends LifecycleEmitter {
45
29
  const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
46
30
  const { MessageIngress } = await import('../mqtt/ingress.js');
47
31
  const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
48
- // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
49
32
  const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
50
33
  const baseClientId = credentials.clientId;
51
34
  const instanceIdRef = { instanceId: null };
52
- // TPB-17: coordinator references for the renewal callback
53
35
  let coordinatorCoreRef = null;
54
36
  let coordinatorIngressRef = null;
55
37
  const deviceIdRef = credentials.clientId;
@@ -60,11 +42,9 @@ export class TcpTunnelHandle extends LifecycleEmitter {
60
42
  if (!coordinatorCoreRef || !coordinatorIngressRef) {
61
43
  throw new Error("Coordinator not available for refresh");
62
44
  }
63
- // TPB-12: Get instanceId from mqttClient (captured in closure)
64
45
  const refreshInstanceId = mqttClient.getClientId();
65
46
  const { getAssignment } = await import('../state/assignment.js');
66
47
  const { getFpHash } = await import('../lib/fingerprint.js');
67
- // TPB-12: Get assignment for this specific instance
68
48
  const currentAssignment = getAssignment(refreshInstanceId);
69
49
  if (!currentAssignment) {
70
50
  throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
@@ -73,20 +53,17 @@ export class TcpTunnelHandle extends LifecycleEmitter {
73
53
  if (!leaseId) {
74
54
  throw new Error("No leaseId in current assignment");
75
55
  }
76
- // Build refresh payload
77
- const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
56
+ const refreshRequestId = `refresh-${randomUUID()}`;
78
57
  const fingerprint = await getFpHash(deviceIdRef);
79
- // TPB-17: Include instanceId and proto:"tcp" in refresh payload
80
58
  const refreshPayload = {
81
59
  requestId: refreshRequestId,
82
- instanceId: refreshInstanceId, // TPB-12: Per-instance routing
60
+ instanceId: refreshInstanceId,
83
61
  refreshOf: leaseId,
84
- proto: 'tcp', // TPB-17: TCP protocol identifier
62
+ proto: 'tcp',
85
63
  localPort: localPortRef,
86
64
  clientId: deviceIdRef,
87
65
  ...fingerprint
88
66
  };
89
- // Cancel any existing awaiters for this leaseId before starting a new refresh
90
67
  const ackTopic = `asyx/tunnel/clients/${deviceIdRef}/evt/ack`;
91
68
  const cancelled = coordinatorIngressRef.cancelAwaitersByCriteria((awaiter) => {
92
69
  try {
@@ -107,7 +84,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
107
84
  reason: 'new_refresh_starting'
108
85
  });
109
86
  }
110
- // Wait for subscription to be ready before publishing
111
87
  if (!subscriptionReadyRef.ready) {
112
88
  logger.debug('jwt.refresh.waiting_for_subscription', { refreshRequestId });
113
89
  const maxWait = 2000;
@@ -122,7 +98,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
122
98
  logger.debug('jwt.refresh.subscription_ready', { refreshRequestId, waited: Date.now() - startWait });
123
99
  }
124
100
  }
125
- // Set up topic and wait for ack
126
101
  const cmdOpenTopic = `asyx/tunnel/clients/${deviceIdRef}/cmd/open`;
127
102
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || "20000", 10);
128
103
  logger.debug('jwt.refresh.awaiter.registered', {
@@ -147,8 +122,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
147
122
  topic: message.topic
148
123
  });
149
124
  }
150
- // TPB-17: For TCP, refresh failures are non-fatal (tunnel continues until WS closes)
151
- // But we still throw on lease_closed/REFRESH_REJECTED to let MqttControlPlaneClient handle it
152
125
  if (isReject) {
153
126
  const reason = parsed.data?.reason || 'unknown';
154
127
  if (reason === 'lease_closed' || reason === 'LEASE_CLOSED') {
@@ -175,32 +148,25 @@ export class TcpTunnelHandle extends LifecycleEmitter {
175
148
  return false;
176
149
  }
177
150
  }, ACK_TIMEOUT_MS);
178
- // Publish refresh request
179
151
  const publishSuccess = await publishRefreshRequestWithErrorHandling(coordinatorCoreRef, cmdOpenTopic, refreshPayload, refreshRequestId, logger);
180
152
  if (publishSuccess === false) {
181
153
  const bufferedError = new Error('Connection closed during refresh publish');
182
154
  bufferedError.code = 'ECONNRESET';
183
155
  throw bufferedError;
184
156
  }
185
- // Wait for ack (non-fatal for TCP - tunnel continues on failure)
186
157
  let ackResult;
187
158
  try {
188
159
  ackResult = await ackPromise;
189
160
  }
190
161
  catch (error) {
191
- // TPB-17: For TCP, refresh failures are non-fatal
192
- // Log and return null to indicate refresh failed, but don't throw
193
- // The tunnel will continue until WebSocket closes naturally
194
162
  if (error.code === 'LEASE_CLOSED' || error.code === 'REFRESH_REJECTED') {
195
163
  logger.warn('tcp.refresh.rejected', {
196
164
  reason: error.reason || 'unknown',
197
165
  requestId: refreshRequestId,
198
166
  action: 'non_fatal_continue'
199
167
  });
200
- // Return null to indicate refresh failed, but don't throw (non-fatal)
201
168
  return null;
202
169
  }
203
- // Timeout or other errors - also non-fatal for TCP
204
170
  logger.warn('tcp.refresh.timeout', {
205
171
  error: error.message,
206
172
  requestId: refreshRequestId,
@@ -208,13 +174,11 @@ export class TcpTunnelHandle extends LifecycleEmitter {
208
174
  });
209
175
  return null;
210
176
  }
211
- // Get new assignment (updated by open_ack handler)
212
177
  const newAssignment = getAssignment(refreshInstanceId);
213
178
  if (!newAssignment) {
214
179
  logger.warn('tcp.refresh.no_assignment', { requestId: refreshRequestId });
215
180
  return null;
216
181
  }
217
- // Extract expiration from new JWT
218
182
  const newJwt = newAssignment.jwt;
219
183
  const parts = newJwt.split('.');
220
184
  if (parts.length !== 3) {
@@ -227,9 +191,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
227
191
  logger.warn('tcp.refresh.no_exp', { requestId: refreshRequestId });
228
192
  return null;
229
193
  }
230
- // TPB-17: TCP refresh updates assignment/JWT for reconnect use
231
- // No data-plane reauth needed (TCP uses TCP-v1 framing, not WebSocket auth)
232
- // The assignment is already updated by the open_ack handler
233
194
  logger.debug('tcp.refresh.success', {
234
195
  leaseId: newAssignment.leaseId,
235
196
  expMs,
@@ -245,8 +206,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
245
206
  metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort },
246
207
  logger,
247
208
  onRefreshLease,
248
- // Story 3.13: a renewal that finds the lease closed reopens on the same port (limit and stop
249
- // conditions in reassignSamePort); a refusal ends the tunnel as before.
250
209
  onLeaseClosed: async () => {
251
210
  const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
252
211
  if (!ok)
@@ -264,8 +223,8 @@ export class TcpTunnelHandle extends LifecycleEmitter {
264
223
  },
265
224
  instanceIdRef,
266
225
  subscriptionReadyRef,
267
- trackSubscriptionReady: false, // TCP has never tracked it
268
- reportOffline: false, // TCP has never reported a lost control-plane connection
226
+ trackSubscriptionReady: false,
227
+ reportOffline: false,
269
228
  });
270
229
  mqttClient = cpSession.mqttClient;
271
230
  this.mqttClient = mqttClient;
@@ -299,7 +258,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
299
258
  await mqttClient.connect();
300
259
  }
301
260
  };
302
- // 3) Connect to control plane
303
261
  try {
304
262
  await mqttClient.connect();
305
263
  }
@@ -307,15 +265,12 @@ export class TcpTunnelHandle extends LifecycleEmitter {
307
265
  logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
308
266
  throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
309
267
  }
310
- // TPB-12: instanceId is the full MQTT clientId after connection
311
268
  instanceIdRef.instanceId = mqttClient.getClientId();
312
269
  const instanceId = instanceIdRef.instanceId;
313
270
  logger.debug('cli.instance.registered', { instanceId, tunnelType: 'tcp', baseClientId });
314
- // 4) Topics
315
271
  const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
316
272
  const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
317
273
  await core.subscribe(evtWildcard, 0);
318
- // 5) Message ingress and dispatcher
319
274
  const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
320
275
  ingress.setDispatcher(dispatchEvt);
321
276
  const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
@@ -328,7 +283,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
328
283
  });
329
284
  coordinatorCoreRef = core;
330
285
  coordinatorIngressRef = ingress;
331
- // A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
332
286
  core.onMessage(async (m) => {
333
287
  try {
334
288
  await ingress.handleMessage(m);
@@ -348,31 +302,27 @@ export class TcpTunnelHandle extends LifecycleEmitter {
348
302
  this.setState('closed', { error });
349
303
  }
350
304
  });
351
- // 6) Publish cmd/open request with TCP protocol
352
305
  let requestId = '';
353
306
  const { getFpHash } = await import('../lib/fingerprint.js');
354
307
  const fingerprint = await getFpHash(credentials.clientId);
355
- // TCP-S2 / E3-S8 / TPB-12: TCP cmd/open payload
356
308
  const openPayload = {
357
- instanceId, // TPB-12: Per-instance routing
358
- tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
309
+ instanceId,
310
+ tunnelSession: this.tunnelSession,
359
311
  proto: 'tcp',
360
- target, // "127.0.0.1:<port>" from TCP-S1
312
+ target,
361
313
  clientId: credentials.clientId,
362
314
  ...fingerprint,
363
315
  };
364
316
  if (this.opts.replace === true)
365
- openPayload.replace = true; // Story 1.9 (SDK form of --replace)
317
+ openPayload.replace = true;
366
318
  openPayload.opts = { preferredPort: null };
367
319
  if (serviceName)
368
320
  openPayload.opts.name = serviceName;
369
321
  if (kind)
370
322
  openPayload.opts.kind = kind;
371
- // TPB-03B: Include requestedExternalPort in opts (null if omitted)
372
323
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
373
324
  openPayload.opts.requestedExternalPort = requestedExternalPort;
374
325
  }
375
- // 7) Wait for ack and assignment
376
326
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
377
327
  let assignment;
378
328
  let reassignSamePort;
@@ -392,7 +342,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
392
342
  assignment = opened.assignment;
393
343
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'tcp' });
394
344
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'tcp', tcpAliasFqdn: assignment.tcpAliasFqdn, publicPort: assignment.publicPort });
395
- // TPB-12: Persist assignment using per-instance store
396
345
  try {
397
346
  const { setAssignment } = await import('../state/assignment.js');
398
347
  const { clearExpectedRequestId } = await import('../state/instance-registry.js');
@@ -400,13 +349,11 @@ export class TcpTunnelHandle extends LifecycleEmitter {
400
349
  clearExpectedRequestId(instanceId);
401
350
  }
402
351
  catch { }
403
- // TCP-S3: Handle warnings array (alias unavailable)
404
352
  const warnings = assignment.warnings || [];
405
353
  const aliasRequestedButFailed = warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some((w) => w.code === 'TCP_ALIAS_UNAVAILABLE');
406
354
  if (aliasRequestedButFailed) {
407
355
  logger.warn('tcp.alias.unavailable', { requestId, fqdn: assignment.fqdn, publicPort: assignment.publicPort });
408
356
  }
409
- // TCP-S3 / E3-S8: where the server is reachable (the CLI prints it)
410
357
  const tcpAliasFqdn = assignment.tcpAliasFqdn;
411
358
  this.emit('assigned', {
412
359
  tcpAliasFqdn,
@@ -420,17 +367,15 @@ export class TcpTunnelHandle extends LifecycleEmitter {
420
367
  if (tcpAliasFqdn) {
421
368
  logger.debug('tcp.alias.ready', { requestId, tcpAliasFqdn, fqdn: assignment.fqdn, publicPort: assignment.publicPort });
422
369
  }
423
- // Story 10.9: if the relay refuses this assignment on a reconnect (the tenant moved), open
424
- // again for the same public port; the control plane places the lease on the current relay.
425
370
  reassignSamePort = async () => {
426
371
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
427
372
  const cur = getA(instanceIdRef.instanceId) || assignment;
428
373
  const rid = randomUUID();
429
- if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
374
+ if (!this.reopenLimiter.allow()) {
430
375
  this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
431
376
  throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
432
377
  }
433
- const again = reopenPayload(openPayload, rid, cur.publicPort ?? assignment.publicPort); // never carries replace
378
+ const again = reopenPayload(openPayload, rid, cur.publicPort ?? assignment.publicPort);
434
379
  setExpectedRequestId(instanceIdRef.instanceId, rid);
435
380
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
436
381
  let next;
@@ -438,13 +383,12 @@ export class TcpTunnelHandle extends LifecycleEmitter {
438
383
  next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
439
384
  }
440
385
  catch (e) {
441
- // Story 3.13: a refused reopen ends the tunnel and says why
442
386
  this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
443
387
  throw e;
444
388
  }
445
389
  setA(instanceIdRef.instanceId, next);
446
390
  logger.info('tcp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
447
- this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort }); // Story 3.13: one line for the user
391
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
448
392
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
449
393
  };
450
394
  }
@@ -455,8 +399,7 @@ export class TcpTunnelHandle extends LifecycleEmitter {
455
399
  }
456
400
  catch { }
457
401
  throw error;
458
- } // Story 1.9
459
- // TCP-S3 / TPB-03B: coordinator error codes, reported as refusals with what the CLI prints
402
+ }
460
403
  const errorCode = error.code || error.reason || error.data?.reason;
461
404
  const lc = String(errorCode || '').toLowerCase();
462
405
  const refused = (code, details, logMsg) => {
@@ -495,7 +438,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
495
438
  catch { }
496
439
  throw refusal;
497
440
  }
498
- // Generic error handling
499
441
  logger.error('cli.ack.wait.failed', { error: error.message, errorCode, instanceId, tunnelType: 'tcp' });
500
442
  try {
501
443
  const { clearExpectedRequestId } = await import('../state/instance-registry.js');
@@ -508,18 +450,17 @@ export class TcpTunnelHandle extends LifecycleEmitter {
508
450
  catch { }
509
451
  throw new ConnectionError('assignment_failed', error.message, { cause: error });
510
452
  }
511
- // TCP-S4: Connect to the relay (was connectToRelayTcp)
512
453
  const { TcpTunnel } = await import('../tunnel/tcp-tunnel.js');
513
454
  const { getAssignment: getStoredAssignment } = await import('../state/assignment.js');
514
455
  const tunnel = new TcpTunnel({
515
456
  relayUrl: assignment.relayUrl,
516
- jwt: assignment.jwt, // Use JWT as-is (no validation)
457
+ jwt: assignment.jwt,
517
458
  getJwt: () => (mqttClient ? getStoredAssignment(mqttClient.getClientId())?.jwt : null) || null,
518
459
  reassign: reassignSamePort,
519
460
  deviceId: credentials.clientId,
520
461
  requestId: assignment.requestId,
521
462
  localPort,
522
- leaseId: assignment.leaseId, // E3-S3: leaseId for TCP relay WebSocket query parameters
463
+ leaseId: assignment.leaseId,
523
464
  coordinatorCore: core,
524
465
  coordinatorIngress: ingress,
525
466
  isControlPlaneConnected,
@@ -528,8 +469,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
528
469
  getForceReconnect,
529
470
  controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
530
471
  log: adaptLogger(logger),
531
- // Story 12.1 (c2): where the tunnel used to exit, it now ends with a typed error; the CLI exits
532
- // with the same code (silently, as before).
533
472
  exit: (code) => this.setState('closed', { error: new ConnectionError('tunnel_ended', `tunnel ended (exit code ${code})`, { details: { exitCode: code } }) }),
534
473
  });
535
474
  this.tunnel = tunnel;
@@ -559,12 +498,11 @@ export class TcpTunnelHandle extends LifecycleEmitter {
559
498
  this.setState('live', info);
560
499
  return info;
561
500
  }
562
- /** Close the data plane, then the control plane. */
563
501
  async close() {
564
502
  try {
565
503
  await this.goodbye(2000);
566
504
  }
567
- catch { /* Story 3.13: a goodbye never blocks a stop */ }
505
+ catch { }
568
506
  try {
569
507
  this.tunnel?.close();
570
508
  }
@@ -573,10 +511,6 @@ export class TcpTunnelHandle extends LifecycleEmitter {
573
511
  }
574
512
  }
575
513
  }
576
- /**
577
- * TPB-17: schedule the first TCP renewal from the assignment token's expiry (moved unchanged from
578
- * connectToRelayTcp; exported so its behaviour can be tested on its own).
579
- */
580
514
  export function scheduleInitialTcpRefresh(mqttClient, assignment, logger) {
581
515
  if (mqttClient && assignment.jwt && assignment.leaseId) {
582
516
  try {
@@ -1,14 +1,6 @@
1
- // Story 12.1 (step 2b, sub-step 3; TypeScript in r3): the UDP tunnel flow, moved from udpTunnel() and
2
- // connectToRelayUdp() in clients/asyx/src/commands/tunnel.js. Behaviour is unchanged; what the CLI
3
- // printed or exited on is now an event or a typed error, and the CLI maps both to its old wording:
4
- // 'control-connected' / 'control-offline' { reason } / 'control-fatal' { reason, error }
5
- // state events from LifecycleEmitter: 'opening', 'live', and a final 'closed' { error } when a
6
- // reply ends the tunnel after it opened (SetupRequiredError, RefusedError, InternalError).
7
- // open() rejects with a ConnectionError whose code tells the caller what failed:
8
- // control_plane_connect_failed, udp_relay_unavailable, assignment_failed, tunnel_connect_failed.
9
1
  import { randomUUID } from 'node:crypto';
10
- import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
11
- import { sayGoodbye } from './goodbye.js'; // Story 3.13
2
+ import { ReopenLimiter, reopenPayload } from './reopen.js';
3
+ import { sayGoodbye } from './goodbye.js';
12
4
  import { LifecycleEmitter } from '../lifecycle.js';
13
5
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
14
6
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -19,9 +11,7 @@ export class UdpTunnelHandle extends LifecycleEmitter {
19
11
  opts;
20
12
  tunnel = null;
21
13
  mqttClient = null;
22
- /** Story 1.9: one id for this tunnel across its opens. */
23
14
  tunnelSession = randomUUID();
24
- /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
25
15
  reopenLimiter = new ReopenLimiter();
26
16
  core = null;
27
17
  assignment = null;
@@ -29,11 +19,9 @@ export class UdpTunnelHandle extends LifecycleEmitter {
29
19
  super();
30
20
  this.opts = { targetHost: '127.0.0.1', requestedExternalPort: null, ...o };
31
21
  }
32
- /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
33
22
  async goodbye(timeoutMs = 2000) {
34
23
  return sayGoodbye(this, timeoutMs);
35
24
  }
36
- /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
37
25
  async open() {
38
26
  const { credentials, targetPort, targetHost, requestedExternalPort, logger } = this.opts;
39
27
  this.setState('opening');
@@ -42,7 +30,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
42
30
  const { MqttControlPlaneTransport } = await import('../control-plane/MqttControlPlaneTransport.js');
43
31
  const { MessageIngress } = await import('../mqtt/ingress.js');
44
32
  const { dispatch: dispatchEvt } = await import('../mqtt/events/index.js');
45
- // CLI-IMG-ControlPlane-Watchdog: Add configurable timeout
46
33
  const CONTROL_PLANE_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_TIMEOUT_MS || '60000', 10);
47
34
  const baseClientId = credentials.clientId;
48
35
  const instanceIdRef = { instanceId: null };
@@ -51,8 +38,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
51
38
  const deviceIdRef = credentials.clientId;
52
39
  const subscriptionReadyRef = { ready: false };
53
40
  let mqttClient;
54
- // Story 11.2: UDP refresh (control plane UDP-S3), so a reconnect after the first token expires
55
- // still has a valid token. Same flow as TCP (TPB-17); failures are non-fatal.
56
41
  const onRefreshLease = async () => {
57
42
  if (!coordinatorCoreRef || !coordinatorIngressRef) {
58
43
  throw new Error('Coordinator not available for refresh');
@@ -64,7 +49,7 @@ export class UdpTunnelHandle extends LifecycleEmitter {
64
49
  if (!currentAssignment?.leaseId) {
65
50
  throw new Error(`No current assignment for refresh (instanceId: ${refreshInstanceId})`);
66
51
  }
67
- const refreshRequestId = `refresh-${randomUUID()}` /* Defect 11.27: unique across processes (was Date.now()) */;
52
+ const refreshRequestId = `refresh-${randomUUID()}`;
68
53
  const fingerprint = await getFpHash(deviceIdRef);
69
54
  const refreshPayload = {
70
55
  requestId: refreshRequestId,
@@ -118,8 +103,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
118
103
  metadata: { baseClientId, targetPort, targetHost, requestedExternalPort },
119
104
  logger,
120
105
  onRefreshLease,
121
- // Story 3.13: a renewal that finds the lease closed reopens on the same port (limit and stop
122
- // conditions in reassignSamePort); a refusal ends the tunnel as before.
123
106
  onLeaseClosed: async () => {
124
107
  const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
125
108
  if (!ok)
@@ -172,7 +155,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
172
155
  await mqttClient.connect();
173
156
  }
174
157
  };
175
- // 3) Connect to control plane
176
158
  try {
177
159
  await mqttClient.connect();
178
160
  }
@@ -180,16 +162,13 @@ export class UdpTunnelHandle extends LifecycleEmitter {
180
162
  logger.error('mqtt.connect.failed', { error: e?.message || String(e) });
181
163
  throw new ConnectionError('control_plane_connect_failed', e?.message || String(e), { cause: e });
182
164
  }
183
- // TPB-12: instanceId is the full MQTT clientId after connection
184
165
  instanceIdRef.instanceId = mqttClient.getClientId();
185
166
  const instanceId = instanceIdRef.instanceId;
186
167
  logger.debug('cli.instance.registered', { instanceId, tunnelType: 'udp', baseClientId });
187
- // 4) Topics
188
168
  const evtWildcard = `asyx/tunnel/clients/${baseClientId}/evt/#`;
189
169
  const cmdOpenTopic = `asyx/tunnel/clients/${baseClientId}/cmd/open`;
190
170
  await core.subscribe(evtWildcard, 0);
191
171
  subscriptionReadyRef.ready = true;
192
- // 5) Message ingress and dispatcher
193
172
  const ingress = new MessageIngress({ maxAwaiters: 100, observability: process.env.ASYX_DEBUG === '1', logger, onObserve: this.opts.onObserve });
194
173
  ingress.setDispatcher(dispatchEvt);
195
174
  const { registerInstance, setExpectedRequestId } = await import('../state/instance-registry.js');
@@ -202,7 +181,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
202
181
  });
203
182
  coordinatorCoreRef = core;
204
183
  coordinatorIngressRef = ingress;
205
- // A reply that ends the tunnel closes it with a typed error (the CLI used to print and exit here).
206
184
  core.onMessage(async (m) => {
207
185
  try {
208
186
  await ingress.handleMessage(m);
@@ -222,28 +200,26 @@ export class UdpTunnelHandle extends LifecycleEmitter {
222
200
  this.setState('closed', { error });
223
201
  }
224
202
  });
225
- // 6) Publish cmd/open request with UDP protocol
226
203
  let requestId = '';
227
204
  const { getFpHash } = await import('../lib/fingerprint.js');
228
205
  const fingerprint = await getFpHash(credentials.clientId);
229
206
  const openPayload = {
230
- instanceId, // TPB-12: Per-instance routing
231
- tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
207
+ instanceId,
208
+ tunnelSession: this.tunnelSession,
232
209
  protocol: 'udp',
233
210
  tunnelMode: 'udpWs-v1',
234
- port: targetPort, // UDP-S13: the app's listening port
211
+ port: targetPort,
235
212
  targetHost,
236
213
  targetPort,
237
214
  clientId: credentials.clientId,
238
- tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
215
+ tenantId: 'tunnel',
239
216
  ...fingerprint,
240
217
  };
241
218
  if (this.opts.replace === true)
242
- openPayload.replace = true; // Story 1.9 (SDK form of --replace)
219
+ openPayload.replace = true;
243
220
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
244
221
  openPayload.externalPort = requestedExternalPort;
245
222
  }
246
- // 7) Wait for ack and assignment
247
223
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
248
224
  let assignment;
249
225
  let reassignSamePort;
@@ -263,7 +239,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
263
239
  assignment = opened.assignment;
264
240
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'udp' });
265
241
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'udp', publicPort: assignment.publicPort });
266
- // UDP-S1: Validate assignment (AC1.4/AC5.1)
267
242
  if (!assignment.relayUrl)
268
243
  throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing relayUrl in assignment');
269
244
  if (!assignment.tunnelMode || assignment.tunnelMode !== 'udpWs-v1') {
@@ -279,7 +254,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
279
254
  const assignmentJwt = assignment.assignmentJwt || assignment.jwt;
280
255
  if (!assignmentJwt)
281
256
  throw relayUnavailable('UDP_RELAY_UNAVAILABLE: Missing assignmentJwt in assignment');
282
- // AC1.4/AC5.1: Verify JWT signature and claims using JWKS
283
257
  try {
284
258
  const { verifyAssignmentJWT } = await import('../lib/jwt-verifier.js');
285
259
  await verifyAssignmentJWT(assignmentJwt, { relayId: assignment.relayId, protocol: 'udp', tunnelMode: 'udpWs-v1', leaseId: assignment.leaseId });
@@ -289,7 +263,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
289
263
  logger.error('udp.assignment.jwt_verification_failed', { error: jwtError.message, code: jwtError.code, relayId: assignment.relayId, leaseId: assignment.leaseId });
290
264
  throw relayUnavailable(`UDP_RELAY_UNAVAILABLE: JWT verification failed: ${jwtError.message}`);
291
265
  }
292
- // TPB-12: Persist assignment using per-instance store
293
266
  try {
294
267
  const { setAssignment } = await import('../state/assignment.js');
295
268
  const { clearExpectedRequestId } = await import('../state/instance-registry.js');
@@ -297,17 +270,15 @@ export class UdpTunnelHandle extends LifecycleEmitter {
297
270
  clearExpectedRequestId(instanceId);
298
271
  }
299
272
  catch { }
300
- // Story 10.9: if the relay refuses this assignment on a reconnect (the tenant moved), open
301
- // again for the same public port; the control plane places the lease on the current relay.
302
273
  reassignSamePort = async () => {
303
274
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
304
275
  const cur = getA(instanceIdRef.instanceId) || assignment;
305
276
  const rid = randomUUID();
306
- if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
277
+ if (!this.reopenLimiter.allow()) {
307
278
  this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
308
279
  throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
309
280
  }
310
- const again = { ...reopenPayload(openPayload, rid, null), externalPort: cur.publicPort ?? assignment.publicPort }; // never carries replace
281
+ const again = { ...reopenPayload(openPayload, rid, null), externalPort: cur.publicPort ?? assignment.publicPort };
311
282
  setExpectedRequestId(instanceIdRef.instanceId, rid);
312
283
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
313
284
  let next;
@@ -315,13 +286,12 @@ export class UdpTunnelHandle extends LifecycleEmitter {
315
286
  next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
316
287
  }
317
288
  catch (e) {
318
- // Story 3.13: a refused reopen ends the tunnel and says why
319
289
  this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
320
290
  throw e;
321
291
  }
322
292
  setA(instanceIdRef.instanceId, next);
323
293
  logger.info('udp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
324
- this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort }); // Story 3.13: one line for the user
294
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
325
295
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
326
296
  };
327
297
  }
@@ -332,7 +302,7 @@ export class UdpTunnelHandle extends LifecycleEmitter {
332
302
  }
333
303
  catch { }
334
304
  throw error;
335
- } // Story 1.9
305
+ }
336
306
  logger.error('cli.ack.wait.failed', { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
337
307
  if (error.code === 'udp_relay_unavailable') {
338
308
  try {
@@ -341,7 +311,6 @@ export class UdpTunnelHandle extends LifecycleEmitter {
341
311
  catch { }
342
312
  throw error;
343
313
  }
344
- // TPB-12: Clean up expected requestId on timeout/error
345
314
  try {
346
315
  const { clearExpectedRequestId } = await import('../state/instance-registry.js');
347
316
  clearExpectedRequestId(instanceId);
@@ -353,14 +322,12 @@ export class UdpTunnelHandle extends LifecycleEmitter {
353
322
  catch { }
354
323
  throw new ConnectionError('assignment_failed', error.message, { cause: error });
355
324
  }
356
- // Connect to the relay (was connectToRelayUdp)
357
325
  const { UdpTunnel } = await import('../tunnel/udp-tunnel.js');
358
326
  const { getAssignment: getStoredAssignment } = await import('../state/assignment.js');
359
327
  const tunnel = new UdpTunnel({
360
328
  reassign: reassignSamePort,
361
329
  relayUrl: assignment.relayUrl,
362
- jwt: assignment.assignmentJwt || assignment.jwt, // UDP-S1: Use assignmentJwt if available
363
- // Story 11.2: reconnects use the newest token (kept fresh by the UDP refresh)
330
+ jwt: assignment.assignmentJwt || assignment.jwt,
364
331
  getJwt: () => {
365
332
  const stored = instanceId ? getStoredAssignment(instanceId) : null;
366
333
  return stored?.assignmentJwt || stored?.jwt || null;
@@ -370,7 +337,7 @@ export class UdpTunnelHandle extends LifecycleEmitter {
370
337
  targetHost,
371
338
  targetPort,
372
339
  leaseId: assignment.leaseId,
373
- relayId: assignment.relayId, // AC5.1: Pass relayId for JWT validation
340
+ relayId: assignment.relayId,
374
341
  coordinatorCore: core,
375
342
  coordinatorIngress: ingress,
376
343
  isControlPlaneConnected,
@@ -379,14 +346,11 @@ export class UdpTunnelHandle extends LifecycleEmitter {
379
346
  getForceReconnect,
380
347
  controlPlaneTimeoutMs: CONTROL_PLANE_TIMEOUT_MS,
381
348
  log: adaptLogger(logger),
382
- // Story 12.1 (c2): where the tunnel used to exit, it now ends with a typed error; the CLI exits
383
- // with the same code (silently, as before).
384
349
  exit: (code) => this.setState('closed', { error: new ConnectionError('tunnel_ended', `tunnel ended (exit code ${code})`, { details: { exitCode: code } }) }),
385
350
  });
386
351
  this.tunnel = tunnel;
387
352
  try {
388
353
  await tunnel.open();
389
- // Story 11.2: schedule the first proactive token refresh (as TCP, TPB-17)
390
354
  const firstExp = jwtExpOf(assignment.assignmentJwt || assignment.jwt);
391
355
  if (mqttClient && firstExp && assignment.leaseId) {
392
356
  mqttClient.scheduleRefresh(firstExp * 1000, assignment.leaseId);
@@ -417,12 +381,11 @@ export class UdpTunnelHandle extends LifecycleEmitter {
417
381
  this.setState('live', info);
418
382
  return info;
419
383
  }
420
- /** Close the data plane, then the control plane. */
421
384
  async close() {
422
385
  try {
423
386
  await this.goodbye(2000);
424
387
  }
425
- catch { /* Story 3.13: a goodbye never blocks a stop */ }
388
+ catch { }
426
389
  try {
427
390
  this.tunnel?.close();
428
391
  }