asyx 0.6.1 → 0.7.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.
Files changed (34) hide show
  1. package/README.md +56 -8
  2. package/package.json +2 -1
  3. package/src/commands/in-use-messages.js +64 -0
  4. package/src/commands/reject-messages.js +56 -0
  5. package/src/commands/tunnel.js +59 -0
  6. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +13 -0
  7. package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +21 -0
  8. package/vendor/tunnel-core/dist/control-plane/session.d.ts +5 -0
  9. package/vendor/tunnel-core/dist/control-plane/session.js +2 -1
  10. package/vendor/tunnel-core/dist/flows/goodbye.d.ts +10 -0
  11. package/vendor/tunnel-core/dist/flows/goodbye.js +27 -0
  12. package/vendor/tunnel-core/dist/flows/http.d.ts +11 -0
  13. package/vendor/tunnel-core/dist/flows/http.js +84 -10
  14. package/vendor/tunnel-core/dist/flows/in-use.d.ts +27 -0
  15. package/vendor/tunnel-core/dist/flows/in-use.js +42 -0
  16. package/vendor/tunnel-core/dist/flows/reopen.d.ts +9 -0
  17. package/vendor/tunnel-core/dist/flows/reopen.js +27 -0
  18. package/vendor/tunnel-core/dist/flows/tcp.d.ts +11 -0
  19. package/vendor/tunnel-core/dist/flows/tcp.js +70 -11
  20. package/vendor/tunnel-core/dist/flows/udp.d.ts +11 -0
  21. package/vendor/tunnel-core/dist/flows/udp.js +70 -10
  22. package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +132 -0
  23. package/vendor/tunnel-core/dist/lib/fingerprint.js +24 -1
  24. package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +2 -0
  25. package/vendor/tunnel-core/dist/mqtt/events/handlers.js +37 -0
  26. package/vendor/tunnel-core/dist/mqtt/events/index.js +2 -1
  27. package/vendor/tunnel-core/dist/state/assignment.d.ts +7 -0
  28. package/vendor/tunnel-core/dist/state/assignment.js +17 -0
  29. package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +4 -1
  30. package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +60 -12
  31. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +3 -0
  32. package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +18 -0
  33. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +3 -0
  34. package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +18 -0
@@ -7,6 +7,8 @@
7
7
  // open() rejects with ConnectionError control_plane_connect_failed | assignment_failed |
8
8
  // tunnel_connect_failed. The renewal callback (in-band reauth, reconnect fallback) is unchanged.
9
9
  import { randomUUID } from 'node:crypto';
10
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
11
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
10
12
  import { LifecycleEmitter } from '../lifecycle.js';
11
13
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
12
14
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -40,12 +42,20 @@ export class HttpTunnelHandle extends LifecycleEmitter {
40
42
  opts;
41
43
  tunnel = null;
42
44
  mqttClient = null;
45
+ /** Story 1.9: one id for this tunnel across its opens (a re-open is never "another tunnel"). */
46
+ tunnelSession = randomUUID();
47
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
48
+ reopenLimiter = new ReopenLimiter();
43
49
  core = null;
44
50
  assignment = null;
45
51
  constructor(o) {
46
52
  super();
47
53
  this.opts = { secGroupSlug: null, ...o };
48
54
  }
55
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
56
+ async goodbye(timeoutMs = 2000) {
57
+ return sayGoodbye(this, timeoutMs);
58
+ }
49
59
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
50
60
  async open() {
51
61
  const { credentials, localPort, secGroupSlug, logger } = this.opts;
@@ -383,6 +393,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
383
393
  logger.debug('jwt.refresh.success', { method: 'reconnect', leaseId: newAssignment.leaseId });
384
394
  return expMs;
385
395
  };
396
+ // Story 3.13: set once the open request exists (below); used by the control plane and the tunnel.
397
+ const reopenRef = { fn: null };
386
398
  const cpSession = createControlPlaneSession({
387
399
  credentials,
388
400
  tunnelType: 'http',
@@ -396,6 +408,8 @@ export class HttpTunnelHandle extends LifecycleEmitter {
396
408
  }
397
409
  return r;
398
410
  },
411
+ onLeaseClosed: async () => { if (!reopenRef.fn)
412
+ throw new Error('reopen unavailable'); return reopenRef.fn(); }, // Story 3.13
399
413
  instanceIdRef,
400
414
  subscriptionReadyRef,
401
415
  getTunnel: () => tunnelInstanceRef.tunnel,
@@ -486,32 +500,42 @@ export class HttpTunnelHandle extends LifecycleEmitter {
486
500
  this.setState('closed', { error });
487
501
  }
488
502
  });
489
- // 6) Publish cmd/open request
490
- const requestId = randomUUID();
503
+ // 6) Publish cmd/open request (Story 1.9: asked again while the address is in use, see in-use.ts)
504
+ let requestId = '';
491
505
  const { getFpHash } = await import('../lib/fingerprint.js');
492
506
  const fingerprint = await getFpHash(credentials.clientId);
493
- // TPB-12: Track expected requestId for pre-assignment routing
494
- setExpectedRequestId(instanceId, requestId);
495
507
  const openPayload = {
496
- requestId,
497
508
  instanceId, // TPB-12: Per-instance routing
498
509
  proto: 'http',
499
510
  localPort,
500
511
  clientId: credentials.clientId,
512
+ tunnelSession: this.tunnelSession, // Story 1.9: the same tunnel opening again is never "another tunnel"
501
513
  ...fingerprint,
502
514
  };
515
+ if (this.opts.replace === true)
516
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
503
517
  // QPA-04: Include secGroupSlug in cmd/open payload if provided
504
518
  if (secGroupSlug)
505
519
  openPayload.secGroupSlug = secGroupSlug;
506
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
507
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'http' });
508
520
  // 7) Wait for ack
509
521
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
510
522
  let assignment;
511
523
  try {
512
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
513
- logger.info('cli.ack.wait.start', { requestId });
514
- assignment = await assignmentPromise;
524
+ const { openUntilFree } = await import('./in-use.js');
525
+ const opened = await openUntilFree({
526
+ send: async (rid) => {
527
+ requestId = rid;
528
+ // TPB-12: Track expected requestId for pre-assignment routing
529
+ setExpectedRequestId(instanceId, rid);
530
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
531
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'http' });
532
+ logger.info('cli.ack.wait.start', { requestId: rid });
533
+ },
534
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
535
+ waitIfInUse: this.opts.waitIfInUse === true,
536
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
537
+ });
538
+ assignment = opened.assignment;
515
539
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'http' });
516
540
  logger.info('cli.assignment.received', { relayId: assignment.relayId, instanceId, tunnelType: 'http' });
517
541
  // TPB-12: Persist assignment using per-instance store
@@ -534,10 +558,53 @@ export class HttpTunnelHandle extends LifecycleEmitter {
534
558
  await core.end();
535
559
  }
536
560
  catch { }
561
+ if (error?.code === 'address_in_use')
562
+ throw error; // Story 1.9: the caller reports why, with the details
537
563
  throw new ConnectionError('assignment_failed', error.message, { cause: error });
538
564
  }
539
565
  // 8) Connect to the relay (was connectToRelay)
540
566
  const { HttpTunnel } = await import('../tunnel/http-tunnel.js');
567
+ // Story 3.13: a fresh open for the same address (same session, never --replace), then the tunnel takes
568
+ // the new token and relay and reconnects, as the renewal fallback does.
569
+ reopenRef.fn = async () => {
570
+ if (!this.reopenLimiter.allow()) {
571
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
572
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
573
+ }
574
+ const rid = randomUUID();
575
+ setExpectedRequestId(instanceId, rid);
576
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(reopenPayload(openPayload, rid, null)), qos: 1, retain: false });
577
+ let next;
578
+ try {
579
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
580
+ }
581
+ catch (e) {
582
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
583
+ throw e;
584
+ }
585
+ const { setAssignment: setA } = await import('../state/assignment.js');
586
+ setA(instanceId, next);
587
+ let expMs = null;
588
+ try {
589
+ expMs = JSON.parse(Buffer.from(String(next.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
590
+ }
591
+ catch {
592
+ expMs = null;
593
+ }
594
+ const t = tunnelInstanceRef.tunnel;
595
+ if (t) {
596
+ t.jwt = next.jwt;
597
+ t.requestId = next.requestId;
598
+ t.relayUrl = next.relayUrl;
599
+ t.headers = { 'Authorization': `Bearer ${next.jwt}`, 'X-Asyx-DeviceId': deviceIdRef, 'X-Asyx-RequestId': next.requestId };
600
+ t.jwtMeta = { token: next.jwt, expMs };
601
+ await t._attemptConnect();
602
+ }
603
+ this.assignment = next;
604
+ logger.info('http.reopen.ok', { leaseId: next.leaseId, relayId: next.relayId });
605
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: null });
606
+ return { exp: expMs, leaseId: next.leaseId };
607
+ };
541
608
  const tunnel = new HttpTunnel({
542
609
  relayUrl: assignment.relayUrl,
543
610
  jwt: assignment.jwt, // Use JWT as-is (no validation)
@@ -559,6 +626,13 @@ export class HttpTunnelHandle extends LifecycleEmitter {
559
626
  // used to print is a notice; the CLI keeps the exit code and the wording.
560
627
  onFatal: (code) => this.setState('closed', { error: new ConnectionError(code, `http tunnel ended: ${code}`, { details: { exitCode: 1 } }) }),
561
628
  onNotice: (code, details) => this.emit('notice', { code, ...details }),
629
+ onLeaseClosed: async () => { try {
630
+ await reopenRef.fn?.();
631
+ return true;
632
+ }
633
+ catch {
634
+ return false;
635
+ } }, // Story 3.13
562
636
  });
563
637
  tunnelInstanceRef.tunnel = tunnel;
564
638
  this.tunnel = tunnel;
@@ -0,0 +1,27 @@
1
+ export declare const SAME_COMPUTER_WAIT_MS = 15000;
2
+ export declare const SAME_COMPUTER_STEP_MS = 3000;
3
+ export declare const WAIT_STEP_MS = 30000;
4
+ export type InUseDetails = Record<string, unknown> & {
5
+ sameComputer?: boolean;
6
+ };
7
+ /** How long to wait before asking again, or null to give up (the caller reports the refusal). */
8
+ export declare function inUseDelay(details: InUseDetails | undefined, firstAt: number, now: number, waitIfInUse: boolean): number | null;
9
+ export interface OpenUntilFreeOptions<T> {
10
+ /** publish a cmd/open with this requestId */
11
+ send: (requestId: string) => Promise<void>;
12
+ /** wait for the assignment of this requestId */
13
+ wait: (requestId: string) => Promise<T>;
14
+ waitIfInUse?: boolean;
15
+ onWaiting?: (info: {
16
+ details: InUseDetails;
17
+ delayMs: number;
18
+ sameComputer: boolean;
19
+ attempt: number;
20
+ }) => void;
21
+ sleep?: (ms: number) => Promise<void>;
22
+ now?: () => number;
23
+ }
24
+ export declare function openUntilFree<T>(o: OpenUntilFreeOptions<T>): Promise<{
25
+ assignment: T;
26
+ requestId: string;
27
+ }>;
@@ -0,0 +1,42 @@
1
+ // Story 1.9: an address runs one tunnel of each kind. When the coordinator answers address_in_use,
2
+ // the open fails with RefusedError('address_in_use', { details }). On the same computer (a restart
3
+ // that beat the old connection's offline notice) the open asks again every 3 s for up to 15 s; with
4
+ // waitIfInUse (`asyx tunnel --wait`) it asks again every 30 s until the address is free. Every retry
5
+ // travels over the same MQTT connection; nothing new is opened.
6
+ import { randomUUID } from 'node:crypto';
7
+ export const SAME_COMPUTER_WAIT_MS = 15_000;
8
+ export const SAME_COMPUTER_STEP_MS = 3_000;
9
+ export const WAIT_STEP_MS = 30_000;
10
+ /** How long to wait before asking again, or null to give up (the caller reports the refusal). */
11
+ export function inUseDelay(details, firstAt, now, waitIfInUse) {
12
+ if (details?.sameComputer === true && now - firstAt < SAME_COMPUTER_WAIT_MS)
13
+ return SAME_COMPUTER_STEP_MS;
14
+ if (waitIfInUse)
15
+ return WAIT_STEP_MS;
16
+ return null;
17
+ }
18
+ export async function openUntilFree(o) {
19
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
20
+ const now = o.now ?? Date.now;
21
+ let firstAt = 0;
22
+ for (let attempt = 1;; attempt++) {
23
+ const requestId = randomUUID();
24
+ await o.send(requestId);
25
+ try {
26
+ return { assignment: await o.wait(requestId), requestId };
27
+ }
28
+ catch (e) {
29
+ if (e?.code !== 'address_in_use')
30
+ throw e;
31
+ const t = now();
32
+ if (!firstAt)
33
+ firstAt = t;
34
+ const details = (e.details || {});
35
+ const delayMs = inUseDelay(details, firstAt, t, o.waitIfInUse === true);
36
+ if (delayMs === null)
37
+ throw e;
38
+ o.onWaiting?.({ details, delayMs, sameComputer: details.sameComputer === true, attempt });
39
+ await sleep(delayMs);
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,9 @@
1
+ export declare class ReopenLimiter {
2
+ private readonly max;
3
+ private readonly windowMs;
4
+ private times;
5
+ constructor(max?: number, windowMs?: number);
6
+ allow(now?: number): boolean;
7
+ }
8
+ /** The open request for a reopen: same address, port and session, never `replace`. */
9
+ export declare function reopenPayload(openPayload: Record<string, any>, requestId: string, publicPort: number | null | undefined): Record<string, any>;
@@ -0,0 +1,27 @@
1
+ // Story 3.13: a tunnel whose lease was closed while it is still meant to run opens a fresh tunnel on the
2
+ // same address (and TCP/UDP port), at most 3 times in 10 minutes; a reopen never carries --replace, so a
3
+ // tunnel that a newer one replaced is refused (address_in_use) instead of taking the address back.
4
+ export class ReopenLimiter {
5
+ max;
6
+ windowMs;
7
+ times = [];
8
+ constructor(max = 3, windowMs = 10 * 60_000) {
9
+ this.max = max;
10
+ this.windowMs = windowMs;
11
+ }
12
+ allow(now = Date.now()) {
13
+ this.times = this.times.filter((t) => now - t < this.windowMs);
14
+ if (this.times.length >= this.max)
15
+ return false;
16
+ this.times.push(now);
17
+ return true;
18
+ }
19
+ }
20
+ /** The open request for a reopen: same address, port and session, never `replace`. */
21
+ export function reopenPayload(openPayload, requestId, publicPort) {
22
+ const { replace, ...rest } = openPayload;
23
+ const again = { ...rest, requestId, reopen: true };
24
+ if (publicPort)
25
+ again.opts = { ...(rest.opts || {}), requestedExternalPort: publicPort };
26
+ return again;
27
+ }
@@ -1,3 +1,4 @@
1
+ import { ReopenLimiter } from './reopen.js';
1
2
  import { LifecycleEmitter } from '../lifecycle.js';
2
3
  import type { ControlPlaneCredentials } from '../control-plane/session.js';
3
4
  import type { Logger } from '../types.js';
@@ -15,6 +16,10 @@ export interface TcpTunnelOptions {
15
16
  logger: Logger;
16
17
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
17
18
  onObserve?: (line: string) => void;
19
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
20
+ waitIfInUse?: boolean;
21
+ /** Story 1.9: take over this address's live tunnel of the same kind (the old one is told and stops), like `asyx tunnel --replace`. */
22
+ replace?: boolean;
18
23
  }
19
24
  /** Sent with 'assigned' when the coordinator's assignment arrives. */
20
25
  export type TcpAssignedEvent = {
@@ -42,9 +47,15 @@ export declare class TcpTunnelHandle extends LifecycleEmitter {
42
47
  };
43
48
  tunnel: any;
44
49
  mqttClient: any;
50
+ /** Story 1.9: one id for this tunnel across its opens. */
51
+ readonly tunnelSession: string;
52
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
53
+ readonly reopenLimiter: ReopenLimiter;
45
54
  core: any;
46
55
  assignment: Record<string, any> | null;
47
56
  constructor(o: TcpTunnelOptions);
57
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
58
+ goodbye(timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
48
59
  /** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
49
60
  open(): Promise<TcpTunnelInfo>;
50
61
  /** Close the data plane, then the control plane. */
@@ -11,6 +11,8 @@
11
11
  // tcp_port_block_exhausted_for_tenant | tcp_port_capacity_exhausted | tenant_tcp_lease_limit_reached
12
12
  // (details carry what the CLI prints: requestedPort, blockStart, blockEnd, relayId).
13
13
  import { randomUUID } from 'node:crypto';
14
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
15
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
14
16
  import { LifecycleEmitter } from '../lifecycle.js';
15
17
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
16
18
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -20,12 +22,20 @@ export class TcpTunnelHandle extends LifecycleEmitter {
20
22
  opts;
21
23
  tunnel = null;
22
24
  mqttClient = null;
25
+ /** Story 1.9: one id for this tunnel across its opens. */
26
+ tunnelSession = randomUUID();
27
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
28
+ reopenLimiter = new ReopenLimiter();
23
29
  core = null;
24
30
  assignment = null;
25
31
  constructor(o) {
26
32
  super();
27
33
  this.opts = { serviceName: null, kind: null, requestedExternalPort: null, ...o };
28
34
  }
35
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
36
+ async goodbye(timeoutMs = 2000) {
37
+ return sayGoodbye(this, timeoutMs);
38
+ }
29
39
  /** Connect the control plane, get a lease and open the data plane; rejects with a typed error. */
30
40
  async open() {
31
41
  const { credentials, localPort, target, serviceName, kind, requestedExternalPort, logger } = this.opts;
@@ -235,6 +245,23 @@ export class TcpTunnelHandle extends LifecycleEmitter {
235
245
  metadata: { baseClientId, localPort, serviceName, kind, requestedExternalPort },
236
246
  logger,
237
247
  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
+ onLeaseClosed: async () => {
251
+ const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
252
+ if (!ok)
253
+ throw new Error('reopen refused');
254
+ const { getAssignment: getA } = await import('../state/assignment.js');
255
+ const a = getA(instanceIdRef.instanceId);
256
+ let exp = null;
257
+ try {
258
+ exp = JSON.parse(Buffer.from(String(a?.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
259
+ }
260
+ catch {
261
+ exp = null;
262
+ }
263
+ return a?.leaseId ? { exp, leaseId: a.leaseId } : null;
264
+ },
238
265
  instanceIdRef,
239
266
  subscriptionReadyRef,
240
267
  trackSubscriptionReady: false, // TCP has never tracked it
@@ -322,20 +349,20 @@ export class TcpTunnelHandle extends LifecycleEmitter {
322
349
  }
323
350
  });
324
351
  // 6) Publish cmd/open request with TCP protocol
325
- const requestId = randomUUID();
352
+ let requestId = '';
326
353
  const { getFpHash } = await import('../lib/fingerprint.js');
327
354
  const fingerprint = await getFpHash(credentials.clientId);
328
- // TPB-12: Track expected requestId for pre-assignment routing (before coordinator sends instanceId)
329
- setExpectedRequestId(instanceId, requestId);
330
355
  // TCP-S2 / E3-S8 / TPB-12: TCP cmd/open payload
331
356
  const openPayload = {
332
- requestId,
333
357
  instanceId, // TPB-12: Per-instance routing
358
+ tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
334
359
  proto: 'tcp',
335
360
  target, // "127.0.0.1:<port>" from TCP-S1
336
361
  clientId: credentials.clientId,
337
362
  ...fingerprint,
338
363
  };
364
+ if (this.opts.replace === true)
365
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
339
366
  openPayload.opts = { preferredPort: null };
340
367
  if (serviceName)
341
368
  openPayload.opts.name = serviceName;
@@ -345,16 +372,24 @@ export class TcpTunnelHandle extends LifecycleEmitter {
345
372
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
346
373
  openPayload.opts.requestedExternalPort = requestedExternalPort;
347
374
  }
348
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
349
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
350
375
  // 7) Wait for ack and assignment
351
376
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
352
377
  let assignment;
353
378
  let reassignSamePort;
354
379
  try {
355
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
356
- logger.info('cli.ack.wait.start', { requestId });
357
- assignment = await assignmentPromise;
380
+ const { openUntilFree } = await import('./in-use.js');
381
+ const opened = await openUntilFree({
382
+ send: async (rid) => {
383
+ requestId = rid;
384
+ setExpectedRequestId(instanceId, rid);
385
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
386
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'tcp', protocol: 'tcp', target });
387
+ },
388
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
389
+ waitIfInUse: this.opts.waitIfInUse === true,
390
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
391
+ });
392
+ assignment = opened.assignment;
358
393
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'tcp' });
359
394
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'tcp', tcpAliasFqdn: assignment.tcpAliasFqdn, publicPort: assignment.publicPort });
360
395
  // TPB-12: Persist assignment using per-instance store
@@ -390,16 +425,36 @@ export class TcpTunnelHandle extends LifecycleEmitter {
390
425
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
391
426
  const cur = getA(instanceIdRef.instanceId) || assignment;
392
427
  const rid = randomUUID();
393
- const again = { ...openPayload, requestId: rid, opts: { ...(openPayload.opts || {}), requestedExternalPort: cur.publicPort ?? assignment.publicPort } };
428
+ if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
429
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
430
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
431
+ }
432
+ const again = reopenPayload(openPayload, rid, cur.publicPort ?? assignment.publicPort); // never carries replace
394
433
  setExpectedRequestId(instanceIdRef.instanceId, rid);
395
434
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
396
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
435
+ let next;
436
+ try {
437
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
438
+ }
439
+ catch (e) {
440
+ // Story 3.13: a refused reopen ends the tunnel and says why
441
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
442
+ throw e;
443
+ }
397
444
  setA(instanceIdRef.instanceId, next);
398
445
  logger.info('tcp.reassign.ok', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort });
446
+ this.emit('reopened', { leaseId: next.leaseId, relayId: next.relayId, publicPort: next.publicPort }); // Story 3.13: one line for the user
399
447
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
400
448
  };
401
449
  }
402
450
  catch (error) {
451
+ if (error?.code === 'address_in_use') {
452
+ try {
453
+ await core.end();
454
+ }
455
+ catch { }
456
+ throw error;
457
+ } // Story 1.9
403
458
  // TCP-S3 / TPB-03B: coordinator error codes, reported as refusals with what the CLI prints
404
459
  const errorCode = error.code || error.reason || error.data?.reason;
405
460
  const lc = String(errorCode || '').toLowerCase();
@@ -505,6 +560,10 @@ export class TcpTunnelHandle extends LifecycleEmitter {
505
560
  }
506
561
  /** Close the data plane, then the control plane. */
507
562
  async close() {
563
+ try {
564
+ await this.goodbye(2000);
565
+ }
566
+ catch { /* Story 3.13: a goodbye never blocks a stop */ }
508
567
  try {
509
568
  this.tunnel?.close();
510
569
  }
@@ -1,3 +1,4 @@
1
+ import { ReopenLimiter } from './reopen.js';
1
2
  import { LifecycleEmitter } from '../lifecycle.js';
2
3
  import type { ControlPlaneCredentials } from '../control-plane/session.js';
3
4
  import type { Logger } from '../types.js';
@@ -12,6 +13,10 @@ export interface UdpTunnelOptions {
12
13
  logger: Logger;
13
14
  /** Called with each observability line when ASYX_DEBUG=1 (the CLI prints them). */
14
15
  onObserve?: (line: string) => void;
16
+ /** Story 1.9: while a live tunnel of this kind serves the address, ask again every 30 s instead of failing. */
17
+ waitIfInUse?: boolean;
18
+ /** Story 1.9: take over this address's live tunnel of the same kind (the old one is told and stops), like `asyx tunnel --replace`. */
19
+ replace?: boolean;
15
20
  }
16
21
  /** What open() resolves to and the 'live' state carries. */
17
22
  export type UdpTunnelInfo = {
@@ -30,9 +35,15 @@ export declare class UdpTunnelHandle extends LifecycleEmitter {
30
35
  };
31
36
  tunnel: any;
32
37
  mqttClient: any;
38
+ /** Story 1.9: one id for this tunnel across its opens. */
39
+ readonly tunnelSession: string;
40
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
41
+ readonly reopenLimiter: ReopenLimiter;
33
42
  core: any;
34
43
  assignment: Record<string, any> | null;
35
44
  constructor(o: UdpTunnelOptions);
45
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
46
+ goodbye(timeoutMs?: number): Promise<'sent' | 'skipped' | 'timeout' | 'error'>;
36
47
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
37
48
  open(): Promise<UdpTunnelInfo>;
38
49
  /** Close the data plane, then the control plane. */
@@ -7,6 +7,8 @@
7
7
  // open() rejects with a ConnectionError whose code tells the caller what failed:
8
8
  // control_plane_connect_failed, udp_relay_unavailable, assignment_failed, tunnel_connect_failed.
9
9
  import { randomUUID } from 'node:crypto';
10
+ import { ReopenLimiter, reopenPayload } from './reopen.js'; // Story 3.13
11
+ import { sayGoodbye } from './goodbye.js'; // Story 3.13
10
12
  import { LifecycleEmitter } from '../lifecycle.js';
11
13
  import { ConnectionError, SetupRequiredError, RefusedError, InternalError } from '../errors.js';
12
14
  import { createControlPlaneSession } from '../control-plane/session.js';
@@ -17,12 +19,20 @@ export class UdpTunnelHandle extends LifecycleEmitter {
17
19
  opts;
18
20
  tunnel = null;
19
21
  mqttClient = null;
22
+ /** Story 1.9: one id for this tunnel across its opens. */
23
+ tunnelSession = randomUUID();
24
+ /** Story 3.13: reopens after a closed lease, at most 3 in 10 minutes. */
25
+ reopenLimiter = new ReopenLimiter();
20
26
  core = null;
21
27
  assignment = null;
22
28
  constructor(o) {
23
29
  super();
24
30
  this.opts = { targetHost: '127.0.0.1', requestedExternalPort: null, ...o };
25
31
  }
32
+ /** Story 3.13: tell the cloud this tunnel stops on purpose (closes its lease at once); waits at most 2 s. */
33
+ async goodbye(timeoutMs = 2000) {
34
+ return sayGoodbye(this, timeoutMs);
35
+ }
26
36
  /** Connect the control plane, get a lease and open the data plane; rejects with a ConnectionError. */
27
37
  async open() {
28
38
  const { credentials, targetPort, targetHost, requestedExternalPort, logger } = this.opts;
@@ -108,6 +118,23 @@ export class UdpTunnelHandle extends LifecycleEmitter {
108
118
  metadata: { baseClientId, targetPort, targetHost, requestedExternalPort },
109
119
  logger,
110
120
  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
+ onLeaseClosed: async () => {
124
+ const ok = await this.tunnel?.reopenAfterLeaseClosed?.();
125
+ if (!ok)
126
+ throw new Error('reopen refused');
127
+ const { getAssignment: getA } = await import('../state/assignment.js');
128
+ const a = getA(instanceIdRef.instanceId);
129
+ let exp = null;
130
+ try {
131
+ exp = JSON.parse(Buffer.from(String(a?.jwt || '').split('.')[1] || '', 'base64url').toString()).exp * 1000 || null;
132
+ }
133
+ catch {
134
+ exp = null;
135
+ }
136
+ return a?.leaseId ? { exp, leaseId: a.leaseId } : null;
137
+ },
111
138
  instanceIdRef,
112
139
  subscriptionReadyRef,
113
140
  verboseRotationLogs: false,
@@ -196,13 +223,12 @@ export class UdpTunnelHandle extends LifecycleEmitter {
196
223
  }
197
224
  });
198
225
  // 6) Publish cmd/open request with UDP protocol
199
- const requestId = randomUUID();
226
+ let requestId = '';
200
227
  const { getFpHash } = await import('../lib/fingerprint.js');
201
228
  const fingerprint = await getFpHash(credentials.clientId);
202
- setExpectedRequestId(instanceId, requestId);
203
229
  const openPayload = {
204
- requestId,
205
230
  instanceId, // TPB-12: Per-instance routing
231
+ tunnelSession: this.tunnelSession, // Story 1.9: a re-open is never "another tunnel"
206
232
  protocol: 'udp',
207
233
  tunnelMode: 'udpWs-v1',
208
234
  port: targetPort, // UDP-S13: the app's listening port
@@ -212,19 +238,29 @@ export class UdpTunnelHandle extends LifecycleEmitter {
212
238
  tenantId: 'tunnel', // AC1.2: v4.1 validation phase uses literal "tunnel" as tenantId
213
239
  ...fingerprint,
214
240
  };
241
+ if (this.opts.replace === true)
242
+ openPayload.replace = true; // Story 1.9 (SDK form of --replace)
215
243
  if (requestedExternalPort !== null && requestedExternalPort !== undefined) {
216
244
  openPayload.externalPort = requestedExternalPort;
217
245
  }
218
- await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(openPayload), qos: 1, retain: false });
219
- logger.info('cli.cmd.open.sent', { requestId, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
220
246
  // 7) Wait for ack and assignment
221
247
  const ACK_TIMEOUT_MS = parseInt(process.env.ASYX_CONTROL_PLANE_ACK_TIMEOUT_MS || '20000', 10);
222
248
  let assignment;
223
249
  let reassignSamePort;
224
250
  try {
225
- const assignmentPromise = waitForAssignment(requestId, ACK_TIMEOUT_MS);
226
- logger.info('cli.ack.wait.start', { requestId });
227
- assignment = await assignmentPromise;
251
+ const { openUntilFree } = await import('./in-use.js');
252
+ const opened = await openUntilFree({
253
+ send: async (rid) => {
254
+ requestId = rid;
255
+ setExpectedRequestId(instanceId, rid);
256
+ await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify({ requestId: rid, ...openPayload }), qos: 1, retain: false });
257
+ logger.info('cli.cmd.open.sent', { requestId: rid, instanceId, tunnelType: 'udp', protocol: 'udp', tunnelMode: 'udpWs-v1' });
258
+ },
259
+ wait: (rid) => waitForAssignment(rid, ACK_TIMEOUT_MS),
260
+ waitIfInUse: this.opts.waitIfInUse === true,
261
+ onWaiting: (info) => this.emit('notice', { code: 'address_in_use_waiting', ...info }),
262
+ });
263
+ assignment = opened.assignment;
228
264
  logger.info('cli.ack.wait.resolved', { requestId, instanceId, tunnelType: 'udp' });
229
265
  logger.info('cli.assignment.received', { relayId: assignment.relayId, leaseId: assignment.leaseId, instanceId, tunnelType: 'udp', publicPort: assignment.publicPort });
230
266
  // UDP-S1: Validate assignment (AC1.4/AC5.1)
@@ -267,16 +303,36 @@ export class UdpTunnelHandle extends LifecycleEmitter {
267
303
  const { setAssignment: setA, getAssignment: getA } = await import('../state/assignment.js');
268
304
  const cur = getA(instanceIdRef.instanceId) || assignment;
269
305
  const rid = randomUUID();
270
- const again = { ...openPayload, requestId: rid, externalPort: cur.publicPort ?? assignment.publicPort };
306
+ if (!this.reopenLimiter.allow()) { // Story 3.13: at most 3 reopens in 10 minutes
307
+ this.emit('reopen_refused', { code: 'reopen_limit', details: { limit: 3, windowMin: 10 } });
308
+ throw new RefusedError('reopen_limit', 'reopened 3 times in 10 minutes', { details: { limit: 3, windowMin: 10 } });
309
+ }
310
+ const again = { ...reopenPayload(openPayload, rid, null), externalPort: cur.publicPort ?? assignment.publicPort }; // never carries replace
271
311
  setExpectedRequestId(instanceIdRef.instanceId, rid);
272
312
  await core.publish({ topic: cmdOpenTopic, payload: JSON.stringify(again), qos: 1, retain: false });
273
- const next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
313
+ let next;
314
+ try {
315
+ next = await waitForAssignment(rid, ACK_TIMEOUT_MS);
316
+ }
317
+ catch (e) {
318
+ // Story 3.13: a refused reopen ends the tunnel and says why
319
+ this.emit('reopen_refused', { code: e?.code || e?.reason || e?.data?.reason || 'refused', details: e?.details || e?.data || null });
320
+ throw e;
321
+ }
274
322
  setA(instanceIdRef.instanceId, next);
275
323
  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
276
325
  return { relayUrl: next.relayUrl, jwt: next.jwt, leaseId: next.leaseId, relayId: next.relayId };
277
326
  };
278
327
  }
279
328
  catch (error) {
329
+ if (error?.code === 'address_in_use') {
330
+ try {
331
+ await core.end();
332
+ }
333
+ catch { }
334
+ throw error;
335
+ } // Story 1.9
280
336
  logger.error('cli.ack.wait.failed', { error: error.message, errorCode: error.code, instanceId, tunnelType: 'udp' });
281
337
  if (error.code === 'udp_relay_unavailable') {
282
338
  try {
@@ -363,6 +419,10 @@ export class UdpTunnelHandle extends LifecycleEmitter {
363
419
  }
364
420
  /** Close the data plane, then the control plane. */
365
421
  async close() {
422
+ try {
423
+ await this.goodbye(2000);
424
+ }
425
+ catch { /* Story 3.13: a goodbye never blocks a stop */ }
366
426
  try {
367
427
  this.tunnel?.close();
368
428
  }